2 Copyright (C) 2002 Richard Henderson
3 Copyright (C) 2001 Rusty Russell, 2002, 2010 Rusty Russell IBM.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include <linux/export.h>
20 #include <linux/moduleloader.h>
21 #include <linux/ftrace_event.h>
22 #include <linux/init.h>
23 #include <linux/kallsyms.h>
24 #include <linux/file.h>
26 #include <linux/sysfs.h>
27 #include <linux/kernel.h>
28 #include <linux/slab.h>
29 #include <linux/vmalloc.h>
30 #include <linux/elf.h>
31 #include <linux/proc_fs.h>
32 #include <linux/security.h>
33 #include <linux/seq_file.h>
34 #include <linux/syscalls.h>
35 #include <linux/fcntl.h>
36 #include <linux/rcupdate.h>
37 #include <linux/capability.h>
38 #include <linux/cpu.h>
39 #include <linux/moduleparam.h>
40 #include <linux/errno.h>
41 #include <linux/err.h>
42 #include <linux/vermagic.h>
43 #include <linux/notifier.h>
44 #include <linux/sched.h>
45 #include <linux/device.h>
46 #include <linux/string.h>
47 #include <linux/mutex.h>
48 #include <linux/rculist.h>
49 #include <asm/uaccess.h>
50 #include <asm/cacheflush.h>
51 #include <asm/mmu_context.h>
52 #include <linux/license.h>
53 #include <asm/sections.h>
54 #include <linux/tracepoint.h>
55 #include <linux/ftrace.h>
56 #include <linux/async.h>
57 #include <linux/percpu.h>
58 #include <linux/kmemleak.h>
59 #include <linux/jump_label.h>
60 #include <linux/pfn.h>
61 #include <linux/bsearch.h>
62 #include <uapi/linux/module.h>
63 #include "module-internal.h"
65 #define CREATE_TRACE_POINTS
66 #include <trace/events/module.h>
68 #ifndef ARCH_SHF_SMALL
69 #define ARCH_SHF_SMALL 0
73 * Modules' sections will be aligned on page boundaries
74 * to ensure complete separation of code and data, but
75 * only when CONFIG_DEBUG_SET_MODULE_RONX=y
77 #ifdef CONFIG_DEBUG_SET_MODULE_RONX
78 # define debug_align(X) ALIGN(X, PAGE_SIZE)
80 # define debug_align(X) (X)
84 * Given BASE and SIZE this macro calculates the number of pages the
85 * memory regions occupies
87 #define MOD_NUMBER_OF_PAGES(BASE, SIZE) (((SIZE) > 0) ? \
88 (PFN_DOWN((unsigned long)(BASE) + (SIZE) - 1) - \
89 PFN_DOWN((unsigned long)BASE) + 1) \
92 /* If this is set, the section belongs in the init part of the module */
93 #define INIT_OFFSET_MASK (1UL << (BITS_PER_LONG-1))
97 * 1) List of modules (also safely readable with preempt_disable),
98 * 2) module_use links,
99 * 3) module_addr_min/module_addr_max.
100 * (delete and add uses RCU list operations). */
101 DEFINE_MUTEX(module_mutex);
102 EXPORT_SYMBOL_GPL(module_mutex);
103 static LIST_HEAD(modules);
105 #ifdef CONFIG_MODULES_TREE_LOOKUP
108 * Use a latched RB-tree for __module_address(); this allows us to use
109 * RCU-sched lookups of the address from any context.
111 * Because modules have two address ranges: init and core, we need two
112 * latch_tree_nodes entries. Therefore we need the back-pointer from
115 * Because init ranges are short lived we mark them unlikely and have placed
116 * them outside the critical cacheline in struct module.
118 * This is conditional on PERF_EVENTS || TRACING because those can really hit
119 * __module_address() hard by doing a lot of stack unwinding; potentially from
123 static __always_inline unsigned long __mod_tree_val(struct latch_tree_node *n)
125 struct mod_tree_node *mtn = container_of(n, struct mod_tree_node, node);
126 struct module *mod = mtn->mod;
128 if (unlikely(mtn == &mod->mtn_init))
129 return (unsigned long)mod->module_init;
131 return (unsigned long)mod->module_core;
134 static __always_inline unsigned long __mod_tree_size(struct latch_tree_node *n)
136 struct mod_tree_node *mtn = container_of(n, struct mod_tree_node, node);
137 struct module *mod = mtn->mod;
139 if (unlikely(mtn == &mod->mtn_init))
140 return (unsigned long)mod->init_size;
142 return (unsigned long)mod->core_size;
145 static __always_inline bool
146 mod_tree_less(struct latch_tree_node *a, struct latch_tree_node *b)
148 return __mod_tree_val(a) < __mod_tree_val(b);
151 static __always_inline int
152 mod_tree_comp(void *key, struct latch_tree_node *n)
154 unsigned long val = (unsigned long)key;
155 unsigned long start, end;
157 start = __mod_tree_val(n);
161 end = start + __mod_tree_size(n);
168 static const struct latch_tree_ops mod_tree_ops = {
169 .less = mod_tree_less,
170 .comp = mod_tree_comp,
173 static struct latch_tree_root mod_tree __cacheline_aligned;
176 * These modifications: insert, remove_init and remove; are serialized by the
179 static void mod_tree_insert(struct module *mod)
181 mod->mtn_core.mod = mod;
182 mod->mtn_init.mod = mod;
184 latch_tree_insert(&mod->mtn_core.node, &mod_tree, &mod_tree_ops);
186 latch_tree_insert(&mod->mtn_init.node, &mod_tree, &mod_tree_ops);
189 static void mod_tree_remove_init(struct module *mod)
192 latch_tree_erase(&mod->mtn_init.node, &mod_tree, &mod_tree_ops);
195 static void mod_tree_remove(struct module *mod)
197 latch_tree_erase(&mod->mtn_core.node, &mod_tree, &mod_tree_ops);
198 mod_tree_remove_init(mod);
201 static struct module *mod_find(unsigned long addr)
203 struct latch_tree_node *ltn;
205 ltn = latch_tree_find((void *)addr, &mod_tree, &mod_tree_ops);
209 return container_of(ltn, struct mod_tree_node, node)->mod;
212 #else /* MODULES_TREE_LOOKUP */
214 static void mod_tree_insert(struct module *mod) { }
215 static void mod_tree_remove_init(struct module *mod) { }
216 static void mod_tree_remove(struct module *mod) { }
218 static struct module *mod_find(unsigned long addr)
222 list_for_each_entry_rcu(mod, &modules, list) {
223 if (within_module(addr, mod))
230 #endif /* MODULES_TREE_LOOKUP */
232 #ifdef CONFIG_KGDB_KDB
233 struct list_head *kdb_modules = &modules; /* kdb needs the list of modules */
234 #endif /* CONFIG_KGDB_KDB */
236 static void module_assert_mutex(void)
238 lockdep_assert_held(&module_mutex);
241 static void module_assert_mutex_or_preempt(void)
243 #ifdef CONFIG_LOCKDEP
244 if (unlikely(!debug_locks))
247 WARN_ON(!rcu_read_lock_sched_held() &&
248 !lockdep_is_held(&module_mutex));
252 #ifdef CONFIG_MODULE_SIG
253 #ifdef CONFIG_MODULE_SIG_FORCE
254 static bool sig_enforce = true;
256 static bool sig_enforce = false;
258 static int param_set_bool_enable_only(const char *val,
259 const struct kernel_param *kp)
263 struct kernel_param dummy_kp = *kp;
265 dummy_kp.arg = &test;
267 err = param_set_bool(val, &dummy_kp);
271 /* Don't let them unset it once it's set! */
272 if (!test && sig_enforce)
280 static const struct kernel_param_ops param_ops_bool_enable_only = {
281 .flags = KERNEL_PARAM_OPS_FL_NOARG,
282 .set = param_set_bool_enable_only,
283 .get = param_get_bool,
285 #define param_check_bool_enable_only param_check_bool
287 module_param(sig_enforce, bool_enable_only, 0644);
288 #endif /* !CONFIG_MODULE_SIG_FORCE */
289 #endif /* CONFIG_MODULE_SIG */
291 /* Block module loading/unloading? */
292 int modules_disabled = 0;
293 core_param(nomodule, modules_disabled, bint, 0);
295 /* Waiting for a module to finish initializing? */
296 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
298 static BLOCKING_NOTIFIER_HEAD(module_notify_list);
300 /* Bounds of module allocation, for speeding __module_address.
301 * Protected by module_mutex. */
302 static unsigned long module_addr_min = -1UL, module_addr_max = 0;
304 int register_module_notifier(struct notifier_block *nb)
306 return blocking_notifier_chain_register(&module_notify_list, nb);
308 EXPORT_SYMBOL(register_module_notifier);
310 int unregister_module_notifier(struct notifier_block *nb)
312 return blocking_notifier_chain_unregister(&module_notify_list, nb);
314 EXPORT_SYMBOL(unregister_module_notifier);
320 char *secstrings, *strtab;
321 unsigned long symoffs, stroffs;
322 struct _ddebug *debug;
323 unsigned int num_debug;
326 unsigned int sym, str, mod, vers, info, pcpu;
330 /* We require a truly strong try_module_get(): 0 means failure due to
331 ongoing or failed initialization etc. */
332 static inline int strong_try_module_get(struct module *mod)
334 BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED);
335 if (mod && mod->state == MODULE_STATE_COMING)
337 if (try_module_get(mod))
343 static inline void add_taint_module(struct module *mod, unsigned flag,
344 enum lockdep_ok lockdep_ok)
346 add_taint(flag, lockdep_ok);
347 mod->taints |= (1U << flag);
351 * A thread that wants to hold a reference to a module only while it
352 * is running can call this to safely exit. nfsd and lockd use this.
354 void __module_put_and_exit(struct module *mod, long code)
359 EXPORT_SYMBOL(__module_put_and_exit);
361 /* Find a module section: 0 means not found. */
362 static unsigned int find_sec(const struct load_info *info, const char *name)
366 for (i = 1; i < info->hdr->e_shnum; i++) {
367 Elf_Shdr *shdr = &info->sechdrs[i];
368 /* Alloc bit cleared means "ignore it." */
369 if ((shdr->sh_flags & SHF_ALLOC)
370 && strcmp(info->secstrings + shdr->sh_name, name) == 0)
376 /* Find a module section, or NULL. */
377 static void *section_addr(const struct load_info *info, const char *name)
379 /* Section 0 has sh_addr 0. */
380 return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
383 /* Find a module section, or NULL. Fill in number of "objects" in section. */
384 static void *section_objs(const struct load_info *info,
389 unsigned int sec = find_sec(info, name);
391 /* Section 0 has sh_addr 0 and sh_size 0. */
392 *num = info->sechdrs[sec].sh_size / object_size;
393 return (void *)info->sechdrs[sec].sh_addr;
396 /* Provided by the linker */
397 extern const struct kernel_symbol __start___ksymtab[];
398 extern const struct kernel_symbol __stop___ksymtab[];
399 extern const struct kernel_symbol __start___ksymtab_gpl[];
400 extern const struct kernel_symbol __stop___ksymtab_gpl[];
401 extern const struct kernel_symbol __start___ksymtab_gpl_future[];
402 extern const struct kernel_symbol __stop___ksymtab_gpl_future[];
403 extern const unsigned long __start___kcrctab[];
404 extern const unsigned long __start___kcrctab_gpl[];
405 extern const unsigned long __start___kcrctab_gpl_future[];
406 #ifdef CONFIG_UNUSED_SYMBOLS
407 extern const struct kernel_symbol __start___ksymtab_unused[];
408 extern const struct kernel_symbol __stop___ksymtab_unused[];
409 extern const struct kernel_symbol __start___ksymtab_unused_gpl[];
410 extern const struct kernel_symbol __stop___ksymtab_unused_gpl[];
411 extern const unsigned long __start___kcrctab_unused[];
412 extern const unsigned long __start___kcrctab_unused_gpl[];
415 #ifndef CONFIG_MODVERSIONS
416 #define symversion(base, idx) NULL
418 #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
421 static bool each_symbol_in_section(const struct symsearch *arr,
422 unsigned int arrsize,
423 struct module *owner,
424 bool (*fn)(const struct symsearch *syms,
425 struct module *owner,
431 for (j = 0; j < arrsize; j++) {
432 if (fn(&arr[j], owner, data))
439 /* Returns true as soon as fn returns true, otherwise false. */
440 bool each_symbol_section(bool (*fn)(const struct symsearch *arr,
441 struct module *owner,
446 static const struct symsearch arr[] = {
447 { __start___ksymtab, __stop___ksymtab, __start___kcrctab,
448 NOT_GPL_ONLY, false },
449 { __start___ksymtab_gpl, __stop___ksymtab_gpl,
450 __start___kcrctab_gpl,
452 { __start___ksymtab_gpl_future, __stop___ksymtab_gpl_future,
453 __start___kcrctab_gpl_future,
454 WILL_BE_GPL_ONLY, false },
455 #ifdef CONFIG_UNUSED_SYMBOLS
456 { __start___ksymtab_unused, __stop___ksymtab_unused,
457 __start___kcrctab_unused,
458 NOT_GPL_ONLY, true },
459 { __start___ksymtab_unused_gpl, __stop___ksymtab_unused_gpl,
460 __start___kcrctab_unused_gpl,
465 module_assert_mutex_or_preempt();
467 if (each_symbol_in_section(arr, ARRAY_SIZE(arr), NULL, fn, data))
470 list_for_each_entry_rcu(mod, &modules, list) {
471 struct symsearch arr[] = {
472 { mod->syms, mod->syms + mod->num_syms, mod->crcs,
473 NOT_GPL_ONLY, false },
474 { mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
477 { mod->gpl_future_syms,
478 mod->gpl_future_syms + mod->num_gpl_future_syms,
479 mod->gpl_future_crcs,
480 WILL_BE_GPL_ONLY, false },
481 #ifdef CONFIG_UNUSED_SYMBOLS
483 mod->unused_syms + mod->num_unused_syms,
485 NOT_GPL_ONLY, true },
486 { mod->unused_gpl_syms,
487 mod->unused_gpl_syms + mod->num_unused_gpl_syms,
488 mod->unused_gpl_crcs,
493 if (mod->state == MODULE_STATE_UNFORMED)
496 if (each_symbol_in_section(arr, ARRAY_SIZE(arr), mod, fn, data))
501 EXPORT_SYMBOL_GPL(each_symbol_section);
503 struct find_symbol_arg {
510 struct module *owner;
511 const unsigned long *crc;
512 const struct kernel_symbol *sym;
515 static bool check_symbol(const struct symsearch *syms,
516 struct module *owner,
517 unsigned int symnum, void *data)
519 struct find_symbol_arg *fsa = data;
522 if (syms->licence == GPL_ONLY)
524 if (syms->licence == WILL_BE_GPL_ONLY && fsa->warn) {
525 pr_warn("Symbol %s is being used by a non-GPL module, "
526 "which will not be allowed in the future\n",
531 #ifdef CONFIG_UNUSED_SYMBOLS
532 if (syms->unused && fsa->warn) {
533 pr_warn("Symbol %s is marked as UNUSED, however this module is "
534 "using it.\n", fsa->name);
535 pr_warn("This symbol will go away in the future.\n");
536 pr_warn("Please evaluate if this is the right api to use and "
537 "if it really is, submit a report to the linux kernel "
538 "mailing list together with submitting your code for "
544 fsa->crc = symversion(syms->crcs, symnum);
545 fsa->sym = &syms->start[symnum];
549 static int cmp_name(const void *va, const void *vb)
552 const struct kernel_symbol *b;
554 return strcmp(a, b->name);
557 static bool find_symbol_in_section(const struct symsearch *syms,
558 struct module *owner,
561 struct find_symbol_arg *fsa = data;
562 struct kernel_symbol *sym;
564 sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
565 sizeof(struct kernel_symbol), cmp_name);
567 if (sym != NULL && check_symbol(syms, owner, sym - syms->start, data))
573 /* Find a symbol and return it, along with, (optional) crc and
574 * (optional) module which owns it. Needs preempt disabled or module_mutex. */
575 const struct kernel_symbol *find_symbol(const char *name,
576 struct module **owner,
577 const unsigned long **crc,
581 struct find_symbol_arg fsa;
587 if (each_symbol_section(find_symbol_in_section, &fsa)) {
595 pr_debug("Failed to find symbol %s\n", name);
598 EXPORT_SYMBOL_GPL(find_symbol);
600 /* Search for module by name: must hold module_mutex. */
601 static struct module *find_module_all(const char *name, size_t len,
606 module_assert_mutex();
608 list_for_each_entry(mod, &modules, list) {
609 if (!even_unformed && mod->state == MODULE_STATE_UNFORMED)
611 if (strlen(mod->name) == len && !memcmp(mod->name, name, len))
617 struct module *find_module(const char *name)
619 return find_module_all(name, strlen(name), false);
621 EXPORT_SYMBOL_GPL(find_module);
625 static inline void __percpu *mod_percpu(struct module *mod)
630 static int percpu_modalloc(struct module *mod, struct load_info *info)
632 Elf_Shdr *pcpusec = &info->sechdrs[info->index.pcpu];
633 unsigned long align = pcpusec->sh_addralign;
635 if (!pcpusec->sh_size)
638 if (align > PAGE_SIZE) {
639 pr_warn("%s: per-cpu alignment %li > %li\n",
640 mod->name, align, PAGE_SIZE);
644 mod->percpu = __alloc_reserved_percpu(pcpusec->sh_size, align);
646 pr_warn("%s: Could not allocate %lu bytes percpu data\n",
647 mod->name, (unsigned long)pcpusec->sh_size);
650 mod->percpu_size = pcpusec->sh_size;
654 static void percpu_modfree(struct module *mod)
656 free_percpu(mod->percpu);
659 static unsigned int find_pcpusec(struct load_info *info)
661 return find_sec(info, ".data..percpu");
664 static void percpu_modcopy(struct module *mod,
665 const void *from, unsigned long size)
669 for_each_possible_cpu(cpu)
670 memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
674 * is_module_percpu_address - test whether address is from module static percpu
675 * @addr: address to test
677 * Test whether @addr belongs to module static percpu area.
680 * %true if @addr is from module static percpu area
682 bool is_module_percpu_address(unsigned long addr)
689 list_for_each_entry_rcu(mod, &modules, list) {
690 if (mod->state == MODULE_STATE_UNFORMED)
692 if (!mod->percpu_size)
694 for_each_possible_cpu(cpu) {
695 void *start = per_cpu_ptr(mod->percpu, cpu);
697 if ((void *)addr >= start &&
698 (void *)addr < start + mod->percpu_size) {
709 #else /* ... !CONFIG_SMP */
711 static inline void __percpu *mod_percpu(struct module *mod)
715 static int percpu_modalloc(struct module *mod, struct load_info *info)
717 /* UP modules shouldn't have this section: ENOMEM isn't quite right */
718 if (info->sechdrs[info->index.pcpu].sh_size != 0)
722 static inline void percpu_modfree(struct module *mod)
725 static unsigned int find_pcpusec(struct load_info *info)
729 static inline void percpu_modcopy(struct module *mod,
730 const void *from, unsigned long size)
732 /* pcpusec should be 0, and size of that section should be 0. */
735 bool is_module_percpu_address(unsigned long addr)
740 #endif /* CONFIG_SMP */
742 #define MODINFO_ATTR(field) \
743 static void setup_modinfo_##field(struct module *mod, const char *s) \
745 mod->field = kstrdup(s, GFP_KERNEL); \
747 static ssize_t show_modinfo_##field(struct module_attribute *mattr, \
748 struct module_kobject *mk, char *buffer) \
750 return scnprintf(buffer, PAGE_SIZE, "%s\n", mk->mod->field); \
752 static int modinfo_##field##_exists(struct module *mod) \
754 return mod->field != NULL; \
756 static void free_modinfo_##field(struct module *mod) \
761 static struct module_attribute modinfo_##field = { \
762 .attr = { .name = __stringify(field), .mode = 0444 }, \
763 .show = show_modinfo_##field, \
764 .setup = setup_modinfo_##field, \
765 .test = modinfo_##field##_exists, \
766 .free = free_modinfo_##field, \
769 MODINFO_ATTR(version);
770 MODINFO_ATTR(srcversion);
772 static char last_unloaded_module[MODULE_NAME_LEN+1];
774 #ifdef CONFIG_MODULE_UNLOAD
776 EXPORT_TRACEPOINT_SYMBOL(module_get);
778 /* MODULE_REF_BASE is the base reference count by kmodule loader. */
779 #define MODULE_REF_BASE 1
781 /* Init the unload section of the module. */
782 static int module_unload_init(struct module *mod)
785 * Initialize reference counter to MODULE_REF_BASE.
786 * refcnt == 0 means module is going.
788 atomic_set(&mod->refcnt, MODULE_REF_BASE);
790 INIT_LIST_HEAD(&mod->source_list);
791 INIT_LIST_HEAD(&mod->target_list);
793 /* Hold reference count during initialization. */
794 atomic_inc(&mod->refcnt);
799 /* Does a already use b? */
800 static int already_uses(struct module *a, struct module *b)
802 struct module_use *use;
804 list_for_each_entry(use, &b->source_list, source_list) {
805 if (use->source == a) {
806 pr_debug("%s uses %s!\n", a->name, b->name);
810 pr_debug("%s does not use %s!\n", a->name, b->name);
816 * - we add 'a' as a "source", 'b' as a "target" of module use
817 * - the module_use is added to the list of 'b' sources (so
818 * 'b' can walk the list to see who sourced them), and of 'a'
819 * targets (so 'a' can see what modules it targets).
821 static int add_module_usage(struct module *a, struct module *b)
823 struct module_use *use;
825 pr_debug("Allocating new usage for %s.\n", a->name);
826 use = kmalloc(sizeof(*use), GFP_ATOMIC);
828 pr_warn("%s: out of memory loading\n", a->name);
834 list_add(&use->source_list, &b->source_list);
835 list_add(&use->target_list, &a->target_list);
839 /* Module a uses b: caller needs module_mutex() */
840 int ref_module(struct module *a, struct module *b)
844 if (b == NULL || already_uses(a, b))
847 /* If module isn't available, we fail. */
848 err = strong_try_module_get(b);
852 err = add_module_usage(a, b);
859 EXPORT_SYMBOL_GPL(ref_module);
861 /* Clear the unload stuff of the module. */
862 static void module_unload_free(struct module *mod)
864 struct module_use *use, *tmp;
866 mutex_lock(&module_mutex);
867 list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
868 struct module *i = use->target;
869 pr_debug("%s unusing %s\n", mod->name, i->name);
871 list_del(&use->source_list);
872 list_del(&use->target_list);
875 mutex_unlock(&module_mutex);
878 #ifdef CONFIG_MODULE_FORCE_UNLOAD
879 static inline int try_force_unload(unsigned int flags)
881 int ret = (flags & O_TRUNC);
883 add_taint(TAINT_FORCED_RMMOD, LOCKDEP_NOW_UNRELIABLE);
887 static inline int try_force_unload(unsigned int flags)
891 #endif /* CONFIG_MODULE_FORCE_UNLOAD */
893 /* Try to release refcount of module, 0 means success. */
894 static int try_release_module_ref(struct module *mod)
898 /* Try to decrement refcnt which we set at loading */
899 ret = atomic_sub_return(MODULE_REF_BASE, &mod->refcnt);
902 /* Someone can put this right now, recover with checking */
903 ret = atomic_add_unless(&mod->refcnt, MODULE_REF_BASE, 0);
908 static int try_stop_module(struct module *mod, int flags, int *forced)
910 /* If it's not unused, quit unless we're forcing. */
911 if (try_release_module_ref(mod) != 0) {
912 *forced = try_force_unload(flags);
917 /* Mark it as dying. */
918 mod->state = MODULE_STATE_GOING;
924 * module_refcount - return the refcount or -1 if unloading
926 * @mod: the module we're checking
929 * -1 if the module is in the process of unloading
930 * otherwise the number of references in the kernel to the module
932 int module_refcount(struct module *mod)
934 return atomic_read(&mod->refcnt) - MODULE_REF_BASE;
936 EXPORT_SYMBOL(module_refcount);
938 /* This exists whether we can unload or not */
939 static void free_module(struct module *mod);
941 SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
945 char name[MODULE_NAME_LEN];
948 if (!capable(CAP_SYS_MODULE) || modules_disabled)
951 if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
953 name[MODULE_NAME_LEN-1] = '\0';
955 if (mutex_lock_interruptible(&module_mutex) != 0)
958 mod = find_module(name);
964 if (!list_empty(&mod->source_list)) {
965 /* Other modules depend on us: get rid of them first. */
970 /* Doing init or already dying? */
971 if (mod->state != MODULE_STATE_LIVE) {
972 /* FIXME: if (force), slam module count damn the torpedoes */
973 pr_debug("%s already dying\n", mod->name);
978 /* If it has an init func, it must have an exit func to unload */
979 if (mod->init && !mod->exit) {
980 forced = try_force_unload(flags);
982 /* This module can't be removed */
988 /* Stop the machine so refcounts can't move and disable module. */
989 ret = try_stop_module(mod, flags, &forced);
993 mutex_unlock(&module_mutex);
994 /* Final destruction now no one is using it. */
995 if (mod->exit != NULL)
997 blocking_notifier_call_chain(&module_notify_list,
998 MODULE_STATE_GOING, mod);
999 async_synchronize_full();
1001 /* Store the name of the last unloaded module for diagnostic purposes */
1002 strlcpy(last_unloaded_module, mod->name, sizeof(last_unloaded_module));
1007 mutex_unlock(&module_mutex);
1011 static inline void print_unload_info(struct seq_file *m, struct module *mod)
1013 struct module_use *use;
1014 int printed_something = 0;
1016 seq_printf(m, " %i ", module_refcount(mod));
1019 * Always include a trailing , so userspace can differentiate
1020 * between this and the old multi-field proc format.
1022 list_for_each_entry(use, &mod->source_list, source_list) {
1023 printed_something = 1;
1024 seq_printf(m, "%s,", use->source->name);
1027 if (mod->init != NULL && mod->exit == NULL) {
1028 printed_something = 1;
1029 seq_puts(m, "[permanent],");
1032 if (!printed_something)
1036 void __symbol_put(const char *symbol)
1038 struct module *owner;
1041 if (!find_symbol(symbol, &owner, NULL, true, false))
1046 EXPORT_SYMBOL(__symbol_put);
1048 /* Note this assumes addr is a function, which it currently always is. */
1049 void symbol_put_addr(void *addr)
1051 struct module *modaddr;
1052 unsigned long a = (unsigned long)dereference_function_descriptor(addr);
1054 if (core_kernel_text(a))
1057 /* module_text_address is safe here: we're supposed to have reference
1058 * to module from symbol_get, so it can't go away. */
1059 modaddr = __module_text_address(a);
1061 module_put(modaddr);
1063 EXPORT_SYMBOL_GPL(symbol_put_addr);
1065 static ssize_t show_refcnt(struct module_attribute *mattr,
1066 struct module_kobject *mk, char *buffer)
1068 return sprintf(buffer, "%i\n", module_refcount(mk->mod));
1071 static struct module_attribute modinfo_refcnt =
1072 __ATTR(refcnt, 0444, show_refcnt, NULL);
1074 void __module_get(struct module *module)
1078 atomic_inc(&module->refcnt);
1079 trace_module_get(module, _RET_IP_);
1083 EXPORT_SYMBOL(__module_get);
1085 bool try_module_get(struct module *module)
1091 /* Note: here, we can fail to get a reference */
1092 if (likely(module_is_live(module) &&
1093 atomic_inc_not_zero(&module->refcnt) != 0))
1094 trace_module_get(module, _RET_IP_);
1102 EXPORT_SYMBOL(try_module_get);
1104 void module_put(struct module *module)
1110 ret = atomic_dec_if_positive(&module->refcnt);
1111 WARN_ON(ret < 0); /* Failed to put refcount */
1112 trace_module_put(module, _RET_IP_);
1116 EXPORT_SYMBOL(module_put);
1118 #else /* !CONFIG_MODULE_UNLOAD */
1119 static inline void print_unload_info(struct seq_file *m, struct module *mod)
1121 /* We don't know the usage count, or what modules are using. */
1122 seq_puts(m, " - -");
1125 static inline void module_unload_free(struct module *mod)
1129 int ref_module(struct module *a, struct module *b)
1131 return strong_try_module_get(b);
1133 EXPORT_SYMBOL_GPL(ref_module);
1135 static inline int module_unload_init(struct module *mod)
1139 #endif /* CONFIG_MODULE_UNLOAD */
1141 static size_t module_flags_taint(struct module *mod, char *buf)
1145 if (mod->taints & (1 << TAINT_PROPRIETARY_MODULE))
1147 if (mod->taints & (1 << TAINT_OOT_MODULE))
1149 if (mod->taints & (1 << TAINT_FORCED_MODULE))
1151 if (mod->taints & (1 << TAINT_CRAP))
1153 if (mod->taints & (1 << TAINT_UNSIGNED_MODULE))
1156 * TAINT_FORCED_RMMOD: could be added.
1157 * TAINT_CPU_OUT_OF_SPEC, TAINT_MACHINE_CHECK, TAINT_BAD_PAGE don't
1163 static ssize_t show_initstate(struct module_attribute *mattr,
1164 struct module_kobject *mk, char *buffer)
1166 const char *state = "unknown";
1168 switch (mk->mod->state) {
1169 case MODULE_STATE_LIVE:
1172 case MODULE_STATE_COMING:
1175 case MODULE_STATE_GOING:
1181 return sprintf(buffer, "%s\n", state);
1184 static struct module_attribute modinfo_initstate =
1185 __ATTR(initstate, 0444, show_initstate, NULL);
1187 static ssize_t store_uevent(struct module_attribute *mattr,
1188 struct module_kobject *mk,
1189 const char *buffer, size_t count)
1191 enum kobject_action action;
1193 if (kobject_action_type(buffer, count, &action) == 0)
1194 kobject_uevent(&mk->kobj, action);
1198 struct module_attribute module_uevent =
1199 __ATTR(uevent, 0200, NULL, store_uevent);
1201 static ssize_t show_coresize(struct module_attribute *mattr,
1202 struct module_kobject *mk, char *buffer)
1204 return sprintf(buffer, "%u\n", mk->mod->core_size);
1207 static struct module_attribute modinfo_coresize =
1208 __ATTR(coresize, 0444, show_coresize, NULL);
1210 static ssize_t show_initsize(struct module_attribute *mattr,
1211 struct module_kobject *mk, char *buffer)
1213 return sprintf(buffer, "%u\n", mk->mod->init_size);
1216 static struct module_attribute modinfo_initsize =
1217 __ATTR(initsize, 0444, show_initsize, NULL);
1219 static ssize_t show_taint(struct module_attribute *mattr,
1220 struct module_kobject *mk, char *buffer)
1224 l = module_flags_taint(mk->mod, buffer);
1229 static struct module_attribute modinfo_taint =
1230 __ATTR(taint, 0444, show_taint, NULL);
1232 static struct module_attribute *modinfo_attrs[] = {
1235 &modinfo_srcversion,
1240 #ifdef CONFIG_MODULE_UNLOAD
1246 static const char vermagic[] = VERMAGIC_STRING;
1248 static int try_to_force_load(struct module *mod, const char *reason)
1250 #ifdef CONFIG_MODULE_FORCE_LOAD
1251 if (!test_taint(TAINT_FORCED_MODULE))
1252 pr_warn("%s: %s: kernel tainted.\n", mod->name, reason);
1253 add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE);
1260 #ifdef CONFIG_MODVERSIONS
1261 /* If the arch applies (non-zero) relocations to kernel kcrctab, unapply it. */
1262 static unsigned long maybe_relocated(unsigned long crc,
1263 const struct module *crc_owner)
1265 #ifdef ARCH_RELOCATES_KCRCTAB
1266 if (crc_owner == NULL)
1267 return crc - (unsigned long)reloc_start;
1272 static int check_version(Elf_Shdr *sechdrs,
1273 unsigned int versindex,
1274 const char *symname,
1276 const unsigned long *crc,
1277 const struct module *crc_owner)
1279 unsigned int i, num_versions;
1280 struct modversion_info *versions;
1282 /* Exporting module didn't supply crcs? OK, we're already tainted. */
1286 /* No versions at all? modprobe --force does this. */
1288 return try_to_force_load(mod, symname) == 0;
1290 versions = (void *) sechdrs[versindex].sh_addr;
1291 num_versions = sechdrs[versindex].sh_size
1292 / sizeof(struct modversion_info);
1294 for (i = 0; i < num_versions; i++) {
1295 if (strcmp(versions[i].name, symname) != 0)
1298 if (versions[i].crc == maybe_relocated(*crc, crc_owner))
1300 pr_debug("Found checksum %lX vs module %lX\n",
1301 maybe_relocated(*crc, crc_owner), versions[i].crc);
1305 pr_warn("%s: no symbol version for %s\n", mod->name, symname);
1309 pr_warn("%s: disagrees about version of symbol %s\n",
1310 mod->name, symname);
1314 static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1315 unsigned int versindex,
1318 const unsigned long *crc;
1321 * Since this should be found in kernel (which can't be removed), no
1322 * locking is necessary -- use preempt_disable() to placate lockdep.
1325 if (!find_symbol(VMLINUX_SYMBOL_STR(module_layout), NULL,
1326 &crc, true, false)) {
1331 return check_version(sechdrs, versindex,
1332 VMLINUX_SYMBOL_STR(module_layout), mod, crc,
1336 /* First part is kernel version, which we ignore if module has crcs. */
1337 static inline int same_magic(const char *amagic, const char *bmagic,
1341 amagic += strcspn(amagic, " ");
1342 bmagic += strcspn(bmagic, " ");
1344 return strcmp(amagic, bmagic) == 0;
1347 static inline int check_version(Elf_Shdr *sechdrs,
1348 unsigned int versindex,
1349 const char *symname,
1351 const unsigned long *crc,
1352 const struct module *crc_owner)
1357 static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1358 unsigned int versindex,
1364 static inline int same_magic(const char *amagic, const char *bmagic,
1367 return strcmp(amagic, bmagic) == 0;
1369 #endif /* CONFIG_MODVERSIONS */
1371 /* Resolve a symbol for this module. I.e. if we find one, record usage. */
1372 static const struct kernel_symbol *resolve_symbol(struct module *mod,
1373 const struct load_info *info,
1377 struct module *owner;
1378 const struct kernel_symbol *sym;
1379 const unsigned long *crc;
1383 * The module_mutex should not be a heavily contended lock;
1384 * if we get the occasional sleep here, we'll go an extra iteration
1385 * in the wait_event_interruptible(), which is harmless.
1387 sched_annotate_sleep();
1388 mutex_lock(&module_mutex);
1389 sym = find_symbol(name, &owner, &crc,
1390 !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)), true);
1394 if (!check_version(info->sechdrs, info->index.vers, name, mod, crc,
1396 sym = ERR_PTR(-EINVAL);
1400 err = ref_module(mod, owner);
1407 /* We must make copy under the lock if we failed to get ref. */
1408 strncpy(ownername, module_name(owner), MODULE_NAME_LEN);
1410 mutex_unlock(&module_mutex);
1414 static const struct kernel_symbol *
1415 resolve_symbol_wait(struct module *mod,
1416 const struct load_info *info,
1419 const struct kernel_symbol *ksym;
1420 char owner[MODULE_NAME_LEN];
1422 if (wait_event_interruptible_timeout(module_wq,
1423 !IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1424 || PTR_ERR(ksym) != -EBUSY,
1426 pr_warn("%s: gave up waiting for init of module %s.\n",
1433 * /sys/module/foo/sections stuff
1434 * J. Corbet <corbet@lwn.net>
1438 #ifdef CONFIG_KALLSYMS
1439 static inline bool sect_empty(const Elf_Shdr *sect)
1441 return !(sect->sh_flags & SHF_ALLOC) || sect->sh_size == 0;
1444 struct module_sect_attr {
1445 struct module_attribute mattr;
1447 unsigned long address;
1450 struct module_sect_attrs {
1451 struct attribute_group grp;
1452 unsigned int nsections;
1453 struct module_sect_attr attrs[0];
1456 static ssize_t module_sect_show(struct module_attribute *mattr,
1457 struct module_kobject *mk, char *buf)
1459 struct module_sect_attr *sattr =
1460 container_of(mattr, struct module_sect_attr, mattr);
1461 return sprintf(buf, "0x%pK\n", (void *)sattr->address);
1464 static void free_sect_attrs(struct module_sect_attrs *sect_attrs)
1466 unsigned int section;
1468 for (section = 0; section < sect_attrs->nsections; section++)
1469 kfree(sect_attrs->attrs[section].name);
1473 static void add_sect_attrs(struct module *mod, const struct load_info *info)
1475 unsigned int nloaded = 0, i, size[2];
1476 struct module_sect_attrs *sect_attrs;
1477 struct module_sect_attr *sattr;
1478 struct attribute **gattr;
1480 /* Count loaded sections and allocate structures */
1481 for (i = 0; i < info->hdr->e_shnum; i++)
1482 if (!sect_empty(&info->sechdrs[i]))
1484 size[0] = ALIGN(sizeof(*sect_attrs)
1485 + nloaded * sizeof(sect_attrs->attrs[0]),
1486 sizeof(sect_attrs->grp.attrs[0]));
1487 size[1] = (nloaded + 1) * sizeof(sect_attrs->grp.attrs[0]);
1488 sect_attrs = kzalloc(size[0] + size[1], GFP_KERNEL);
1489 if (sect_attrs == NULL)
1492 /* Setup section attributes. */
1493 sect_attrs->grp.name = "sections";
1494 sect_attrs->grp.attrs = (void *)sect_attrs + size[0];
1496 sect_attrs->nsections = 0;
1497 sattr = §_attrs->attrs[0];
1498 gattr = §_attrs->grp.attrs[0];
1499 for (i = 0; i < info->hdr->e_shnum; i++) {
1500 Elf_Shdr *sec = &info->sechdrs[i];
1501 if (sect_empty(sec))
1503 sattr->address = sec->sh_addr;
1504 sattr->name = kstrdup(info->secstrings + sec->sh_name,
1506 if (sattr->name == NULL)
1508 sect_attrs->nsections++;
1509 sysfs_attr_init(&sattr->mattr.attr);
1510 sattr->mattr.show = module_sect_show;
1511 sattr->mattr.store = NULL;
1512 sattr->mattr.attr.name = sattr->name;
1513 sattr->mattr.attr.mode = S_IRUGO;
1514 *(gattr++) = &(sattr++)->mattr.attr;
1518 if (sysfs_create_group(&mod->mkobj.kobj, §_attrs->grp))
1521 mod->sect_attrs = sect_attrs;
1524 free_sect_attrs(sect_attrs);
1527 static void remove_sect_attrs(struct module *mod)
1529 if (mod->sect_attrs) {
1530 sysfs_remove_group(&mod->mkobj.kobj,
1531 &mod->sect_attrs->grp);
1532 /* We are positive that no one is using any sect attrs
1533 * at this point. Deallocate immediately. */
1534 free_sect_attrs(mod->sect_attrs);
1535 mod->sect_attrs = NULL;
1540 * /sys/module/foo/notes/.section.name gives contents of SHT_NOTE sections.
1543 struct module_notes_attrs {
1544 struct kobject *dir;
1546 struct bin_attribute attrs[0];
1549 static ssize_t module_notes_read(struct file *filp, struct kobject *kobj,
1550 struct bin_attribute *bin_attr,
1551 char *buf, loff_t pos, size_t count)
1554 * The caller checked the pos and count against our size.
1556 memcpy(buf, bin_attr->private + pos, count);
1560 static void free_notes_attrs(struct module_notes_attrs *notes_attrs,
1563 if (notes_attrs->dir) {
1565 sysfs_remove_bin_file(notes_attrs->dir,
1566 ¬es_attrs->attrs[i]);
1567 kobject_put(notes_attrs->dir);
1572 static void add_notes_attrs(struct module *mod, const struct load_info *info)
1574 unsigned int notes, loaded, i;
1575 struct module_notes_attrs *notes_attrs;
1576 struct bin_attribute *nattr;
1578 /* failed to create section attributes, so can't create notes */
1579 if (!mod->sect_attrs)
1582 /* Count notes sections and allocate structures. */
1584 for (i = 0; i < info->hdr->e_shnum; i++)
1585 if (!sect_empty(&info->sechdrs[i]) &&
1586 (info->sechdrs[i].sh_type == SHT_NOTE))
1592 notes_attrs = kzalloc(sizeof(*notes_attrs)
1593 + notes * sizeof(notes_attrs->attrs[0]),
1595 if (notes_attrs == NULL)
1598 notes_attrs->notes = notes;
1599 nattr = ¬es_attrs->attrs[0];
1600 for (loaded = i = 0; i < info->hdr->e_shnum; ++i) {
1601 if (sect_empty(&info->sechdrs[i]))
1603 if (info->sechdrs[i].sh_type == SHT_NOTE) {
1604 sysfs_bin_attr_init(nattr);
1605 nattr->attr.name = mod->sect_attrs->attrs[loaded].name;
1606 nattr->attr.mode = S_IRUGO;
1607 nattr->size = info->sechdrs[i].sh_size;
1608 nattr->private = (void *) info->sechdrs[i].sh_addr;
1609 nattr->read = module_notes_read;
1615 notes_attrs->dir = kobject_create_and_add("notes", &mod->mkobj.kobj);
1616 if (!notes_attrs->dir)
1619 for (i = 0; i < notes; ++i)
1620 if (sysfs_create_bin_file(notes_attrs->dir,
1621 ¬es_attrs->attrs[i]))
1624 mod->notes_attrs = notes_attrs;
1628 free_notes_attrs(notes_attrs, i);
1631 static void remove_notes_attrs(struct module *mod)
1633 if (mod->notes_attrs)
1634 free_notes_attrs(mod->notes_attrs, mod->notes_attrs->notes);
1639 static inline void add_sect_attrs(struct module *mod,
1640 const struct load_info *info)
1644 static inline void remove_sect_attrs(struct module *mod)
1648 static inline void add_notes_attrs(struct module *mod,
1649 const struct load_info *info)
1653 static inline void remove_notes_attrs(struct module *mod)
1656 #endif /* CONFIG_KALLSYMS */
1658 static void add_usage_links(struct module *mod)
1660 #ifdef CONFIG_MODULE_UNLOAD
1661 struct module_use *use;
1664 mutex_lock(&module_mutex);
1665 list_for_each_entry(use, &mod->target_list, target_list) {
1666 nowarn = sysfs_create_link(use->target->holders_dir,
1667 &mod->mkobj.kobj, mod->name);
1669 mutex_unlock(&module_mutex);
1673 static void del_usage_links(struct module *mod)
1675 #ifdef CONFIG_MODULE_UNLOAD
1676 struct module_use *use;
1678 mutex_lock(&module_mutex);
1679 list_for_each_entry(use, &mod->target_list, target_list)
1680 sysfs_remove_link(use->target->holders_dir, mod->name);
1681 mutex_unlock(&module_mutex);
1685 static int module_add_modinfo_attrs(struct module *mod)
1687 struct module_attribute *attr;
1688 struct module_attribute *temp_attr;
1692 mod->modinfo_attrs = kzalloc((sizeof(struct module_attribute) *
1693 (ARRAY_SIZE(modinfo_attrs) + 1)),
1695 if (!mod->modinfo_attrs)
1698 temp_attr = mod->modinfo_attrs;
1699 for (i = 0; (attr = modinfo_attrs[i]) && !error; i++) {
1701 (attr->test && attr->test(mod))) {
1702 memcpy(temp_attr, attr, sizeof(*temp_attr));
1703 sysfs_attr_init(&temp_attr->attr);
1704 error = sysfs_create_file(&mod->mkobj.kobj,
1712 static void module_remove_modinfo_attrs(struct module *mod)
1714 struct module_attribute *attr;
1717 for (i = 0; (attr = &mod->modinfo_attrs[i]); i++) {
1718 /* pick a field to test for end of list */
1719 if (!attr->attr.name)
1721 sysfs_remove_file(&mod->mkobj.kobj, &attr->attr);
1725 kfree(mod->modinfo_attrs);
1728 static void mod_kobject_put(struct module *mod)
1730 DECLARE_COMPLETION_ONSTACK(c);
1731 mod->mkobj.kobj_completion = &c;
1732 kobject_put(&mod->mkobj.kobj);
1733 wait_for_completion(&c);
1736 static int mod_sysfs_init(struct module *mod)
1739 struct kobject *kobj;
1741 if (!module_sysfs_initialized) {
1742 pr_err("%s: module sysfs not initialized\n", mod->name);
1747 kobj = kset_find_obj(module_kset, mod->name);
1749 pr_err("%s: module is already loaded\n", mod->name);
1755 mod->mkobj.mod = mod;
1757 memset(&mod->mkobj.kobj, 0, sizeof(mod->mkobj.kobj));
1758 mod->mkobj.kobj.kset = module_kset;
1759 err = kobject_init_and_add(&mod->mkobj.kobj, &module_ktype, NULL,
1762 mod_kobject_put(mod);
1764 /* delay uevent until full sysfs population */
1769 static int mod_sysfs_setup(struct module *mod,
1770 const struct load_info *info,
1771 struct kernel_param *kparam,
1772 unsigned int num_params)
1776 err = mod_sysfs_init(mod);
1780 mod->holders_dir = kobject_create_and_add("holders", &mod->mkobj.kobj);
1781 if (!mod->holders_dir) {
1786 err = module_param_sysfs_setup(mod, kparam, num_params);
1788 goto out_unreg_holders;
1790 err = module_add_modinfo_attrs(mod);
1792 goto out_unreg_param;
1794 add_usage_links(mod);
1795 add_sect_attrs(mod, info);
1796 add_notes_attrs(mod, info);
1798 kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
1802 module_param_sysfs_remove(mod);
1804 kobject_put(mod->holders_dir);
1806 mod_kobject_put(mod);
1811 static void mod_sysfs_fini(struct module *mod)
1813 remove_notes_attrs(mod);
1814 remove_sect_attrs(mod);
1815 mod_kobject_put(mod);
1818 #else /* !CONFIG_SYSFS */
1820 static int mod_sysfs_setup(struct module *mod,
1821 const struct load_info *info,
1822 struct kernel_param *kparam,
1823 unsigned int num_params)
1828 static void mod_sysfs_fini(struct module *mod)
1832 static void module_remove_modinfo_attrs(struct module *mod)
1836 static void del_usage_links(struct module *mod)
1840 #endif /* CONFIG_SYSFS */
1842 static void mod_sysfs_teardown(struct module *mod)
1844 del_usage_links(mod);
1845 module_remove_modinfo_attrs(mod);
1846 module_param_sysfs_remove(mod);
1847 kobject_put(mod->mkobj.drivers_dir);
1848 kobject_put(mod->holders_dir);
1849 mod_sysfs_fini(mod);
1852 #ifdef CONFIG_DEBUG_SET_MODULE_RONX
1854 * LKM RO/NX protection: protect module's text/ro-data
1855 * from modification and any data from execution.
1857 void set_page_attributes(void *start, void *end, int (*set)(unsigned long start, int num_pages))
1859 unsigned long begin_pfn = PFN_DOWN((unsigned long)start);
1860 unsigned long end_pfn = PFN_DOWN((unsigned long)end);
1862 if (end_pfn > begin_pfn)
1863 set(begin_pfn << PAGE_SHIFT, end_pfn - begin_pfn);
1866 static void set_section_ro_nx(void *base,
1867 unsigned long text_size,
1868 unsigned long ro_size,
1869 unsigned long total_size)
1871 /* begin and end PFNs of the current subsection */
1872 unsigned long begin_pfn;
1873 unsigned long end_pfn;
1876 * Set RO for module text and RO-data:
1877 * - Always protect first page.
1878 * - Do not protect last partial page.
1881 set_page_attributes(base, base + ro_size, set_memory_ro);
1884 * Set NX permissions for module data:
1885 * - Do not protect first partial page.
1886 * - Always protect last page.
1888 if (total_size > text_size) {
1889 begin_pfn = PFN_UP((unsigned long)base + text_size);
1890 end_pfn = PFN_UP((unsigned long)base + total_size);
1891 if (end_pfn > begin_pfn)
1892 set_memory_nx(begin_pfn << PAGE_SHIFT, end_pfn - begin_pfn);
1896 static void unset_module_core_ro_nx(struct module *mod)
1898 set_page_attributes(mod->module_core + mod->core_text_size,
1899 mod->module_core + mod->core_size,
1901 set_page_attributes(mod->module_core,
1902 mod->module_core + mod->core_ro_size,
1906 static void unset_module_init_ro_nx(struct module *mod)
1908 set_page_attributes(mod->module_init + mod->init_text_size,
1909 mod->module_init + mod->init_size,
1911 set_page_attributes(mod->module_init,
1912 mod->module_init + mod->init_ro_size,
1916 /* Iterate through all modules and set each module's text as RW */
1917 void set_all_modules_text_rw(void)
1921 mutex_lock(&module_mutex);
1922 list_for_each_entry_rcu(mod, &modules, list) {
1923 if (mod->state == MODULE_STATE_UNFORMED)
1925 if ((mod->module_core) && (mod->core_text_size)) {
1926 set_page_attributes(mod->module_core,
1927 mod->module_core + mod->core_text_size,
1930 if ((mod->module_init) && (mod->init_text_size)) {
1931 set_page_attributes(mod->module_init,
1932 mod->module_init + mod->init_text_size,
1936 mutex_unlock(&module_mutex);
1939 /* Iterate through all modules and set each module's text as RO */
1940 void set_all_modules_text_ro(void)
1944 mutex_lock(&module_mutex);
1945 list_for_each_entry_rcu(mod, &modules, list) {
1946 if (mod->state == MODULE_STATE_UNFORMED)
1948 if ((mod->module_core) && (mod->core_text_size)) {
1949 set_page_attributes(mod->module_core,
1950 mod->module_core + mod->core_text_size,
1953 if ((mod->module_init) && (mod->init_text_size)) {
1954 set_page_attributes(mod->module_init,
1955 mod->module_init + mod->init_text_size,
1959 mutex_unlock(&module_mutex);
1962 static inline void set_section_ro_nx(void *base, unsigned long text_size, unsigned long ro_size, unsigned long total_size) { }
1963 static void unset_module_core_ro_nx(struct module *mod) { }
1964 static void unset_module_init_ro_nx(struct module *mod) { }
1967 void __weak module_memfree(void *module_region)
1969 vfree(module_region);
1972 void __weak module_arch_cleanup(struct module *mod)
1976 void __weak module_arch_freeing_init(struct module *mod)
1980 /* Free a module, remove from lists, etc. */
1981 static void free_module(struct module *mod)
1983 trace_module_free(mod);
1985 mod_sysfs_teardown(mod);
1987 /* We leave it in list to prevent duplicate loads, but make sure
1988 * that noone uses it while it's being deconstructed. */
1989 mutex_lock(&module_mutex);
1990 mod->state = MODULE_STATE_UNFORMED;
1991 mutex_unlock(&module_mutex);
1993 /* Remove dynamic debug info */
1994 ddebug_remove_module(mod->name);
1996 /* Arch-specific cleanup. */
1997 module_arch_cleanup(mod);
1999 /* Module unload stuff */
2000 module_unload_free(mod);
2002 /* Free any allocated parameters. */
2003 destroy_params(mod->kp, mod->num_kp);
2005 /* Now we can delete it from the lists */
2006 mutex_lock(&module_mutex);
2007 /* Unlink carefully: kallsyms could be walking list. */
2008 list_del_rcu(&mod->list);
2009 mod_tree_remove(mod);
2010 /* Remove this module from bug list, this uses list_del_rcu */
2011 module_bug_cleanup(mod);
2012 /* Wait for RCU-sched synchronizing before releasing mod->list and buglist. */
2013 synchronize_sched();
2014 mutex_unlock(&module_mutex);
2016 /* This may be NULL, but that's OK */
2017 unset_module_init_ro_nx(mod);
2018 module_arch_freeing_init(mod);
2019 module_memfree(mod->module_init);
2021 percpu_modfree(mod);
2023 /* Free lock-classes; relies on the preceding sync_rcu(). */
2024 lockdep_free_key_range(mod->module_core, mod->core_size);
2026 /* Finally, free the core (containing the module structure) */
2027 unset_module_core_ro_nx(mod);
2028 module_memfree(mod->module_core);
2031 update_protections(current->mm);
2035 void *__symbol_get(const char *symbol)
2037 struct module *owner;
2038 const struct kernel_symbol *sym;
2041 sym = find_symbol(symbol, &owner, NULL, true, true);
2042 if (sym && strong_try_module_get(owner))
2046 return sym ? (void *)sym->value : NULL;
2048 EXPORT_SYMBOL_GPL(__symbol_get);
2051 * Ensure that an exported symbol [global namespace] does not already exist
2052 * in the kernel or in some other module's exported symbol table.
2054 * You must hold the module_mutex.
2056 static int verify_export_symbols(struct module *mod)
2059 struct module *owner;
2060 const struct kernel_symbol *s;
2062 const struct kernel_symbol *sym;
2065 { mod->syms, mod->num_syms },
2066 { mod->gpl_syms, mod->num_gpl_syms },
2067 { mod->gpl_future_syms, mod->num_gpl_future_syms },
2068 #ifdef CONFIG_UNUSED_SYMBOLS
2069 { mod->unused_syms, mod->num_unused_syms },
2070 { mod->unused_gpl_syms, mod->num_unused_gpl_syms },
2074 for (i = 0; i < ARRAY_SIZE(arr); i++) {
2075 for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
2076 if (find_symbol(s->name, &owner, NULL, true, false)) {
2077 pr_err("%s: exports duplicate symbol %s"
2079 mod->name, s->name, module_name(owner));
2087 /* Change all symbols so that st_value encodes the pointer directly. */
2088 static int simplify_symbols(struct module *mod, const struct load_info *info)
2090 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2091 Elf_Sym *sym = (void *)symsec->sh_addr;
2092 unsigned long secbase;
2095 const struct kernel_symbol *ksym;
2097 for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
2098 const char *name = info->strtab + sym[i].st_name;
2100 switch (sym[i].st_shndx) {
2102 /* Ignore common symbols */
2103 if (!strncmp(name, "__gnu_lto", 9))
2106 /* We compiled with -fno-common. These are not
2107 supposed to happen. */
2108 pr_debug("Common symbol: %s\n", name);
2109 pr_warn("%s: please compile with -fno-common\n",
2115 /* Don't need to do anything */
2116 pr_debug("Absolute symbol: 0x%08lx\n",
2117 (long)sym[i].st_value);
2121 ksym = resolve_symbol_wait(mod, info, name);
2122 /* Ok if resolved. */
2123 if (ksym && !IS_ERR(ksym)) {
2124 sym[i].st_value = ksym->value;
2129 if (!ksym && ELF_ST_BIND(sym[i].st_info) == STB_WEAK)
2132 pr_warn("%s: Unknown symbol %s (err %li)\n",
2133 mod->name, name, PTR_ERR(ksym));
2134 ret = PTR_ERR(ksym) ?: -ENOENT;
2138 /* Divert to percpu allocation if a percpu var. */
2139 if (sym[i].st_shndx == info->index.pcpu)
2140 secbase = (unsigned long)mod_percpu(mod);
2142 secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
2143 sym[i].st_value += secbase;
2151 static int apply_relocations(struct module *mod, const struct load_info *info)
2156 /* Now do relocations. */
2157 for (i = 1; i < info->hdr->e_shnum; i++) {
2158 unsigned int infosec = info->sechdrs[i].sh_info;
2160 /* Not a valid relocation section? */
2161 if (infosec >= info->hdr->e_shnum)
2164 /* Don't bother with non-allocated sections */
2165 if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
2168 if (info->sechdrs[i].sh_type == SHT_REL)
2169 err = apply_relocate(info->sechdrs, info->strtab,
2170 info->index.sym, i, mod);
2171 else if (info->sechdrs[i].sh_type == SHT_RELA)
2172 err = apply_relocate_add(info->sechdrs, info->strtab,
2173 info->index.sym, i, mod);
2180 /* Additional bytes needed by arch in front of individual sections */
2181 unsigned int __weak arch_mod_section_prepend(struct module *mod,
2182 unsigned int section)
2184 /* default implementation just returns zero */
2188 /* Update size with this section: return offset. */
2189 static long get_offset(struct module *mod, unsigned int *size,
2190 Elf_Shdr *sechdr, unsigned int section)
2194 *size += arch_mod_section_prepend(mod, section);
2195 ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
2196 *size = ret + sechdr->sh_size;
2200 /* Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
2201 might -- code, read-only data, read-write data, small data. Tally
2202 sizes, and place the offsets into sh_entsize fields: high bit means it
2204 static void layout_sections(struct module *mod, struct load_info *info)
2206 static unsigned long const masks[][2] = {
2207 /* NOTE: all executable code must be the first section
2208 * in this array; otherwise modify the text_size
2209 * finder in the two loops below */
2210 { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
2211 { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
2212 { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
2213 { ARCH_SHF_SMALL | SHF_ALLOC, 0 }
2217 for (i = 0; i < info->hdr->e_shnum; i++)
2218 info->sechdrs[i].sh_entsize = ~0UL;
2220 pr_debug("Core section allocation order:\n");
2221 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2222 for (i = 0; i < info->hdr->e_shnum; ++i) {
2223 Elf_Shdr *s = &info->sechdrs[i];
2224 const char *sname = info->secstrings + s->sh_name;
2226 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2227 || (s->sh_flags & masks[m][1])
2228 || s->sh_entsize != ~0UL
2229 || strstarts(sname, ".init"))
2231 s->sh_entsize = get_offset(mod, &mod->core_size, s, i);
2232 pr_debug("\t%s\n", sname);
2235 case 0: /* executable */
2236 mod->core_size = debug_align(mod->core_size);
2237 mod->core_text_size = mod->core_size;
2239 case 1: /* RO: text and ro-data */
2240 mod->core_size = debug_align(mod->core_size);
2241 mod->core_ro_size = mod->core_size;
2243 case 3: /* whole core */
2244 mod->core_size = debug_align(mod->core_size);
2249 pr_debug("Init section allocation order:\n");
2250 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2251 for (i = 0; i < info->hdr->e_shnum; ++i) {
2252 Elf_Shdr *s = &info->sechdrs[i];
2253 const char *sname = info->secstrings + s->sh_name;
2255 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2256 || (s->sh_flags & masks[m][1])
2257 || s->sh_entsize != ~0UL
2258 || !strstarts(sname, ".init"))
2260 s->sh_entsize = (get_offset(mod, &mod->init_size, s, i)
2261 | INIT_OFFSET_MASK);
2262 pr_debug("\t%s\n", sname);
2265 case 0: /* executable */
2266 mod->init_size = debug_align(mod->init_size);
2267 mod->init_text_size = mod->init_size;
2269 case 1: /* RO: text and ro-data */
2270 mod->init_size = debug_align(mod->init_size);
2271 mod->init_ro_size = mod->init_size;
2273 case 3: /* whole init */
2274 mod->init_size = debug_align(mod->init_size);
2280 static void set_license(struct module *mod, const char *license)
2283 license = "unspecified";
2285 if (!license_is_gpl_compatible(license)) {
2286 if (!test_taint(TAINT_PROPRIETARY_MODULE))
2287 pr_warn("%s: module license '%s' taints kernel.\n",
2288 mod->name, license);
2289 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2290 LOCKDEP_NOW_UNRELIABLE);
2294 /* Parse tag=value strings from .modinfo section */
2295 static char *next_string(char *string, unsigned long *secsize)
2297 /* Skip non-zero chars */
2300 if ((*secsize)-- <= 1)
2304 /* Skip any zero padding. */
2305 while (!string[0]) {
2307 if ((*secsize)-- <= 1)
2313 static char *get_modinfo(struct load_info *info, const char *tag)
2316 unsigned int taglen = strlen(tag);
2317 Elf_Shdr *infosec = &info->sechdrs[info->index.info];
2318 unsigned long size = infosec->sh_size;
2320 for (p = (char *)infosec->sh_addr; p; p = next_string(p, &size)) {
2321 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
2322 return p + taglen + 1;
2327 static void setup_modinfo(struct module *mod, struct load_info *info)
2329 struct module_attribute *attr;
2332 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2334 attr->setup(mod, get_modinfo(info, attr->attr.name));
2338 static void free_modinfo(struct module *mod)
2340 struct module_attribute *attr;
2343 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2349 #ifdef CONFIG_KALLSYMS
2351 /* lookup symbol in given range of kernel_symbols */
2352 static const struct kernel_symbol *lookup_symbol(const char *name,
2353 const struct kernel_symbol *start,
2354 const struct kernel_symbol *stop)
2356 return bsearch(name, start, stop - start,
2357 sizeof(struct kernel_symbol), cmp_name);
2360 static int is_exported(const char *name, unsigned long value,
2361 const struct module *mod)
2363 const struct kernel_symbol *ks;
2365 ks = lookup_symbol(name, __start___ksymtab, __stop___ksymtab);
2367 ks = lookup_symbol(name, mod->syms, mod->syms + mod->num_syms);
2368 return ks != NULL && ks->value == value;
2372 static char elf_type(const Elf_Sym *sym, const struct load_info *info)
2374 const Elf_Shdr *sechdrs = info->sechdrs;
2376 if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
2377 if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT)
2382 if (sym->st_shndx == SHN_UNDEF)
2384 if (sym->st_shndx == SHN_ABS)
2386 if (sym->st_shndx >= SHN_LORESERVE)
2388 if (sechdrs[sym->st_shndx].sh_flags & SHF_EXECINSTR)
2390 if (sechdrs[sym->st_shndx].sh_flags & SHF_ALLOC
2391 && sechdrs[sym->st_shndx].sh_type != SHT_NOBITS) {
2392 if (!(sechdrs[sym->st_shndx].sh_flags & SHF_WRITE))
2394 else if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2399 if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
2400 if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2405 if (strstarts(info->secstrings + sechdrs[sym->st_shndx].sh_name,
2412 static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
2415 const Elf_Shdr *sec;
2417 if (src->st_shndx == SHN_UNDEF
2418 || src->st_shndx >= shnum
2422 sec = sechdrs + src->st_shndx;
2423 if (!(sec->sh_flags & SHF_ALLOC)
2424 #ifndef CONFIG_KALLSYMS_ALL
2425 || !(sec->sh_flags & SHF_EXECINSTR)
2427 || (sec->sh_entsize & INIT_OFFSET_MASK))
2434 * We only allocate and copy the strings needed by the parts of symtab
2435 * we keep. This is simple, but has the effect of making multiple
2436 * copies of duplicates. We could be more sophisticated, see
2437 * linux-kernel thread starting with
2438 * <73defb5e4bca04a6431392cc341112b1@localhost>.
2440 static void layout_symtab(struct module *mod, struct load_info *info)
2442 Elf_Shdr *symsect = info->sechdrs + info->index.sym;
2443 Elf_Shdr *strsect = info->sechdrs + info->index.str;
2445 unsigned int i, nsrc, ndst, strtab_size = 0;
2447 /* Put symbol section at end of init part of module. */
2448 symsect->sh_flags |= SHF_ALLOC;
2449 symsect->sh_entsize = get_offset(mod, &mod->init_size, symsect,
2450 info->index.sym) | INIT_OFFSET_MASK;
2451 pr_debug("\t%s\n", info->secstrings + symsect->sh_name);
2453 src = (void *)info->hdr + symsect->sh_offset;
2454 nsrc = symsect->sh_size / sizeof(*src);
2456 /* Compute total space required for the core symbols' strtab. */
2457 for (ndst = i = 0; i < nsrc; i++) {
2459 is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum)) {
2460 strtab_size += strlen(&info->strtab[src[i].st_name])+1;
2465 /* Append room for core symbols at end of core part. */
2466 info->symoffs = ALIGN(mod->core_size, symsect->sh_addralign ?: 1);
2467 info->stroffs = mod->core_size = info->symoffs + ndst * sizeof(Elf_Sym);
2468 mod->core_size += strtab_size;
2469 mod->core_size = debug_align(mod->core_size);
2471 /* Put string table section at end of init part of module. */
2472 strsect->sh_flags |= SHF_ALLOC;
2473 strsect->sh_entsize = get_offset(mod, &mod->init_size, strsect,
2474 info->index.str) | INIT_OFFSET_MASK;
2475 mod->init_size = debug_align(mod->init_size);
2476 pr_debug("\t%s\n", info->secstrings + strsect->sh_name);
2479 static void add_kallsyms(struct module *mod, const struct load_info *info)
2481 unsigned int i, ndst;
2485 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2487 mod->symtab = (void *)symsec->sh_addr;
2488 mod->num_symtab = symsec->sh_size / sizeof(Elf_Sym);
2489 /* Make sure we get permanent strtab: don't use info->strtab. */
2490 mod->strtab = (void *)info->sechdrs[info->index.str].sh_addr;
2492 /* Set types up while we still have access to sections. */
2493 for (i = 0; i < mod->num_symtab; i++)
2494 mod->symtab[i].st_info = elf_type(&mod->symtab[i], info);
2496 mod->core_symtab = dst = mod->module_core + info->symoffs;
2497 mod->core_strtab = s = mod->module_core + info->stroffs;
2499 for (ndst = i = 0; i < mod->num_symtab; i++) {
2501 is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum)) {
2503 dst[ndst++].st_name = s - mod->core_strtab;
2504 s += strlcpy(s, &mod->strtab[src[i].st_name],
2508 mod->core_num_syms = ndst;
2511 static inline void layout_symtab(struct module *mod, struct load_info *info)
2515 static void add_kallsyms(struct module *mod, const struct load_info *info)
2518 #endif /* CONFIG_KALLSYMS */
2520 static void dynamic_debug_setup(struct _ddebug *debug, unsigned int num)
2524 #ifdef CONFIG_DYNAMIC_DEBUG
2525 if (ddebug_add_module(debug, num, debug->modname))
2526 pr_err("dynamic debug error adding module: %s\n",
2531 static void dynamic_debug_remove(struct _ddebug *debug)
2534 ddebug_remove_module(debug->modname);
2537 void * __weak module_alloc(unsigned long size)
2539 return vmalloc_exec(size);
2542 static void *module_alloc_update_bounds(unsigned long size)
2544 void *ret = module_alloc(size);
2547 mutex_lock(&module_mutex);
2548 /* Update module bounds. */
2549 if ((unsigned long)ret < module_addr_min)
2550 module_addr_min = (unsigned long)ret;
2551 if ((unsigned long)ret + size > module_addr_max)
2552 module_addr_max = (unsigned long)ret + size;
2553 mutex_unlock(&module_mutex);
2558 #ifdef CONFIG_DEBUG_KMEMLEAK
2559 static void kmemleak_load_module(const struct module *mod,
2560 const struct load_info *info)
2564 /* only scan the sections containing data */
2565 kmemleak_scan_area(mod, sizeof(struct module), GFP_KERNEL);
2567 for (i = 1; i < info->hdr->e_shnum; i++) {
2568 /* Scan all writable sections that's not executable */
2569 if (!(info->sechdrs[i].sh_flags & SHF_ALLOC) ||
2570 !(info->sechdrs[i].sh_flags & SHF_WRITE) ||
2571 (info->sechdrs[i].sh_flags & SHF_EXECINSTR))
2574 kmemleak_scan_area((void *)info->sechdrs[i].sh_addr,
2575 info->sechdrs[i].sh_size, GFP_KERNEL);
2579 static inline void kmemleak_load_module(const struct module *mod,
2580 const struct load_info *info)
2585 #ifdef CONFIG_MODULE_SIG
2586 static int module_sig_check(struct load_info *info)
2589 const unsigned long markerlen = sizeof(MODULE_SIG_STRING) - 1;
2590 const void *mod = info->hdr;
2592 if (info->len > markerlen &&
2593 memcmp(mod + info->len - markerlen, MODULE_SIG_STRING, markerlen) == 0) {
2594 /* We truncate the module to discard the signature */
2595 info->len -= markerlen;
2596 err = mod_verify_sig(mod, &info->len);
2600 info->sig_ok = true;
2604 /* Not having a signature is only an error if we're strict. */
2605 if (err == -ENOKEY && !sig_enforce)
2610 #else /* !CONFIG_MODULE_SIG */
2611 static int module_sig_check(struct load_info *info)
2615 #endif /* !CONFIG_MODULE_SIG */
2617 /* Sanity checks against invalid binaries, wrong arch, weird elf version. */
2618 static int elf_header_check(struct load_info *info)
2620 if (info->len < sizeof(*(info->hdr)))
2623 if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0
2624 || info->hdr->e_type != ET_REL
2625 || !elf_check_arch(info->hdr)
2626 || info->hdr->e_shentsize != sizeof(Elf_Shdr))
2629 if (info->hdr->e_shoff >= info->len
2630 || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
2631 info->len - info->hdr->e_shoff))
2637 #define COPY_CHUNK_SIZE (16*PAGE_SIZE)
2639 static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len)
2642 unsigned long n = min(len, COPY_CHUNK_SIZE);
2644 if (copy_from_user(dst, usrc, n) != 0)
2654 /* Sets info->hdr and info->len. */
2655 static int copy_module_from_user(const void __user *umod, unsigned long len,
2656 struct load_info *info)
2661 if (info->len < sizeof(*(info->hdr)))
2664 err = security_kernel_module_from_file(NULL);
2668 /* Suck in entire file: we'll want most of it. */
2669 info->hdr = __vmalloc(info->len,
2670 GFP_KERNEL | __GFP_HIGHMEM | __GFP_NOWARN, PAGE_KERNEL);
2674 if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) {
2682 /* Sets info->hdr and info->len. */
2683 static int copy_module_from_fd(int fd, struct load_info *info)
2685 struct fd f = fdget(fd);
2694 err = security_kernel_module_from_file(f.file);
2698 err = vfs_getattr(&f.file->f_path, &stat);
2702 if (stat.size > INT_MAX) {
2707 /* Don't hand 0 to vmalloc, it whines. */
2708 if (stat.size == 0) {
2713 info->hdr = vmalloc(stat.size);
2720 while (pos < stat.size) {
2721 bytes = kernel_read(f.file, pos, (char *)(info->hdr) + pos,
2739 static void free_copy(struct load_info *info)
2744 static int rewrite_section_headers(struct load_info *info, int flags)
2748 /* This should always be true, but let's be sure. */
2749 info->sechdrs[0].sh_addr = 0;
2751 for (i = 1; i < info->hdr->e_shnum; i++) {
2752 Elf_Shdr *shdr = &info->sechdrs[i];
2753 if (shdr->sh_type != SHT_NOBITS
2754 && info->len < shdr->sh_offset + shdr->sh_size) {
2755 pr_err("Module len %lu truncated\n", info->len);
2759 /* Mark all sections sh_addr with their address in the
2761 shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
2763 #ifndef CONFIG_MODULE_UNLOAD
2764 /* Don't load .exit sections */
2765 if (strstarts(info->secstrings+shdr->sh_name, ".exit"))
2766 shdr->sh_flags &= ~(unsigned long)SHF_ALLOC;
2770 /* Track but don't keep modinfo and version sections. */
2771 if (flags & MODULE_INIT_IGNORE_MODVERSIONS)
2772 info->index.vers = 0; /* Pretend no __versions section! */
2774 info->index.vers = find_sec(info, "__versions");
2775 info->index.info = find_sec(info, ".modinfo");
2776 info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
2777 info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
2782 * Set up our basic convenience variables (pointers to section headers,
2783 * search for module section index etc), and do some basic section
2786 * Return the temporary module pointer (we'll replace it with the final
2787 * one when we move the module sections around).
2789 static struct module *setup_load_info(struct load_info *info, int flags)
2795 /* Set up the convenience variables */
2796 info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
2797 info->secstrings = (void *)info->hdr
2798 + info->sechdrs[info->hdr->e_shstrndx].sh_offset;
2800 err = rewrite_section_headers(info, flags);
2802 return ERR_PTR(err);
2804 /* Find internal symbols and strings. */
2805 for (i = 1; i < info->hdr->e_shnum; i++) {
2806 if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
2807 info->index.sym = i;
2808 info->index.str = info->sechdrs[i].sh_link;
2809 info->strtab = (char *)info->hdr
2810 + info->sechdrs[info->index.str].sh_offset;
2815 info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
2816 if (!info->index.mod) {
2817 pr_warn("No module found in object\n");
2818 return ERR_PTR(-ENOEXEC);
2820 /* This is temporary: point mod into copy of data. */
2821 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2823 if (info->index.sym == 0) {
2824 pr_warn("%s: module has no symbols (stripped?)\n", mod->name);
2825 return ERR_PTR(-ENOEXEC);
2828 info->index.pcpu = find_pcpusec(info);
2830 /* Check module struct version now, before we try to use module. */
2831 if (!check_modstruct_version(info->sechdrs, info->index.vers, mod))
2832 return ERR_PTR(-ENOEXEC);
2837 static int check_modinfo(struct module *mod, struct load_info *info, int flags)
2839 const char *modmagic = get_modinfo(info, "vermagic");
2842 if (flags & MODULE_INIT_IGNORE_VERMAGIC)
2845 /* This is allowed: modprobe --force will invalidate it. */
2847 err = try_to_force_load(mod, "bad vermagic");
2850 } else if (!same_magic(modmagic, vermagic, info->index.vers)) {
2851 pr_err("%s: version magic '%s' should be '%s'\n",
2852 mod->name, modmagic, vermagic);
2856 if (!get_modinfo(info, "intree"))
2857 add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
2859 if (get_modinfo(info, "staging")) {
2860 add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
2861 pr_warn("%s: module is from the staging directory, the quality "
2862 "is unknown, you have been warned.\n", mod->name);
2865 /* Set up license info based on the info section */
2866 set_license(mod, get_modinfo(info, "license"));
2871 static int find_module_sections(struct module *mod, struct load_info *info)
2873 mod->kp = section_objs(info, "__param",
2874 sizeof(*mod->kp), &mod->num_kp);
2875 mod->syms = section_objs(info, "__ksymtab",
2876 sizeof(*mod->syms), &mod->num_syms);
2877 mod->crcs = section_addr(info, "__kcrctab");
2878 mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
2879 sizeof(*mod->gpl_syms),
2880 &mod->num_gpl_syms);
2881 mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
2882 mod->gpl_future_syms = section_objs(info,
2883 "__ksymtab_gpl_future",
2884 sizeof(*mod->gpl_future_syms),
2885 &mod->num_gpl_future_syms);
2886 mod->gpl_future_crcs = section_addr(info, "__kcrctab_gpl_future");
2888 #ifdef CONFIG_UNUSED_SYMBOLS
2889 mod->unused_syms = section_objs(info, "__ksymtab_unused",
2890 sizeof(*mod->unused_syms),
2891 &mod->num_unused_syms);
2892 mod->unused_crcs = section_addr(info, "__kcrctab_unused");
2893 mod->unused_gpl_syms = section_objs(info, "__ksymtab_unused_gpl",
2894 sizeof(*mod->unused_gpl_syms),
2895 &mod->num_unused_gpl_syms);
2896 mod->unused_gpl_crcs = section_addr(info, "__kcrctab_unused_gpl");
2898 #ifdef CONFIG_CONSTRUCTORS
2899 mod->ctors = section_objs(info, ".ctors",
2900 sizeof(*mod->ctors), &mod->num_ctors);
2902 mod->ctors = section_objs(info, ".init_array",
2903 sizeof(*mod->ctors), &mod->num_ctors);
2904 else if (find_sec(info, ".init_array")) {
2906 * This shouldn't happen with same compiler and binutils
2907 * building all parts of the module.
2909 pr_warn("%s: has both .ctors and .init_array.\n",
2915 #ifdef CONFIG_TRACEPOINTS
2916 mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
2917 sizeof(*mod->tracepoints_ptrs),
2918 &mod->num_tracepoints);
2920 #ifdef HAVE_JUMP_LABEL
2921 mod->jump_entries = section_objs(info, "__jump_table",
2922 sizeof(*mod->jump_entries),
2923 &mod->num_jump_entries);
2925 #ifdef CONFIG_EVENT_TRACING
2926 mod->trace_events = section_objs(info, "_ftrace_events",
2927 sizeof(*mod->trace_events),
2928 &mod->num_trace_events);
2929 mod->trace_enums = section_objs(info, "_ftrace_enum_map",
2930 sizeof(*mod->trace_enums),
2931 &mod->num_trace_enums);
2933 #ifdef CONFIG_TRACING
2934 mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
2935 sizeof(*mod->trace_bprintk_fmt_start),
2936 &mod->num_trace_bprintk_fmt);
2938 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
2939 /* sechdrs[0].sh_size is always zero */
2940 mod->ftrace_callsites = section_objs(info, "__mcount_loc",
2941 sizeof(*mod->ftrace_callsites),
2942 &mod->num_ftrace_callsites);
2945 mod->extable = section_objs(info, "__ex_table",
2946 sizeof(*mod->extable), &mod->num_exentries);
2948 if (section_addr(info, "__obsparm"))
2949 pr_warn("%s: Ignoring obsolete parameters\n", mod->name);
2951 info->debug = section_objs(info, "__verbose",
2952 sizeof(*info->debug), &info->num_debug);
2957 static int move_module(struct module *mod, struct load_info *info)
2962 /* Do the allocs. */
2963 ptr = module_alloc_update_bounds(mod->core_size);
2965 * The pointer to this block is stored in the module structure
2966 * which is inside the block. Just mark it as not being a
2969 kmemleak_not_leak(ptr);
2973 memset(ptr, 0, mod->core_size);
2974 mod->module_core = ptr;
2976 if (mod->init_size) {
2977 ptr = module_alloc_update_bounds(mod->init_size);
2979 * The pointer to this block is stored in the module structure
2980 * which is inside the block. This block doesn't need to be
2981 * scanned as it contains data and code that will be freed
2982 * after the module is initialized.
2984 kmemleak_ignore(ptr);
2986 module_memfree(mod->module_core);
2989 memset(ptr, 0, mod->init_size);
2990 mod->module_init = ptr;
2992 mod->module_init = NULL;
2994 /* Transfer each section which specifies SHF_ALLOC */
2995 pr_debug("final section addresses:\n");
2996 for (i = 0; i < info->hdr->e_shnum; i++) {
2998 Elf_Shdr *shdr = &info->sechdrs[i];
3000 if (!(shdr->sh_flags & SHF_ALLOC))
3003 if (shdr->sh_entsize & INIT_OFFSET_MASK)
3004 dest = mod->module_init
3005 + (shdr->sh_entsize & ~INIT_OFFSET_MASK);
3007 dest = mod->module_core + shdr->sh_entsize;
3009 if (shdr->sh_type != SHT_NOBITS)
3010 memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
3011 /* Update sh_addr to point to copy in image. */
3012 shdr->sh_addr = (unsigned long)dest;
3013 pr_debug("\t0x%lx %s\n",
3014 (long)shdr->sh_addr, info->secstrings + shdr->sh_name);
3020 static int check_module_license_and_versions(struct module *mod)
3023 * ndiswrapper is under GPL by itself, but loads proprietary modules.
3024 * Don't use add_taint_module(), as it would prevent ndiswrapper from
3025 * using GPL-only symbols it needs.
3027 if (strcmp(mod->name, "ndiswrapper") == 0)
3028 add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
3030 /* driverloader was caught wrongly pretending to be under GPL */
3031 if (strcmp(mod->name, "driverloader") == 0)
3032 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
3033 LOCKDEP_NOW_UNRELIABLE);
3035 /* lve claims to be GPL but upstream won't provide source */
3036 if (strcmp(mod->name, "lve") == 0)
3037 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
3038 LOCKDEP_NOW_UNRELIABLE);
3040 #ifdef CONFIG_MODVERSIONS
3041 if ((mod->num_syms && !mod->crcs)
3042 || (mod->num_gpl_syms && !mod->gpl_crcs)
3043 || (mod->num_gpl_future_syms && !mod->gpl_future_crcs)
3044 #ifdef CONFIG_UNUSED_SYMBOLS
3045 || (mod->num_unused_syms && !mod->unused_crcs)
3046 || (mod->num_unused_gpl_syms && !mod->unused_gpl_crcs)
3049 return try_to_force_load(mod,
3050 "no versions for exported symbols");
3056 static void flush_module_icache(const struct module *mod)
3058 mm_segment_t old_fs;
3060 /* flush the icache in correct context */
3065 * Flush the instruction cache, since we've played with text.
3066 * Do it before processing of module parameters, so the module
3067 * can provide parameter accessor functions of its own.
3069 if (mod->module_init)
3070 flush_icache_range((unsigned long)mod->module_init,
3071 (unsigned long)mod->module_init
3073 flush_icache_range((unsigned long)mod->module_core,
3074 (unsigned long)mod->module_core + mod->core_size);
3079 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
3087 static struct module *layout_and_allocate(struct load_info *info, int flags)
3089 /* Module within temporary copy. */
3093 mod = setup_load_info(info, flags);
3097 err = check_modinfo(mod, info, flags);
3099 return ERR_PTR(err);
3101 /* Allow arches to frob section contents and sizes. */
3102 err = module_frob_arch_sections(info->hdr, info->sechdrs,
3103 info->secstrings, mod);
3105 return ERR_PTR(err);
3107 /* We will do a special allocation for per-cpu sections later. */
3108 info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
3110 /* Determine total sizes, and put offsets in sh_entsize. For now
3111 this is done generically; there doesn't appear to be any
3112 special cases for the architectures. */
3113 layout_sections(mod, info);
3114 layout_symtab(mod, info);
3116 /* Allocate and move to the final place */
3117 err = move_module(mod, info);
3119 return ERR_PTR(err);
3121 /* Module has been copied to its final place now: return it. */
3122 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
3123 kmemleak_load_module(mod, info);
3127 /* mod is no longer valid after this! */
3128 static void module_deallocate(struct module *mod, struct load_info *info)
3130 percpu_modfree(mod);
3131 module_arch_freeing_init(mod);
3132 module_memfree(mod->module_init);
3133 module_memfree(mod->module_core);
3136 int __weak module_finalize(const Elf_Ehdr *hdr,
3137 const Elf_Shdr *sechdrs,
3143 static int post_relocation(struct module *mod, const struct load_info *info)
3145 /* Sort exception table now relocations are done. */
3146 sort_extable(mod->extable, mod->extable + mod->num_exentries);
3148 /* Copy relocated percpu area over. */
3149 percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
3150 info->sechdrs[info->index.pcpu].sh_size);
3152 /* Setup kallsyms-specific fields. */
3153 add_kallsyms(mod, info);
3155 /* Arch-specific module finalizing. */
3156 return module_finalize(info->hdr, info->sechdrs, mod);
3159 /* Is this module of this name done loading? No locks held. */
3160 static bool finished_loading(const char *name)
3166 * The module_mutex should not be a heavily contended lock;
3167 * if we get the occasional sleep here, we'll go an extra iteration
3168 * in the wait_event_interruptible(), which is harmless.
3170 sched_annotate_sleep();
3171 mutex_lock(&module_mutex);
3172 mod = find_module_all(name, strlen(name), true);
3173 ret = !mod || mod->state == MODULE_STATE_LIVE
3174 || mod->state == MODULE_STATE_GOING;
3175 mutex_unlock(&module_mutex);
3180 /* Call module constructors. */
3181 static void do_mod_ctors(struct module *mod)
3183 #ifdef CONFIG_CONSTRUCTORS
3186 for (i = 0; i < mod->num_ctors; i++)
3191 /* For freeing module_init on success, in case kallsyms traversing */
3192 struct mod_initfree {
3193 struct rcu_head rcu;
3197 static void do_free_init(struct rcu_head *head)
3199 struct mod_initfree *m = container_of(head, struct mod_initfree, rcu);
3200 module_memfree(m->module_init);
3205 * This is where the real work happens.
3207 * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb
3208 * helper command 'lx-symbols'.
3210 static noinline int do_init_module(struct module *mod)
3213 struct mod_initfree *freeinit;
3215 freeinit = kmalloc(sizeof(*freeinit), GFP_KERNEL);
3220 freeinit->module_init = mod->module_init;
3223 * We want to find out whether @mod uses async during init. Clear
3224 * PF_USED_ASYNC. async_schedule*() will set it.
3226 current->flags &= ~PF_USED_ASYNC;
3229 /* Start the module */
3230 if (mod->init != NULL)
3231 ret = do_one_initcall(mod->init);
3233 goto fail_free_freeinit;
3236 pr_warn("%s: '%s'->init suspiciously returned %d, it should "
3237 "follow 0/-E convention\n"
3238 "%s: loading module anyway...\n",
3239 __func__, mod->name, ret, __func__);
3243 /* Now it's a first class citizen! */
3244 mod->state = MODULE_STATE_LIVE;
3245 blocking_notifier_call_chain(&module_notify_list,
3246 MODULE_STATE_LIVE, mod);
3249 * We need to finish all async code before the module init sequence
3250 * is done. This has potential to deadlock. For example, a newly
3251 * detected block device can trigger request_module() of the
3252 * default iosched from async probing task. Once userland helper
3253 * reaches here, async_synchronize_full() will wait on the async
3254 * task waiting on request_module() and deadlock.
3256 * This deadlock is avoided by perfomring async_synchronize_full()
3257 * iff module init queued any async jobs. This isn't a full
3258 * solution as it will deadlock the same if module loading from
3259 * async jobs nests more than once; however, due to the various
3260 * constraints, this hack seems to be the best option for now.
3261 * Please refer to the following thread for details.
3263 * http://thread.gmane.org/gmane.linux.kernel/1420814
3265 if (current->flags & PF_USED_ASYNC)
3266 async_synchronize_full();
3268 mutex_lock(&module_mutex);
3269 /* Drop initial reference. */
3271 trim_init_extable(mod);
3272 #ifdef CONFIG_KALLSYMS
3273 mod->num_symtab = mod->core_num_syms;
3274 mod->symtab = mod->core_symtab;
3275 mod->strtab = mod->core_strtab;
3277 mod_tree_remove_init(mod);
3278 unset_module_init_ro_nx(mod);
3279 module_arch_freeing_init(mod);
3280 mod->module_init = NULL;
3282 mod->init_ro_size = 0;
3283 mod->init_text_size = 0;
3285 * We want to free module_init, but be aware that kallsyms may be
3286 * walking this with preempt disabled. In all the failure paths, we
3287 * call synchronize_sched(), but we don't want to slow down the success
3288 * path, so use actual RCU here.
3290 call_rcu_sched(&freeinit->rcu, do_free_init);
3291 mutex_unlock(&module_mutex);
3292 wake_up_all(&module_wq);
3299 /* Try to protect us from buggy refcounters. */
3300 mod->state = MODULE_STATE_GOING;
3301 synchronize_sched();
3303 blocking_notifier_call_chain(&module_notify_list,
3304 MODULE_STATE_GOING, mod);
3306 wake_up_all(&module_wq);
3310 static int may_init_module(void)
3312 if (!capable(CAP_SYS_MODULE) || modules_disabled)
3319 * We try to place it in the list now to make sure it's unique before
3320 * we dedicate too many resources. In particular, temporary percpu
3321 * memory exhaustion.
3323 static int add_unformed_module(struct module *mod)
3328 mod->state = MODULE_STATE_UNFORMED;
3331 mutex_lock(&module_mutex);
3332 old = find_module_all(mod->name, strlen(mod->name), true);
3334 if (old->state == MODULE_STATE_COMING
3335 || old->state == MODULE_STATE_UNFORMED) {
3336 /* Wait in case it fails to load. */
3337 mutex_unlock(&module_mutex);
3338 err = wait_event_interruptible(module_wq,
3339 finished_loading(mod->name));
3347 list_add_rcu(&mod->list, &modules);
3348 mod_tree_insert(mod);
3352 mutex_unlock(&module_mutex);
3357 static int complete_formation(struct module *mod, struct load_info *info)
3361 mutex_lock(&module_mutex);
3363 /* Find duplicate symbols (must be called under lock). */
3364 err = verify_export_symbols(mod);
3368 /* This relies on module_mutex for list integrity. */
3369 module_bug_finalize(info->hdr, info->sechdrs, mod);
3371 /* Set RO and NX regions for core */
3372 set_section_ro_nx(mod->module_core,
3373 mod->core_text_size,
3377 /* Set RO and NX regions for init */
3378 set_section_ro_nx(mod->module_init,
3379 mod->init_text_size,
3383 /* Mark state as coming so strong_try_module_get() ignores us,
3384 * but kallsyms etc. can see us. */
3385 mod->state = MODULE_STATE_COMING;
3386 mutex_unlock(&module_mutex);
3388 blocking_notifier_call_chain(&module_notify_list,
3389 MODULE_STATE_COMING, mod);
3393 mutex_unlock(&module_mutex);
3397 static int unknown_module_param_cb(char *param, char *val, const char *modname)
3399 /* Check for magic 'dyndbg' arg */
3400 int ret = ddebug_dyndbg_module_param_cb(param, val, modname);
3402 pr_warn("%s: unknown parameter '%s' ignored\n", modname, param);
3406 /* Allocate and load the module: note that size of section 0 is always
3407 zero, and we rely on this for optional sections. */
3408 static int load_module(struct load_info *info, const char __user *uargs,
3415 err = module_sig_check(info);
3419 err = elf_header_check(info);
3423 /* Figure out module layout, and allocate all the memory. */
3424 mod = layout_and_allocate(info, flags);
3430 /* Reserve our place in the list. */
3431 err = add_unformed_module(mod);
3435 #ifdef CONFIG_MODULE_SIG
3436 mod->sig_ok = info->sig_ok;
3438 pr_notice_once("%s: module verification failed: signature "
3439 "and/or required key missing - tainting "
3440 "kernel\n", mod->name);
3441 add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
3445 /* To avoid stressing percpu allocator, do this once we're unique. */
3446 err = percpu_modalloc(mod, info);
3450 /* Now module is in final location, initialize linked lists, etc. */
3451 err = module_unload_init(mod);
3455 /* Now we've got everything in the final locations, we can
3456 * find optional sections. */
3457 err = find_module_sections(mod, info);
3461 err = check_module_license_and_versions(mod);
3465 /* Set up MODINFO_ATTR fields */
3466 setup_modinfo(mod, info);
3468 /* Fix up syms, so that st_value is a pointer to location. */
3469 err = simplify_symbols(mod, info);
3473 err = apply_relocations(mod, info);
3477 err = post_relocation(mod, info);
3481 flush_module_icache(mod);
3483 /* Now copy in args */
3484 mod->args = strndup_user(uargs, ~0UL >> 1);
3485 if (IS_ERR(mod->args)) {
3486 err = PTR_ERR(mod->args);
3487 goto free_arch_cleanup;
3490 dynamic_debug_setup(info->debug, info->num_debug);
3492 /* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
3493 ftrace_module_init(mod);
3495 /* Finally it's fully formed, ready to start executing. */
3496 err = complete_formation(mod, info);
3498 goto ddebug_cleanup;
3500 /* Module is ready to execute: parsing args may do that. */
3501 after_dashes = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
3502 -32768, 32767, unknown_module_param_cb);
3503 if (IS_ERR(after_dashes)) {
3504 err = PTR_ERR(after_dashes);
3506 } else if (after_dashes) {
3507 pr_warn("%s: parameters '%s' after `--' ignored\n",
3508 mod->name, after_dashes);
3511 /* Link in to syfs. */
3512 err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
3516 /* Get rid of temporary copy. */
3520 trace_module_load(mod);
3522 return do_init_module(mod);
3525 /* module_bug_cleanup needs module_mutex protection */
3526 mutex_lock(&module_mutex);
3527 module_bug_cleanup(mod);
3528 mutex_unlock(&module_mutex);
3530 /* we can't deallocate the module until we clear memory protection */
3531 unset_module_init_ro_nx(mod);
3532 unset_module_core_ro_nx(mod);
3535 dynamic_debug_remove(info->debug);
3536 synchronize_sched();
3539 module_arch_cleanup(mod);
3543 module_unload_free(mod);
3545 mutex_lock(&module_mutex);
3546 /* Unlink carefully: kallsyms could be walking list. */
3547 list_del_rcu(&mod->list);
3548 wake_up_all(&module_wq);
3549 /* Wait for RCU-sched synchronizing before releasing mod->list. */
3550 synchronize_sched();
3551 mutex_unlock(&module_mutex);
3553 /* Free lock-classes; relies on the preceding sync_rcu() */
3554 lockdep_free_key_range(mod->module_core, mod->core_size);
3556 module_deallocate(mod, info);
3562 SYSCALL_DEFINE3(init_module, void __user *, umod,
3563 unsigned long, len, const char __user *, uargs)
3566 struct load_info info = { };
3568 err = may_init_module();
3572 pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
3575 err = copy_module_from_user(umod, len, &info);
3579 return load_module(&info, uargs, 0);
3582 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
3585 struct load_info info = { };
3587 err = may_init_module();
3591 pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
3593 if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
3594 |MODULE_INIT_IGNORE_VERMAGIC))
3597 err = copy_module_from_fd(fd, &info);
3601 return load_module(&info, uargs, flags);
3604 static inline int within(unsigned long addr, void *start, unsigned long size)
3606 return ((void *)addr >= start && (void *)addr < start + size);
3609 #ifdef CONFIG_KALLSYMS
3611 * This ignores the intensely annoying "mapping symbols" found
3612 * in ARM ELF files: $a, $t and $d.
3614 static inline int is_arm_mapping_symbol(const char *str)
3616 if (str[0] == '.' && str[1] == 'L')
3618 return str[0] == '$' && strchr("axtd", str[1])
3619 && (str[2] == '\0' || str[2] == '.');
3622 static const char *get_ksymbol(struct module *mod,
3624 unsigned long *size,
3625 unsigned long *offset)
3627 unsigned int i, best = 0;
3628 unsigned long nextval;
3630 /* At worse, next value is at end of module */
3631 if (within_module_init(addr, mod))
3632 nextval = (unsigned long)mod->module_init+mod->init_text_size;
3634 nextval = (unsigned long)mod->module_core+mod->core_text_size;
3636 /* Scan for closest preceding symbol, and next symbol. (ELF
3637 starts real symbols at 1). */
3638 for (i = 1; i < mod->num_symtab; i++) {
3639 if (mod->symtab[i].st_shndx == SHN_UNDEF)
3642 /* We ignore unnamed symbols: they're uninformative
3643 * and inserted at a whim. */
3644 if (mod->symtab[i].st_value <= addr
3645 && mod->symtab[i].st_value > mod->symtab[best].st_value
3646 && *(mod->strtab + mod->symtab[i].st_name) != '\0'
3647 && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
3649 if (mod->symtab[i].st_value > addr
3650 && mod->symtab[i].st_value < nextval
3651 && *(mod->strtab + mod->symtab[i].st_name) != '\0'
3652 && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
3653 nextval = mod->symtab[i].st_value;
3660 *size = nextval - mod->symtab[best].st_value;
3662 *offset = addr - mod->symtab[best].st_value;
3663 return mod->strtab + mod->symtab[best].st_name;
3666 /* For kallsyms to ask for address resolution. NULL means not found. Careful
3667 * not to lock to avoid deadlock on oopses, simply disable preemption. */
3668 const char *module_address_lookup(unsigned long addr,
3669 unsigned long *size,
3670 unsigned long *offset,
3675 const char *ret = NULL;
3678 list_for_each_entry_rcu(mod, &modules, list) {
3679 if (mod->state == MODULE_STATE_UNFORMED)
3681 if (within_module(addr, mod)) {
3683 *modname = mod->name;
3684 ret = get_ksymbol(mod, addr, size, offset);
3688 /* Make a copy in here where it's safe */
3690 strncpy(namebuf, ret, KSYM_NAME_LEN - 1);
3697 int lookup_module_symbol_name(unsigned long addr, char *symname)
3702 list_for_each_entry_rcu(mod, &modules, list) {
3703 if (mod->state == MODULE_STATE_UNFORMED)
3705 if (within_module(addr, mod)) {
3708 sym = get_ksymbol(mod, addr, NULL, NULL);
3711 strlcpy(symname, sym, KSYM_NAME_LEN);
3721 int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size,
3722 unsigned long *offset, char *modname, char *name)
3727 list_for_each_entry_rcu(mod, &modules, list) {
3728 if (mod->state == MODULE_STATE_UNFORMED)
3730 if (within_module(addr, mod)) {
3733 sym = get_ksymbol(mod, addr, size, offset);
3737 strlcpy(modname, mod->name, MODULE_NAME_LEN);
3739 strlcpy(name, sym, KSYM_NAME_LEN);
3749 int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
3750 char *name, char *module_name, int *exported)
3755 list_for_each_entry_rcu(mod, &modules, list) {
3756 if (mod->state == MODULE_STATE_UNFORMED)
3758 if (symnum < mod->num_symtab) {
3759 *value = mod->symtab[symnum].st_value;
3760 *type = mod->symtab[symnum].st_info;
3761 strlcpy(name, mod->strtab + mod->symtab[symnum].st_name,
3763 strlcpy(module_name, mod->name, MODULE_NAME_LEN);
3764 *exported = is_exported(name, *value, mod);
3768 symnum -= mod->num_symtab;
3774 static unsigned long mod_find_symname(struct module *mod, const char *name)
3778 for (i = 0; i < mod->num_symtab; i++)
3779 if (strcmp(name, mod->strtab+mod->symtab[i].st_name) == 0 &&
3780 mod->symtab[i].st_info != 'U')
3781 return mod->symtab[i].st_value;
3785 /* Look for this name: can be of form module:name. */
3786 unsigned long module_kallsyms_lookup_name(const char *name)
3790 unsigned long ret = 0;
3792 /* Don't lock: we're in enough trouble already. */
3794 if ((colon = strchr(name, ':')) != NULL) {
3795 if ((mod = find_module_all(name, colon - name, false)) != NULL)
3796 ret = mod_find_symname(mod, colon+1);
3798 list_for_each_entry_rcu(mod, &modules, list) {
3799 if (mod->state == MODULE_STATE_UNFORMED)
3801 if ((ret = mod_find_symname(mod, name)) != 0)
3809 int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
3810 struct module *, unsigned long),
3817 module_assert_mutex();
3819 list_for_each_entry(mod, &modules, list) {
3820 if (mod->state == MODULE_STATE_UNFORMED)
3822 for (i = 0; i < mod->num_symtab; i++) {
3823 ret = fn(data, mod->strtab + mod->symtab[i].st_name,
3824 mod, mod->symtab[i].st_value);
3831 #endif /* CONFIG_KALLSYMS */
3833 static char *module_flags(struct module *mod, char *buf)
3837 BUG_ON(mod->state == MODULE_STATE_UNFORMED);
3839 mod->state == MODULE_STATE_GOING ||
3840 mod->state == MODULE_STATE_COMING) {
3842 bx += module_flags_taint(mod, buf + bx);
3843 /* Show a - for module-is-being-unloaded */
3844 if (mod->state == MODULE_STATE_GOING)
3846 /* Show a + for module-is-being-loaded */
3847 if (mod->state == MODULE_STATE_COMING)
3856 #ifdef CONFIG_PROC_FS
3857 /* Called by the /proc file system to return a list of modules. */
3858 static void *m_start(struct seq_file *m, loff_t *pos)
3860 mutex_lock(&module_mutex);
3861 return seq_list_start(&modules, *pos);
3864 static void *m_next(struct seq_file *m, void *p, loff_t *pos)
3866 return seq_list_next(p, &modules, pos);
3869 static void m_stop(struct seq_file *m, void *p)
3871 mutex_unlock(&module_mutex);
3874 static int m_show(struct seq_file *m, void *p)
3876 struct module *mod = list_entry(p, struct module, list);
3879 /* We always ignore unformed modules. */
3880 if (mod->state == MODULE_STATE_UNFORMED)
3883 seq_printf(m, "%s %u",
3884 mod->name, mod->init_size + mod->core_size);
3885 print_unload_info(m, mod);
3887 /* Informative for users. */
3888 seq_printf(m, " %s",
3889 mod->state == MODULE_STATE_GOING ? "Unloading" :
3890 mod->state == MODULE_STATE_COMING ? "Loading" :
3892 /* Used by oprofile and other similar tools. */
3893 seq_printf(m, " 0x%pK", mod->module_core);
3897 seq_printf(m, " %s", module_flags(mod, buf));
3903 /* Format: modulename size refcount deps address
3905 Where refcount is a number or -, and deps is a comma-separated list
3908 static const struct seq_operations modules_op = {
3915 static int modules_open(struct inode *inode, struct file *file)
3917 return seq_open(file, &modules_op);
3920 static const struct file_operations proc_modules_operations = {
3921 .open = modules_open,
3923 .llseek = seq_lseek,
3924 .release = seq_release,
3927 static int __init proc_modules_init(void)
3929 proc_create("modules", 0, NULL, &proc_modules_operations);
3932 module_init(proc_modules_init);
3935 /* Given an address, look for it in the module exception tables. */
3936 const struct exception_table_entry *search_module_extables(unsigned long addr)
3938 const struct exception_table_entry *e = NULL;
3942 list_for_each_entry_rcu(mod, &modules, list) {
3943 if (mod->state == MODULE_STATE_UNFORMED)
3945 if (mod->num_exentries == 0)
3948 e = search_extable(mod->extable,
3949 mod->extable + mod->num_exentries - 1,
3956 /* Now, if we found one, we are running inside it now, hence
3957 we cannot unload the module, hence no refcnt needed. */
3962 * is_module_address - is this address inside a module?
3963 * @addr: the address to check.
3965 * See is_module_text_address() if you simply want to see if the address
3966 * is code (not data).
3968 bool is_module_address(unsigned long addr)
3973 ret = __module_address(addr) != NULL;
3980 * __module_address - get the module which contains an address.
3981 * @addr: the address.
3983 * Must be called with preempt disabled or module mutex held so that
3984 * module doesn't get freed during this.
3986 struct module *__module_address(unsigned long addr)
3990 if (addr < module_addr_min || addr > module_addr_max)
3993 module_assert_mutex_or_preempt();
3995 mod = mod_find(addr);
3997 BUG_ON(!within_module(addr, mod));
3998 if (mod->state == MODULE_STATE_UNFORMED)
4003 EXPORT_SYMBOL_GPL(__module_address);
4006 * is_module_text_address - is this address inside module code?
4007 * @addr: the address to check.
4009 * See is_module_address() if you simply want to see if the address is
4010 * anywhere in a module. See kernel_text_address() for testing if an
4011 * address corresponds to kernel or module code.
4013 bool is_module_text_address(unsigned long addr)
4018 ret = __module_text_address(addr) != NULL;
4025 * __module_text_address - get the module whose code contains an address.
4026 * @addr: the address.
4028 * Must be called with preempt disabled or module mutex held so that
4029 * module doesn't get freed during this.
4031 struct module *__module_text_address(unsigned long addr)
4033 struct module *mod = __module_address(addr);
4035 /* Make sure it's within the text section. */
4036 if (!within(addr, mod->module_init, mod->init_text_size)
4037 && !within(addr, mod->module_core, mod->core_text_size))
4042 EXPORT_SYMBOL_GPL(__module_text_address);
4044 /* Don't grab lock, we're oopsing. */
4045 void print_modules(void)
4050 printk(KERN_DEFAULT "Modules linked in:");
4051 /* Most callers should already have preempt disabled, but make sure */
4053 list_for_each_entry_rcu(mod, &modules, list) {
4054 if (mod->state == MODULE_STATE_UNFORMED)
4056 pr_cont(" %s%s", mod->name, module_flags(mod, buf));
4059 if (last_unloaded_module[0])
4060 pr_cont(" [last unloaded: %s]", last_unloaded_module);
4064 #ifdef CONFIG_MODVERSIONS
4065 /* Generate the signature for all relevant module structures here.
4066 * If these change, we don't want to try to parse the module. */
4067 void module_layout(struct module *mod,
4068 struct modversion_info *ver,
4069 struct kernel_param *kp,
4070 struct kernel_symbol *ks,
4071 struct tracepoint * const *tp)
4074 EXPORT_SYMBOL(module_layout);