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);
104 #ifdef CONFIG_KGDB_KDB
105 struct list_head *kdb_modules = &modules; /* kdb needs the list of modules */
106 #endif /* CONFIG_KGDB_KDB */
108 static void module_assert_mutex(void)
110 lockdep_assert_held(&module_mutex);
113 static void module_assert_mutex_or_preempt(void)
115 #ifdef CONFIG_LOCKDEP
116 if (unlikely(!debug_locks))
119 WARN_ON(!rcu_read_lock_sched_held() &&
120 !lockdep_is_held(&module_mutex));
124 #ifdef CONFIG_MODULE_SIG
125 #ifdef CONFIG_MODULE_SIG_FORCE
126 static bool sig_enforce = true;
128 static bool sig_enforce = false;
130 static int param_set_bool_enable_only(const char *val,
131 const struct kernel_param *kp)
135 struct kernel_param dummy_kp = *kp;
137 dummy_kp.arg = &test;
139 err = param_set_bool(val, &dummy_kp);
143 /* Don't let them unset it once it's set! */
144 if (!test && sig_enforce)
152 static const struct kernel_param_ops param_ops_bool_enable_only = {
153 .flags = KERNEL_PARAM_OPS_FL_NOARG,
154 .set = param_set_bool_enable_only,
155 .get = param_get_bool,
157 #define param_check_bool_enable_only param_check_bool
159 module_param(sig_enforce, bool_enable_only, 0644);
160 #endif /* !CONFIG_MODULE_SIG_FORCE */
161 #endif /* CONFIG_MODULE_SIG */
163 /* Block module loading/unloading? */
164 int modules_disabled = 0;
165 core_param(nomodule, modules_disabled, bint, 0);
167 /* Waiting for a module to finish initializing? */
168 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
170 static BLOCKING_NOTIFIER_HEAD(module_notify_list);
172 /* Bounds of module allocation, for speeding __module_address.
173 * Protected by module_mutex. */
174 static unsigned long module_addr_min = -1UL, module_addr_max = 0;
176 int register_module_notifier(struct notifier_block *nb)
178 return blocking_notifier_chain_register(&module_notify_list, nb);
180 EXPORT_SYMBOL(register_module_notifier);
182 int unregister_module_notifier(struct notifier_block *nb)
184 return blocking_notifier_chain_unregister(&module_notify_list, nb);
186 EXPORT_SYMBOL(unregister_module_notifier);
192 char *secstrings, *strtab;
193 unsigned long symoffs, stroffs;
194 struct _ddebug *debug;
195 unsigned int num_debug;
198 unsigned int sym, str, mod, vers, info, pcpu;
202 /* We require a truly strong try_module_get(): 0 means failure due to
203 ongoing or failed initialization etc. */
204 static inline int strong_try_module_get(struct module *mod)
206 BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED);
207 if (mod && mod->state == MODULE_STATE_COMING)
209 if (try_module_get(mod))
215 static inline void add_taint_module(struct module *mod, unsigned flag,
216 enum lockdep_ok lockdep_ok)
218 add_taint(flag, lockdep_ok);
219 mod->taints |= (1U << flag);
223 * A thread that wants to hold a reference to a module only while it
224 * is running can call this to safely exit. nfsd and lockd use this.
226 void __module_put_and_exit(struct module *mod, long code)
231 EXPORT_SYMBOL(__module_put_and_exit);
233 /* Find a module section: 0 means not found. */
234 static unsigned int find_sec(const struct load_info *info, const char *name)
238 for (i = 1; i < info->hdr->e_shnum; i++) {
239 Elf_Shdr *shdr = &info->sechdrs[i];
240 /* Alloc bit cleared means "ignore it." */
241 if ((shdr->sh_flags & SHF_ALLOC)
242 && strcmp(info->secstrings + shdr->sh_name, name) == 0)
248 /* Find a module section, or NULL. */
249 static void *section_addr(const struct load_info *info, const char *name)
251 /* Section 0 has sh_addr 0. */
252 return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
255 /* Find a module section, or NULL. Fill in number of "objects" in section. */
256 static void *section_objs(const struct load_info *info,
261 unsigned int sec = find_sec(info, name);
263 /* Section 0 has sh_addr 0 and sh_size 0. */
264 *num = info->sechdrs[sec].sh_size / object_size;
265 return (void *)info->sechdrs[sec].sh_addr;
268 /* Provided by the linker */
269 extern const struct kernel_symbol __start___ksymtab[];
270 extern const struct kernel_symbol __stop___ksymtab[];
271 extern const struct kernel_symbol __start___ksymtab_gpl[];
272 extern const struct kernel_symbol __stop___ksymtab_gpl[];
273 extern const struct kernel_symbol __start___ksymtab_gpl_future[];
274 extern const struct kernel_symbol __stop___ksymtab_gpl_future[];
275 extern const unsigned long __start___kcrctab[];
276 extern const unsigned long __start___kcrctab_gpl[];
277 extern const unsigned long __start___kcrctab_gpl_future[];
278 #ifdef CONFIG_UNUSED_SYMBOLS
279 extern const struct kernel_symbol __start___ksymtab_unused[];
280 extern const struct kernel_symbol __stop___ksymtab_unused[];
281 extern const struct kernel_symbol __start___ksymtab_unused_gpl[];
282 extern const struct kernel_symbol __stop___ksymtab_unused_gpl[];
283 extern const unsigned long __start___kcrctab_unused[];
284 extern const unsigned long __start___kcrctab_unused_gpl[];
287 #ifndef CONFIG_MODVERSIONS
288 #define symversion(base, idx) NULL
290 #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
293 static bool each_symbol_in_section(const struct symsearch *arr,
294 unsigned int arrsize,
295 struct module *owner,
296 bool (*fn)(const struct symsearch *syms,
297 struct module *owner,
303 for (j = 0; j < arrsize; j++) {
304 if (fn(&arr[j], owner, data))
311 /* Returns true as soon as fn returns true, otherwise false. */
312 bool each_symbol_section(bool (*fn)(const struct symsearch *arr,
313 struct module *owner,
318 static const struct symsearch arr[] = {
319 { __start___ksymtab, __stop___ksymtab, __start___kcrctab,
320 NOT_GPL_ONLY, false },
321 { __start___ksymtab_gpl, __stop___ksymtab_gpl,
322 __start___kcrctab_gpl,
324 { __start___ksymtab_gpl_future, __stop___ksymtab_gpl_future,
325 __start___kcrctab_gpl_future,
326 WILL_BE_GPL_ONLY, false },
327 #ifdef CONFIG_UNUSED_SYMBOLS
328 { __start___ksymtab_unused, __stop___ksymtab_unused,
329 __start___kcrctab_unused,
330 NOT_GPL_ONLY, true },
331 { __start___ksymtab_unused_gpl, __stop___ksymtab_unused_gpl,
332 __start___kcrctab_unused_gpl,
337 module_assert_mutex_or_preempt();
339 if (each_symbol_in_section(arr, ARRAY_SIZE(arr), NULL, fn, data))
342 list_for_each_entry_rcu(mod, &modules, list) {
343 struct symsearch arr[] = {
344 { mod->syms, mod->syms + mod->num_syms, mod->crcs,
345 NOT_GPL_ONLY, false },
346 { mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
349 { mod->gpl_future_syms,
350 mod->gpl_future_syms + mod->num_gpl_future_syms,
351 mod->gpl_future_crcs,
352 WILL_BE_GPL_ONLY, false },
353 #ifdef CONFIG_UNUSED_SYMBOLS
355 mod->unused_syms + mod->num_unused_syms,
357 NOT_GPL_ONLY, true },
358 { mod->unused_gpl_syms,
359 mod->unused_gpl_syms + mod->num_unused_gpl_syms,
360 mod->unused_gpl_crcs,
365 if (mod->state == MODULE_STATE_UNFORMED)
368 if (each_symbol_in_section(arr, ARRAY_SIZE(arr), mod, fn, data))
373 EXPORT_SYMBOL_GPL(each_symbol_section);
375 struct find_symbol_arg {
382 struct module *owner;
383 const unsigned long *crc;
384 const struct kernel_symbol *sym;
387 static bool check_symbol(const struct symsearch *syms,
388 struct module *owner,
389 unsigned int symnum, void *data)
391 struct find_symbol_arg *fsa = data;
394 if (syms->licence == GPL_ONLY)
396 if (syms->licence == WILL_BE_GPL_ONLY && fsa->warn) {
397 pr_warn("Symbol %s is being used by a non-GPL module, "
398 "which will not be allowed in the future\n",
403 #ifdef CONFIG_UNUSED_SYMBOLS
404 if (syms->unused && fsa->warn) {
405 pr_warn("Symbol %s is marked as UNUSED, however this module is "
406 "using it.\n", fsa->name);
407 pr_warn("This symbol will go away in the future.\n");
408 pr_warn("Please evaluate if this is the right api to use and "
409 "if it really is, submit a report to the linux kernel "
410 "mailing list together with submitting your code for "
416 fsa->crc = symversion(syms->crcs, symnum);
417 fsa->sym = &syms->start[symnum];
421 static int cmp_name(const void *va, const void *vb)
424 const struct kernel_symbol *b;
426 return strcmp(a, b->name);
429 static bool find_symbol_in_section(const struct symsearch *syms,
430 struct module *owner,
433 struct find_symbol_arg *fsa = data;
434 struct kernel_symbol *sym;
436 sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
437 sizeof(struct kernel_symbol), cmp_name);
439 if (sym != NULL && check_symbol(syms, owner, sym - syms->start, data))
445 /* Find a symbol and return it, along with, (optional) crc and
446 * (optional) module which owns it. Needs preempt disabled or module_mutex. */
447 const struct kernel_symbol *find_symbol(const char *name,
448 struct module **owner,
449 const unsigned long **crc,
453 struct find_symbol_arg fsa;
459 if (each_symbol_section(find_symbol_in_section, &fsa)) {
467 pr_debug("Failed to find symbol %s\n", name);
470 EXPORT_SYMBOL_GPL(find_symbol);
472 /* Search for module by name: must hold module_mutex. */
473 static struct module *find_module_all(const char *name, size_t len,
478 module_assert_mutex();
480 list_for_each_entry(mod, &modules, list) {
481 if (!even_unformed && mod->state == MODULE_STATE_UNFORMED)
483 if (strlen(mod->name) == len && !memcmp(mod->name, name, len))
489 struct module *find_module(const char *name)
491 return find_module_all(name, strlen(name), false);
493 EXPORT_SYMBOL_GPL(find_module);
497 static inline void __percpu *mod_percpu(struct module *mod)
502 static int percpu_modalloc(struct module *mod, struct load_info *info)
504 Elf_Shdr *pcpusec = &info->sechdrs[info->index.pcpu];
505 unsigned long align = pcpusec->sh_addralign;
507 if (!pcpusec->sh_size)
510 if (align > PAGE_SIZE) {
511 pr_warn("%s: per-cpu alignment %li > %li\n",
512 mod->name, align, PAGE_SIZE);
516 mod->percpu = __alloc_reserved_percpu(pcpusec->sh_size, align);
518 pr_warn("%s: Could not allocate %lu bytes percpu data\n",
519 mod->name, (unsigned long)pcpusec->sh_size);
522 mod->percpu_size = pcpusec->sh_size;
526 static void percpu_modfree(struct module *mod)
528 free_percpu(mod->percpu);
531 static unsigned int find_pcpusec(struct load_info *info)
533 return find_sec(info, ".data..percpu");
536 static void percpu_modcopy(struct module *mod,
537 const void *from, unsigned long size)
541 for_each_possible_cpu(cpu)
542 memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
546 * is_module_percpu_address - test whether address is from module static percpu
547 * @addr: address to test
549 * Test whether @addr belongs to module static percpu area.
552 * %true if @addr is from module static percpu area
554 bool is_module_percpu_address(unsigned long addr)
561 list_for_each_entry_rcu(mod, &modules, list) {
562 if (mod->state == MODULE_STATE_UNFORMED)
564 if (!mod->percpu_size)
566 for_each_possible_cpu(cpu) {
567 void *start = per_cpu_ptr(mod->percpu, cpu);
569 if ((void *)addr >= start &&
570 (void *)addr < start + mod->percpu_size) {
581 #else /* ... !CONFIG_SMP */
583 static inline void __percpu *mod_percpu(struct module *mod)
587 static int percpu_modalloc(struct module *mod, struct load_info *info)
589 /* UP modules shouldn't have this section: ENOMEM isn't quite right */
590 if (info->sechdrs[info->index.pcpu].sh_size != 0)
594 static inline void percpu_modfree(struct module *mod)
597 static unsigned int find_pcpusec(struct load_info *info)
601 static inline void percpu_modcopy(struct module *mod,
602 const void *from, unsigned long size)
604 /* pcpusec should be 0, and size of that section should be 0. */
607 bool is_module_percpu_address(unsigned long addr)
612 #endif /* CONFIG_SMP */
614 #define MODINFO_ATTR(field) \
615 static void setup_modinfo_##field(struct module *mod, const char *s) \
617 mod->field = kstrdup(s, GFP_KERNEL); \
619 static ssize_t show_modinfo_##field(struct module_attribute *mattr, \
620 struct module_kobject *mk, char *buffer) \
622 return scnprintf(buffer, PAGE_SIZE, "%s\n", mk->mod->field); \
624 static int modinfo_##field##_exists(struct module *mod) \
626 return mod->field != NULL; \
628 static void free_modinfo_##field(struct module *mod) \
633 static struct module_attribute modinfo_##field = { \
634 .attr = { .name = __stringify(field), .mode = 0444 }, \
635 .show = show_modinfo_##field, \
636 .setup = setup_modinfo_##field, \
637 .test = modinfo_##field##_exists, \
638 .free = free_modinfo_##field, \
641 MODINFO_ATTR(version);
642 MODINFO_ATTR(srcversion);
644 static char last_unloaded_module[MODULE_NAME_LEN+1];
646 #ifdef CONFIG_MODULE_UNLOAD
648 EXPORT_TRACEPOINT_SYMBOL(module_get);
650 /* MODULE_REF_BASE is the base reference count by kmodule loader. */
651 #define MODULE_REF_BASE 1
653 /* Init the unload section of the module. */
654 static int module_unload_init(struct module *mod)
657 * Initialize reference counter to MODULE_REF_BASE.
658 * refcnt == 0 means module is going.
660 atomic_set(&mod->refcnt, MODULE_REF_BASE);
662 INIT_LIST_HEAD(&mod->source_list);
663 INIT_LIST_HEAD(&mod->target_list);
665 /* Hold reference count during initialization. */
666 atomic_inc(&mod->refcnt);
671 /* Does a already use b? */
672 static int already_uses(struct module *a, struct module *b)
674 struct module_use *use;
676 list_for_each_entry(use, &b->source_list, source_list) {
677 if (use->source == a) {
678 pr_debug("%s uses %s!\n", a->name, b->name);
682 pr_debug("%s does not use %s!\n", a->name, b->name);
688 * - we add 'a' as a "source", 'b' as a "target" of module use
689 * - the module_use is added to the list of 'b' sources (so
690 * 'b' can walk the list to see who sourced them), and of 'a'
691 * targets (so 'a' can see what modules it targets).
693 static int add_module_usage(struct module *a, struct module *b)
695 struct module_use *use;
697 pr_debug("Allocating new usage for %s.\n", a->name);
698 use = kmalloc(sizeof(*use), GFP_ATOMIC);
700 pr_warn("%s: out of memory loading\n", a->name);
706 list_add(&use->source_list, &b->source_list);
707 list_add(&use->target_list, &a->target_list);
711 /* Module a uses b: caller needs module_mutex() */
712 int ref_module(struct module *a, struct module *b)
716 if (b == NULL || already_uses(a, b))
719 /* If module isn't available, we fail. */
720 err = strong_try_module_get(b);
724 err = add_module_usage(a, b);
731 EXPORT_SYMBOL_GPL(ref_module);
733 /* Clear the unload stuff of the module. */
734 static void module_unload_free(struct module *mod)
736 struct module_use *use, *tmp;
738 mutex_lock(&module_mutex);
739 list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
740 struct module *i = use->target;
741 pr_debug("%s unusing %s\n", mod->name, i->name);
743 list_del(&use->source_list);
744 list_del(&use->target_list);
747 mutex_unlock(&module_mutex);
750 #ifdef CONFIG_MODULE_FORCE_UNLOAD
751 static inline int try_force_unload(unsigned int flags)
753 int ret = (flags & O_TRUNC);
755 add_taint(TAINT_FORCED_RMMOD, LOCKDEP_NOW_UNRELIABLE);
759 static inline int try_force_unload(unsigned int flags)
763 #endif /* CONFIG_MODULE_FORCE_UNLOAD */
765 /* Try to release refcount of module, 0 means success. */
766 static int try_release_module_ref(struct module *mod)
770 /* Try to decrement refcnt which we set at loading */
771 ret = atomic_sub_return(MODULE_REF_BASE, &mod->refcnt);
774 /* Someone can put this right now, recover with checking */
775 ret = atomic_add_unless(&mod->refcnt, MODULE_REF_BASE, 0);
780 static int try_stop_module(struct module *mod, int flags, int *forced)
782 /* If it's not unused, quit unless we're forcing. */
783 if (try_release_module_ref(mod) != 0) {
784 *forced = try_force_unload(flags);
789 /* Mark it as dying. */
790 mod->state = MODULE_STATE_GOING;
796 * module_refcount - return the refcount or -1 if unloading
798 * @mod: the module we're checking
801 * -1 if the module is in the process of unloading
802 * otherwise the number of references in the kernel to the module
804 int module_refcount(struct module *mod)
806 return atomic_read(&mod->refcnt) - MODULE_REF_BASE;
808 EXPORT_SYMBOL(module_refcount);
810 /* This exists whether we can unload or not */
811 static void free_module(struct module *mod);
813 SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
817 char name[MODULE_NAME_LEN];
820 if (!capable(CAP_SYS_MODULE) || modules_disabled)
823 if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
825 name[MODULE_NAME_LEN-1] = '\0';
827 if (mutex_lock_interruptible(&module_mutex) != 0)
830 mod = find_module(name);
836 if (!list_empty(&mod->source_list)) {
837 /* Other modules depend on us: get rid of them first. */
842 /* Doing init or already dying? */
843 if (mod->state != MODULE_STATE_LIVE) {
844 /* FIXME: if (force), slam module count damn the torpedoes */
845 pr_debug("%s already dying\n", mod->name);
850 /* If it has an init func, it must have an exit func to unload */
851 if (mod->init && !mod->exit) {
852 forced = try_force_unload(flags);
854 /* This module can't be removed */
860 /* Stop the machine so refcounts can't move and disable module. */
861 ret = try_stop_module(mod, flags, &forced);
865 mutex_unlock(&module_mutex);
866 /* Final destruction now no one is using it. */
867 if (mod->exit != NULL)
869 blocking_notifier_call_chain(&module_notify_list,
870 MODULE_STATE_GOING, mod);
871 async_synchronize_full();
873 /* Store the name of the last unloaded module for diagnostic purposes */
874 strlcpy(last_unloaded_module, mod->name, sizeof(last_unloaded_module));
879 mutex_unlock(&module_mutex);
883 static inline void print_unload_info(struct seq_file *m, struct module *mod)
885 struct module_use *use;
886 int printed_something = 0;
888 seq_printf(m, " %i ", module_refcount(mod));
891 * Always include a trailing , so userspace can differentiate
892 * between this and the old multi-field proc format.
894 list_for_each_entry(use, &mod->source_list, source_list) {
895 printed_something = 1;
896 seq_printf(m, "%s,", use->source->name);
899 if (mod->init != NULL && mod->exit == NULL) {
900 printed_something = 1;
901 seq_puts(m, "[permanent],");
904 if (!printed_something)
908 void __symbol_put(const char *symbol)
910 struct module *owner;
913 if (!find_symbol(symbol, &owner, NULL, true, false))
918 EXPORT_SYMBOL(__symbol_put);
920 /* Note this assumes addr is a function, which it currently always is. */
921 void symbol_put_addr(void *addr)
923 struct module *modaddr;
924 unsigned long a = (unsigned long)dereference_function_descriptor(addr);
926 if (core_kernel_text(a))
929 /* module_text_address is safe here: we're supposed to have reference
930 * to module from symbol_get, so it can't go away. */
931 modaddr = __module_text_address(a);
935 EXPORT_SYMBOL_GPL(symbol_put_addr);
937 static ssize_t show_refcnt(struct module_attribute *mattr,
938 struct module_kobject *mk, char *buffer)
940 return sprintf(buffer, "%i\n", module_refcount(mk->mod));
943 static struct module_attribute modinfo_refcnt =
944 __ATTR(refcnt, 0444, show_refcnt, NULL);
946 void __module_get(struct module *module)
950 atomic_inc(&module->refcnt);
951 trace_module_get(module, _RET_IP_);
955 EXPORT_SYMBOL(__module_get);
957 bool try_module_get(struct module *module)
963 /* Note: here, we can fail to get a reference */
964 if (likely(module_is_live(module) &&
965 atomic_inc_not_zero(&module->refcnt) != 0))
966 trace_module_get(module, _RET_IP_);
974 EXPORT_SYMBOL(try_module_get);
976 void module_put(struct module *module)
982 ret = atomic_dec_if_positive(&module->refcnt);
983 WARN_ON(ret < 0); /* Failed to put refcount */
984 trace_module_put(module, _RET_IP_);
988 EXPORT_SYMBOL(module_put);
990 #else /* !CONFIG_MODULE_UNLOAD */
991 static inline void print_unload_info(struct seq_file *m, struct module *mod)
993 /* We don't know the usage count, or what modules are using. */
997 static inline void module_unload_free(struct module *mod)
1001 int ref_module(struct module *a, struct module *b)
1003 return strong_try_module_get(b);
1005 EXPORT_SYMBOL_GPL(ref_module);
1007 static inline int module_unload_init(struct module *mod)
1011 #endif /* CONFIG_MODULE_UNLOAD */
1013 static size_t module_flags_taint(struct module *mod, char *buf)
1017 if (mod->taints & (1 << TAINT_PROPRIETARY_MODULE))
1019 if (mod->taints & (1 << TAINT_OOT_MODULE))
1021 if (mod->taints & (1 << TAINT_FORCED_MODULE))
1023 if (mod->taints & (1 << TAINT_CRAP))
1025 if (mod->taints & (1 << TAINT_UNSIGNED_MODULE))
1028 * TAINT_FORCED_RMMOD: could be added.
1029 * TAINT_CPU_OUT_OF_SPEC, TAINT_MACHINE_CHECK, TAINT_BAD_PAGE don't
1035 static ssize_t show_initstate(struct module_attribute *mattr,
1036 struct module_kobject *mk, char *buffer)
1038 const char *state = "unknown";
1040 switch (mk->mod->state) {
1041 case MODULE_STATE_LIVE:
1044 case MODULE_STATE_COMING:
1047 case MODULE_STATE_GOING:
1053 return sprintf(buffer, "%s\n", state);
1056 static struct module_attribute modinfo_initstate =
1057 __ATTR(initstate, 0444, show_initstate, NULL);
1059 static ssize_t store_uevent(struct module_attribute *mattr,
1060 struct module_kobject *mk,
1061 const char *buffer, size_t count)
1063 enum kobject_action action;
1065 if (kobject_action_type(buffer, count, &action) == 0)
1066 kobject_uevent(&mk->kobj, action);
1070 struct module_attribute module_uevent =
1071 __ATTR(uevent, 0200, NULL, store_uevent);
1073 static ssize_t show_coresize(struct module_attribute *mattr,
1074 struct module_kobject *mk, char *buffer)
1076 return sprintf(buffer, "%u\n", mk->mod->core_size);
1079 static struct module_attribute modinfo_coresize =
1080 __ATTR(coresize, 0444, show_coresize, NULL);
1082 static ssize_t show_initsize(struct module_attribute *mattr,
1083 struct module_kobject *mk, char *buffer)
1085 return sprintf(buffer, "%u\n", mk->mod->init_size);
1088 static struct module_attribute modinfo_initsize =
1089 __ATTR(initsize, 0444, show_initsize, NULL);
1091 static ssize_t show_taint(struct module_attribute *mattr,
1092 struct module_kobject *mk, char *buffer)
1096 l = module_flags_taint(mk->mod, buffer);
1101 static struct module_attribute modinfo_taint =
1102 __ATTR(taint, 0444, show_taint, NULL);
1104 static struct module_attribute *modinfo_attrs[] = {
1107 &modinfo_srcversion,
1112 #ifdef CONFIG_MODULE_UNLOAD
1118 static const char vermagic[] = VERMAGIC_STRING;
1120 static int try_to_force_load(struct module *mod, const char *reason)
1122 #ifdef CONFIG_MODULE_FORCE_LOAD
1123 if (!test_taint(TAINT_FORCED_MODULE))
1124 pr_warn("%s: %s: kernel tainted.\n", mod->name, reason);
1125 add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE);
1132 #ifdef CONFIG_MODVERSIONS
1133 /* If the arch applies (non-zero) relocations to kernel kcrctab, unapply it. */
1134 static unsigned long maybe_relocated(unsigned long crc,
1135 const struct module *crc_owner)
1137 #ifdef ARCH_RELOCATES_KCRCTAB
1138 if (crc_owner == NULL)
1139 return crc - (unsigned long)reloc_start;
1144 static int check_version(Elf_Shdr *sechdrs,
1145 unsigned int versindex,
1146 const char *symname,
1148 const unsigned long *crc,
1149 const struct module *crc_owner)
1151 unsigned int i, num_versions;
1152 struct modversion_info *versions;
1154 /* Exporting module didn't supply crcs? OK, we're already tainted. */
1158 /* No versions at all? modprobe --force does this. */
1160 return try_to_force_load(mod, symname) == 0;
1162 versions = (void *) sechdrs[versindex].sh_addr;
1163 num_versions = sechdrs[versindex].sh_size
1164 / sizeof(struct modversion_info);
1166 for (i = 0; i < num_versions; i++) {
1167 if (strcmp(versions[i].name, symname) != 0)
1170 if (versions[i].crc == maybe_relocated(*crc, crc_owner))
1172 pr_debug("Found checksum %lX vs module %lX\n",
1173 maybe_relocated(*crc, crc_owner), versions[i].crc);
1177 pr_warn("%s: no symbol version for %s\n", mod->name, symname);
1181 pr_warn("%s: disagrees about version of symbol %s\n",
1182 mod->name, symname);
1186 static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1187 unsigned int versindex,
1190 const unsigned long *crc;
1193 * Since this should be found in kernel (which can't be removed), no
1194 * locking is necessary -- use preempt_disable() to placate lockdep.
1197 if (!find_symbol(VMLINUX_SYMBOL_STR(module_layout), NULL,
1198 &crc, true, false)) {
1203 return check_version(sechdrs, versindex,
1204 VMLINUX_SYMBOL_STR(module_layout), mod, crc,
1208 /* First part is kernel version, which we ignore if module has crcs. */
1209 static inline int same_magic(const char *amagic, const char *bmagic,
1213 amagic += strcspn(amagic, " ");
1214 bmagic += strcspn(bmagic, " ");
1216 return strcmp(amagic, bmagic) == 0;
1219 static inline int check_version(Elf_Shdr *sechdrs,
1220 unsigned int versindex,
1221 const char *symname,
1223 const unsigned long *crc,
1224 const struct module *crc_owner)
1229 static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1230 unsigned int versindex,
1236 static inline int same_magic(const char *amagic, const char *bmagic,
1239 return strcmp(amagic, bmagic) == 0;
1241 #endif /* CONFIG_MODVERSIONS */
1243 /* Resolve a symbol for this module. I.e. if we find one, record usage. */
1244 static const struct kernel_symbol *resolve_symbol(struct module *mod,
1245 const struct load_info *info,
1249 struct module *owner;
1250 const struct kernel_symbol *sym;
1251 const unsigned long *crc;
1255 * The module_mutex should not be a heavily contended lock;
1256 * if we get the occasional sleep here, we'll go an extra iteration
1257 * in the wait_event_interruptible(), which is harmless.
1259 sched_annotate_sleep();
1260 mutex_lock(&module_mutex);
1261 sym = find_symbol(name, &owner, &crc,
1262 !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)), true);
1266 if (!check_version(info->sechdrs, info->index.vers, name, mod, crc,
1268 sym = ERR_PTR(-EINVAL);
1272 err = ref_module(mod, owner);
1279 /* We must make copy under the lock if we failed to get ref. */
1280 strncpy(ownername, module_name(owner), MODULE_NAME_LEN);
1282 mutex_unlock(&module_mutex);
1286 static const struct kernel_symbol *
1287 resolve_symbol_wait(struct module *mod,
1288 const struct load_info *info,
1291 const struct kernel_symbol *ksym;
1292 char owner[MODULE_NAME_LEN];
1294 if (wait_event_interruptible_timeout(module_wq,
1295 !IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1296 || PTR_ERR(ksym) != -EBUSY,
1298 pr_warn("%s: gave up waiting for init of module %s.\n",
1305 * /sys/module/foo/sections stuff
1306 * J. Corbet <corbet@lwn.net>
1310 #ifdef CONFIG_KALLSYMS
1311 static inline bool sect_empty(const Elf_Shdr *sect)
1313 return !(sect->sh_flags & SHF_ALLOC) || sect->sh_size == 0;
1316 struct module_sect_attr {
1317 struct module_attribute mattr;
1319 unsigned long address;
1322 struct module_sect_attrs {
1323 struct attribute_group grp;
1324 unsigned int nsections;
1325 struct module_sect_attr attrs[0];
1328 static ssize_t module_sect_show(struct module_attribute *mattr,
1329 struct module_kobject *mk, char *buf)
1331 struct module_sect_attr *sattr =
1332 container_of(mattr, struct module_sect_attr, mattr);
1333 return sprintf(buf, "0x%pK\n", (void *)sattr->address);
1336 static void free_sect_attrs(struct module_sect_attrs *sect_attrs)
1338 unsigned int section;
1340 for (section = 0; section < sect_attrs->nsections; section++)
1341 kfree(sect_attrs->attrs[section].name);
1345 static void add_sect_attrs(struct module *mod, const struct load_info *info)
1347 unsigned int nloaded = 0, i, size[2];
1348 struct module_sect_attrs *sect_attrs;
1349 struct module_sect_attr *sattr;
1350 struct attribute **gattr;
1352 /* Count loaded sections and allocate structures */
1353 for (i = 0; i < info->hdr->e_shnum; i++)
1354 if (!sect_empty(&info->sechdrs[i]))
1356 size[0] = ALIGN(sizeof(*sect_attrs)
1357 + nloaded * sizeof(sect_attrs->attrs[0]),
1358 sizeof(sect_attrs->grp.attrs[0]));
1359 size[1] = (nloaded + 1) * sizeof(sect_attrs->grp.attrs[0]);
1360 sect_attrs = kzalloc(size[0] + size[1], GFP_KERNEL);
1361 if (sect_attrs == NULL)
1364 /* Setup section attributes. */
1365 sect_attrs->grp.name = "sections";
1366 sect_attrs->grp.attrs = (void *)sect_attrs + size[0];
1368 sect_attrs->nsections = 0;
1369 sattr = §_attrs->attrs[0];
1370 gattr = §_attrs->grp.attrs[0];
1371 for (i = 0; i < info->hdr->e_shnum; i++) {
1372 Elf_Shdr *sec = &info->sechdrs[i];
1373 if (sect_empty(sec))
1375 sattr->address = sec->sh_addr;
1376 sattr->name = kstrdup(info->secstrings + sec->sh_name,
1378 if (sattr->name == NULL)
1380 sect_attrs->nsections++;
1381 sysfs_attr_init(&sattr->mattr.attr);
1382 sattr->mattr.show = module_sect_show;
1383 sattr->mattr.store = NULL;
1384 sattr->mattr.attr.name = sattr->name;
1385 sattr->mattr.attr.mode = S_IRUGO;
1386 *(gattr++) = &(sattr++)->mattr.attr;
1390 if (sysfs_create_group(&mod->mkobj.kobj, §_attrs->grp))
1393 mod->sect_attrs = sect_attrs;
1396 free_sect_attrs(sect_attrs);
1399 static void remove_sect_attrs(struct module *mod)
1401 if (mod->sect_attrs) {
1402 sysfs_remove_group(&mod->mkobj.kobj,
1403 &mod->sect_attrs->grp);
1404 /* We are positive that no one is using any sect attrs
1405 * at this point. Deallocate immediately. */
1406 free_sect_attrs(mod->sect_attrs);
1407 mod->sect_attrs = NULL;
1412 * /sys/module/foo/notes/.section.name gives contents of SHT_NOTE sections.
1415 struct module_notes_attrs {
1416 struct kobject *dir;
1418 struct bin_attribute attrs[0];
1421 static ssize_t module_notes_read(struct file *filp, struct kobject *kobj,
1422 struct bin_attribute *bin_attr,
1423 char *buf, loff_t pos, size_t count)
1426 * The caller checked the pos and count against our size.
1428 memcpy(buf, bin_attr->private + pos, count);
1432 static void free_notes_attrs(struct module_notes_attrs *notes_attrs,
1435 if (notes_attrs->dir) {
1437 sysfs_remove_bin_file(notes_attrs->dir,
1438 ¬es_attrs->attrs[i]);
1439 kobject_put(notes_attrs->dir);
1444 static void add_notes_attrs(struct module *mod, const struct load_info *info)
1446 unsigned int notes, loaded, i;
1447 struct module_notes_attrs *notes_attrs;
1448 struct bin_attribute *nattr;
1450 /* failed to create section attributes, so can't create notes */
1451 if (!mod->sect_attrs)
1454 /* Count notes sections and allocate structures. */
1456 for (i = 0; i < info->hdr->e_shnum; i++)
1457 if (!sect_empty(&info->sechdrs[i]) &&
1458 (info->sechdrs[i].sh_type == SHT_NOTE))
1464 notes_attrs = kzalloc(sizeof(*notes_attrs)
1465 + notes * sizeof(notes_attrs->attrs[0]),
1467 if (notes_attrs == NULL)
1470 notes_attrs->notes = notes;
1471 nattr = ¬es_attrs->attrs[0];
1472 for (loaded = i = 0; i < info->hdr->e_shnum; ++i) {
1473 if (sect_empty(&info->sechdrs[i]))
1475 if (info->sechdrs[i].sh_type == SHT_NOTE) {
1476 sysfs_bin_attr_init(nattr);
1477 nattr->attr.name = mod->sect_attrs->attrs[loaded].name;
1478 nattr->attr.mode = S_IRUGO;
1479 nattr->size = info->sechdrs[i].sh_size;
1480 nattr->private = (void *) info->sechdrs[i].sh_addr;
1481 nattr->read = module_notes_read;
1487 notes_attrs->dir = kobject_create_and_add("notes", &mod->mkobj.kobj);
1488 if (!notes_attrs->dir)
1491 for (i = 0; i < notes; ++i)
1492 if (sysfs_create_bin_file(notes_attrs->dir,
1493 ¬es_attrs->attrs[i]))
1496 mod->notes_attrs = notes_attrs;
1500 free_notes_attrs(notes_attrs, i);
1503 static void remove_notes_attrs(struct module *mod)
1505 if (mod->notes_attrs)
1506 free_notes_attrs(mod->notes_attrs, mod->notes_attrs->notes);
1511 static inline void add_sect_attrs(struct module *mod,
1512 const struct load_info *info)
1516 static inline void remove_sect_attrs(struct module *mod)
1520 static inline void add_notes_attrs(struct module *mod,
1521 const struct load_info *info)
1525 static inline void remove_notes_attrs(struct module *mod)
1528 #endif /* CONFIG_KALLSYMS */
1530 static void add_usage_links(struct module *mod)
1532 #ifdef CONFIG_MODULE_UNLOAD
1533 struct module_use *use;
1536 mutex_lock(&module_mutex);
1537 list_for_each_entry(use, &mod->target_list, target_list) {
1538 nowarn = sysfs_create_link(use->target->holders_dir,
1539 &mod->mkobj.kobj, mod->name);
1541 mutex_unlock(&module_mutex);
1545 static void del_usage_links(struct module *mod)
1547 #ifdef CONFIG_MODULE_UNLOAD
1548 struct module_use *use;
1550 mutex_lock(&module_mutex);
1551 list_for_each_entry(use, &mod->target_list, target_list)
1552 sysfs_remove_link(use->target->holders_dir, mod->name);
1553 mutex_unlock(&module_mutex);
1557 static int module_add_modinfo_attrs(struct module *mod)
1559 struct module_attribute *attr;
1560 struct module_attribute *temp_attr;
1564 mod->modinfo_attrs = kzalloc((sizeof(struct module_attribute) *
1565 (ARRAY_SIZE(modinfo_attrs) + 1)),
1567 if (!mod->modinfo_attrs)
1570 temp_attr = mod->modinfo_attrs;
1571 for (i = 0; (attr = modinfo_attrs[i]) && !error; i++) {
1573 (attr->test && attr->test(mod))) {
1574 memcpy(temp_attr, attr, sizeof(*temp_attr));
1575 sysfs_attr_init(&temp_attr->attr);
1576 error = sysfs_create_file(&mod->mkobj.kobj,
1584 static void module_remove_modinfo_attrs(struct module *mod)
1586 struct module_attribute *attr;
1589 for (i = 0; (attr = &mod->modinfo_attrs[i]); i++) {
1590 /* pick a field to test for end of list */
1591 if (!attr->attr.name)
1593 sysfs_remove_file(&mod->mkobj.kobj, &attr->attr);
1597 kfree(mod->modinfo_attrs);
1600 static void mod_kobject_put(struct module *mod)
1602 DECLARE_COMPLETION_ONSTACK(c);
1603 mod->mkobj.kobj_completion = &c;
1604 kobject_put(&mod->mkobj.kobj);
1605 wait_for_completion(&c);
1608 static int mod_sysfs_init(struct module *mod)
1611 struct kobject *kobj;
1613 if (!module_sysfs_initialized) {
1614 pr_err("%s: module sysfs not initialized\n", mod->name);
1619 kobj = kset_find_obj(module_kset, mod->name);
1621 pr_err("%s: module is already loaded\n", mod->name);
1627 mod->mkobj.mod = mod;
1629 memset(&mod->mkobj.kobj, 0, sizeof(mod->mkobj.kobj));
1630 mod->mkobj.kobj.kset = module_kset;
1631 err = kobject_init_and_add(&mod->mkobj.kobj, &module_ktype, NULL,
1634 mod_kobject_put(mod);
1636 /* delay uevent until full sysfs population */
1641 static int mod_sysfs_setup(struct module *mod,
1642 const struct load_info *info,
1643 struct kernel_param *kparam,
1644 unsigned int num_params)
1648 err = mod_sysfs_init(mod);
1652 mod->holders_dir = kobject_create_and_add("holders", &mod->mkobj.kobj);
1653 if (!mod->holders_dir) {
1658 err = module_param_sysfs_setup(mod, kparam, num_params);
1660 goto out_unreg_holders;
1662 err = module_add_modinfo_attrs(mod);
1664 goto out_unreg_param;
1666 add_usage_links(mod);
1667 add_sect_attrs(mod, info);
1668 add_notes_attrs(mod, info);
1670 kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
1674 module_param_sysfs_remove(mod);
1676 kobject_put(mod->holders_dir);
1678 mod_kobject_put(mod);
1683 static void mod_sysfs_fini(struct module *mod)
1685 remove_notes_attrs(mod);
1686 remove_sect_attrs(mod);
1687 mod_kobject_put(mod);
1690 #else /* !CONFIG_SYSFS */
1692 static int mod_sysfs_setup(struct module *mod,
1693 const struct load_info *info,
1694 struct kernel_param *kparam,
1695 unsigned int num_params)
1700 static void mod_sysfs_fini(struct module *mod)
1704 static void module_remove_modinfo_attrs(struct module *mod)
1708 static void del_usage_links(struct module *mod)
1712 #endif /* CONFIG_SYSFS */
1714 static void mod_sysfs_teardown(struct module *mod)
1716 del_usage_links(mod);
1717 module_remove_modinfo_attrs(mod);
1718 module_param_sysfs_remove(mod);
1719 kobject_put(mod->mkobj.drivers_dir);
1720 kobject_put(mod->holders_dir);
1721 mod_sysfs_fini(mod);
1724 #ifdef CONFIG_DEBUG_SET_MODULE_RONX
1726 * LKM RO/NX protection: protect module's text/ro-data
1727 * from modification and any data from execution.
1729 void set_page_attributes(void *start, void *end, int (*set)(unsigned long start, int num_pages))
1731 unsigned long begin_pfn = PFN_DOWN((unsigned long)start);
1732 unsigned long end_pfn = PFN_DOWN((unsigned long)end);
1734 if (end_pfn > begin_pfn)
1735 set(begin_pfn << PAGE_SHIFT, end_pfn - begin_pfn);
1738 static void set_section_ro_nx(void *base,
1739 unsigned long text_size,
1740 unsigned long ro_size,
1741 unsigned long total_size)
1743 /* begin and end PFNs of the current subsection */
1744 unsigned long begin_pfn;
1745 unsigned long end_pfn;
1748 * Set RO for module text and RO-data:
1749 * - Always protect first page.
1750 * - Do not protect last partial page.
1753 set_page_attributes(base, base + ro_size, set_memory_ro);
1756 * Set NX permissions for module data:
1757 * - Do not protect first partial page.
1758 * - Always protect last page.
1760 if (total_size > text_size) {
1761 begin_pfn = PFN_UP((unsigned long)base + text_size);
1762 end_pfn = PFN_UP((unsigned long)base + total_size);
1763 if (end_pfn > begin_pfn)
1764 set_memory_nx(begin_pfn << PAGE_SHIFT, end_pfn - begin_pfn);
1768 static void unset_module_core_ro_nx(struct module *mod)
1770 set_page_attributes(mod->module_core + mod->core_text_size,
1771 mod->module_core + mod->core_size,
1773 set_page_attributes(mod->module_core,
1774 mod->module_core + mod->core_ro_size,
1778 static void unset_module_init_ro_nx(struct module *mod)
1780 set_page_attributes(mod->module_init + mod->init_text_size,
1781 mod->module_init + mod->init_size,
1783 set_page_attributes(mod->module_init,
1784 mod->module_init + mod->init_ro_size,
1788 /* Iterate through all modules and set each module's text as RW */
1789 void set_all_modules_text_rw(void)
1793 mutex_lock(&module_mutex);
1794 list_for_each_entry_rcu(mod, &modules, list) {
1795 if (mod->state == MODULE_STATE_UNFORMED)
1797 if ((mod->module_core) && (mod->core_text_size)) {
1798 set_page_attributes(mod->module_core,
1799 mod->module_core + mod->core_text_size,
1802 if ((mod->module_init) && (mod->init_text_size)) {
1803 set_page_attributes(mod->module_init,
1804 mod->module_init + mod->init_text_size,
1808 mutex_unlock(&module_mutex);
1811 /* Iterate through all modules and set each module's text as RO */
1812 void set_all_modules_text_ro(void)
1816 mutex_lock(&module_mutex);
1817 list_for_each_entry_rcu(mod, &modules, list) {
1818 if (mod->state == MODULE_STATE_UNFORMED)
1820 if ((mod->module_core) && (mod->core_text_size)) {
1821 set_page_attributes(mod->module_core,
1822 mod->module_core + mod->core_text_size,
1825 if ((mod->module_init) && (mod->init_text_size)) {
1826 set_page_attributes(mod->module_init,
1827 mod->module_init + mod->init_text_size,
1831 mutex_unlock(&module_mutex);
1834 static inline void set_section_ro_nx(void *base, unsigned long text_size, unsigned long ro_size, unsigned long total_size) { }
1835 static void unset_module_core_ro_nx(struct module *mod) { }
1836 static void unset_module_init_ro_nx(struct module *mod) { }
1839 void __weak module_memfree(void *module_region)
1841 vfree(module_region);
1844 void __weak module_arch_cleanup(struct module *mod)
1848 void __weak module_arch_freeing_init(struct module *mod)
1852 /* Free a module, remove from lists, etc. */
1853 static void free_module(struct module *mod)
1855 trace_module_free(mod);
1857 mod_sysfs_teardown(mod);
1859 /* We leave it in list to prevent duplicate loads, but make sure
1860 * that noone uses it while it's being deconstructed. */
1861 mutex_lock(&module_mutex);
1862 mod->state = MODULE_STATE_UNFORMED;
1863 mutex_unlock(&module_mutex);
1865 /* Remove dynamic debug info */
1866 ddebug_remove_module(mod->name);
1868 /* Arch-specific cleanup. */
1869 module_arch_cleanup(mod);
1871 /* Module unload stuff */
1872 module_unload_free(mod);
1874 /* Free any allocated parameters. */
1875 destroy_params(mod->kp, mod->num_kp);
1877 /* Now we can delete it from the lists */
1878 mutex_lock(&module_mutex);
1879 /* Unlink carefully: kallsyms could be walking list. */
1880 list_del_rcu(&mod->list);
1881 /* Remove this module from bug list, this uses list_del_rcu */
1882 module_bug_cleanup(mod);
1883 /* Wait for RCU-sched synchronizing before releasing mod->list and buglist. */
1884 synchronize_sched();
1885 mutex_unlock(&module_mutex);
1887 /* This may be NULL, but that's OK */
1888 unset_module_init_ro_nx(mod);
1889 module_arch_freeing_init(mod);
1890 module_memfree(mod->module_init);
1892 percpu_modfree(mod);
1894 /* Free lock-classes; relies on the preceding sync_rcu(). */
1895 lockdep_free_key_range(mod->module_core, mod->core_size);
1897 /* Finally, free the core (containing the module structure) */
1898 unset_module_core_ro_nx(mod);
1899 module_memfree(mod->module_core);
1902 update_protections(current->mm);
1906 void *__symbol_get(const char *symbol)
1908 struct module *owner;
1909 const struct kernel_symbol *sym;
1912 sym = find_symbol(symbol, &owner, NULL, true, true);
1913 if (sym && strong_try_module_get(owner))
1917 return sym ? (void *)sym->value : NULL;
1919 EXPORT_SYMBOL_GPL(__symbol_get);
1922 * Ensure that an exported symbol [global namespace] does not already exist
1923 * in the kernel or in some other module's exported symbol table.
1925 * You must hold the module_mutex.
1927 static int verify_export_symbols(struct module *mod)
1930 struct module *owner;
1931 const struct kernel_symbol *s;
1933 const struct kernel_symbol *sym;
1936 { mod->syms, mod->num_syms },
1937 { mod->gpl_syms, mod->num_gpl_syms },
1938 { mod->gpl_future_syms, mod->num_gpl_future_syms },
1939 #ifdef CONFIG_UNUSED_SYMBOLS
1940 { mod->unused_syms, mod->num_unused_syms },
1941 { mod->unused_gpl_syms, mod->num_unused_gpl_syms },
1945 for (i = 0; i < ARRAY_SIZE(arr); i++) {
1946 for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
1947 if (find_symbol(s->name, &owner, NULL, true, false)) {
1948 pr_err("%s: exports duplicate symbol %s"
1950 mod->name, s->name, module_name(owner));
1958 /* Change all symbols so that st_value encodes the pointer directly. */
1959 static int simplify_symbols(struct module *mod, const struct load_info *info)
1961 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
1962 Elf_Sym *sym = (void *)symsec->sh_addr;
1963 unsigned long secbase;
1966 const struct kernel_symbol *ksym;
1968 for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
1969 const char *name = info->strtab + sym[i].st_name;
1971 switch (sym[i].st_shndx) {
1973 /* Ignore common symbols */
1974 if (!strncmp(name, "__gnu_lto", 9))
1977 /* We compiled with -fno-common. These are not
1978 supposed to happen. */
1979 pr_debug("Common symbol: %s\n", name);
1980 pr_warn("%s: please compile with -fno-common\n",
1986 /* Don't need to do anything */
1987 pr_debug("Absolute symbol: 0x%08lx\n",
1988 (long)sym[i].st_value);
1992 ksym = resolve_symbol_wait(mod, info, name);
1993 /* Ok if resolved. */
1994 if (ksym && !IS_ERR(ksym)) {
1995 sym[i].st_value = ksym->value;
2000 if (!ksym && ELF_ST_BIND(sym[i].st_info) == STB_WEAK)
2003 pr_warn("%s: Unknown symbol %s (err %li)\n",
2004 mod->name, name, PTR_ERR(ksym));
2005 ret = PTR_ERR(ksym) ?: -ENOENT;
2009 /* Divert to percpu allocation if a percpu var. */
2010 if (sym[i].st_shndx == info->index.pcpu)
2011 secbase = (unsigned long)mod_percpu(mod);
2013 secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
2014 sym[i].st_value += secbase;
2022 static int apply_relocations(struct module *mod, const struct load_info *info)
2027 /* Now do relocations. */
2028 for (i = 1; i < info->hdr->e_shnum; i++) {
2029 unsigned int infosec = info->sechdrs[i].sh_info;
2031 /* Not a valid relocation section? */
2032 if (infosec >= info->hdr->e_shnum)
2035 /* Don't bother with non-allocated sections */
2036 if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
2039 if (info->sechdrs[i].sh_type == SHT_REL)
2040 err = apply_relocate(info->sechdrs, info->strtab,
2041 info->index.sym, i, mod);
2042 else if (info->sechdrs[i].sh_type == SHT_RELA)
2043 err = apply_relocate_add(info->sechdrs, info->strtab,
2044 info->index.sym, i, mod);
2051 /* Additional bytes needed by arch in front of individual sections */
2052 unsigned int __weak arch_mod_section_prepend(struct module *mod,
2053 unsigned int section)
2055 /* default implementation just returns zero */
2059 /* Update size with this section: return offset. */
2060 static long get_offset(struct module *mod, unsigned int *size,
2061 Elf_Shdr *sechdr, unsigned int section)
2065 *size += arch_mod_section_prepend(mod, section);
2066 ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
2067 *size = ret + sechdr->sh_size;
2071 /* Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
2072 might -- code, read-only data, read-write data, small data. Tally
2073 sizes, and place the offsets into sh_entsize fields: high bit means it
2075 static void layout_sections(struct module *mod, struct load_info *info)
2077 static unsigned long const masks[][2] = {
2078 /* NOTE: all executable code must be the first section
2079 * in this array; otherwise modify the text_size
2080 * finder in the two loops below */
2081 { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
2082 { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
2083 { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
2084 { ARCH_SHF_SMALL | SHF_ALLOC, 0 }
2088 for (i = 0; i < info->hdr->e_shnum; i++)
2089 info->sechdrs[i].sh_entsize = ~0UL;
2091 pr_debug("Core section allocation order:\n");
2092 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2093 for (i = 0; i < info->hdr->e_shnum; ++i) {
2094 Elf_Shdr *s = &info->sechdrs[i];
2095 const char *sname = info->secstrings + s->sh_name;
2097 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2098 || (s->sh_flags & masks[m][1])
2099 || s->sh_entsize != ~0UL
2100 || strstarts(sname, ".init"))
2102 s->sh_entsize = get_offset(mod, &mod->core_size, s, i);
2103 pr_debug("\t%s\n", sname);
2106 case 0: /* executable */
2107 mod->core_size = debug_align(mod->core_size);
2108 mod->core_text_size = mod->core_size;
2110 case 1: /* RO: text and ro-data */
2111 mod->core_size = debug_align(mod->core_size);
2112 mod->core_ro_size = mod->core_size;
2114 case 3: /* whole core */
2115 mod->core_size = debug_align(mod->core_size);
2120 pr_debug("Init section allocation order:\n");
2121 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2122 for (i = 0; i < info->hdr->e_shnum; ++i) {
2123 Elf_Shdr *s = &info->sechdrs[i];
2124 const char *sname = info->secstrings + s->sh_name;
2126 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2127 || (s->sh_flags & masks[m][1])
2128 || s->sh_entsize != ~0UL
2129 || !strstarts(sname, ".init"))
2131 s->sh_entsize = (get_offset(mod, &mod->init_size, s, i)
2132 | INIT_OFFSET_MASK);
2133 pr_debug("\t%s\n", sname);
2136 case 0: /* executable */
2137 mod->init_size = debug_align(mod->init_size);
2138 mod->init_text_size = mod->init_size;
2140 case 1: /* RO: text and ro-data */
2141 mod->init_size = debug_align(mod->init_size);
2142 mod->init_ro_size = mod->init_size;
2144 case 3: /* whole init */
2145 mod->init_size = debug_align(mod->init_size);
2151 static void set_license(struct module *mod, const char *license)
2154 license = "unspecified";
2156 if (!license_is_gpl_compatible(license)) {
2157 if (!test_taint(TAINT_PROPRIETARY_MODULE))
2158 pr_warn("%s: module license '%s' taints kernel.\n",
2159 mod->name, license);
2160 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2161 LOCKDEP_NOW_UNRELIABLE);
2165 /* Parse tag=value strings from .modinfo section */
2166 static char *next_string(char *string, unsigned long *secsize)
2168 /* Skip non-zero chars */
2171 if ((*secsize)-- <= 1)
2175 /* Skip any zero padding. */
2176 while (!string[0]) {
2178 if ((*secsize)-- <= 1)
2184 static char *get_modinfo(struct load_info *info, const char *tag)
2187 unsigned int taglen = strlen(tag);
2188 Elf_Shdr *infosec = &info->sechdrs[info->index.info];
2189 unsigned long size = infosec->sh_size;
2191 for (p = (char *)infosec->sh_addr; p; p = next_string(p, &size)) {
2192 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
2193 return p + taglen + 1;
2198 static void setup_modinfo(struct module *mod, struct load_info *info)
2200 struct module_attribute *attr;
2203 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2205 attr->setup(mod, get_modinfo(info, attr->attr.name));
2209 static void free_modinfo(struct module *mod)
2211 struct module_attribute *attr;
2214 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2220 #ifdef CONFIG_KALLSYMS
2222 /* lookup symbol in given range of kernel_symbols */
2223 static const struct kernel_symbol *lookup_symbol(const char *name,
2224 const struct kernel_symbol *start,
2225 const struct kernel_symbol *stop)
2227 return bsearch(name, start, stop - start,
2228 sizeof(struct kernel_symbol), cmp_name);
2231 static int is_exported(const char *name, unsigned long value,
2232 const struct module *mod)
2234 const struct kernel_symbol *ks;
2236 ks = lookup_symbol(name, __start___ksymtab, __stop___ksymtab);
2238 ks = lookup_symbol(name, mod->syms, mod->syms + mod->num_syms);
2239 return ks != NULL && ks->value == value;
2243 static char elf_type(const Elf_Sym *sym, const struct load_info *info)
2245 const Elf_Shdr *sechdrs = info->sechdrs;
2247 if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
2248 if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT)
2253 if (sym->st_shndx == SHN_UNDEF)
2255 if (sym->st_shndx == SHN_ABS)
2257 if (sym->st_shndx >= SHN_LORESERVE)
2259 if (sechdrs[sym->st_shndx].sh_flags & SHF_EXECINSTR)
2261 if (sechdrs[sym->st_shndx].sh_flags & SHF_ALLOC
2262 && sechdrs[sym->st_shndx].sh_type != SHT_NOBITS) {
2263 if (!(sechdrs[sym->st_shndx].sh_flags & SHF_WRITE))
2265 else if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2270 if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
2271 if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2276 if (strstarts(info->secstrings + sechdrs[sym->st_shndx].sh_name,
2283 static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
2286 const Elf_Shdr *sec;
2288 if (src->st_shndx == SHN_UNDEF
2289 || src->st_shndx >= shnum
2293 sec = sechdrs + src->st_shndx;
2294 if (!(sec->sh_flags & SHF_ALLOC)
2295 #ifndef CONFIG_KALLSYMS_ALL
2296 || !(sec->sh_flags & SHF_EXECINSTR)
2298 || (sec->sh_entsize & INIT_OFFSET_MASK))
2305 * We only allocate and copy the strings needed by the parts of symtab
2306 * we keep. This is simple, but has the effect of making multiple
2307 * copies of duplicates. We could be more sophisticated, see
2308 * linux-kernel thread starting with
2309 * <73defb5e4bca04a6431392cc341112b1@localhost>.
2311 static void layout_symtab(struct module *mod, struct load_info *info)
2313 Elf_Shdr *symsect = info->sechdrs + info->index.sym;
2314 Elf_Shdr *strsect = info->sechdrs + info->index.str;
2316 unsigned int i, nsrc, ndst, strtab_size = 0;
2318 /* Put symbol section at end of init part of module. */
2319 symsect->sh_flags |= SHF_ALLOC;
2320 symsect->sh_entsize = get_offset(mod, &mod->init_size, symsect,
2321 info->index.sym) | INIT_OFFSET_MASK;
2322 pr_debug("\t%s\n", info->secstrings + symsect->sh_name);
2324 src = (void *)info->hdr + symsect->sh_offset;
2325 nsrc = symsect->sh_size / sizeof(*src);
2327 /* Compute total space required for the core symbols' strtab. */
2328 for (ndst = i = 0; i < nsrc; i++) {
2330 is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum)) {
2331 strtab_size += strlen(&info->strtab[src[i].st_name])+1;
2336 /* Append room for core symbols at end of core part. */
2337 info->symoffs = ALIGN(mod->core_size, symsect->sh_addralign ?: 1);
2338 info->stroffs = mod->core_size = info->symoffs + ndst * sizeof(Elf_Sym);
2339 mod->core_size += strtab_size;
2340 mod->core_size = debug_align(mod->core_size);
2342 /* Put string table section at end of init part of module. */
2343 strsect->sh_flags |= SHF_ALLOC;
2344 strsect->sh_entsize = get_offset(mod, &mod->init_size, strsect,
2345 info->index.str) | INIT_OFFSET_MASK;
2346 mod->init_size = debug_align(mod->init_size);
2347 pr_debug("\t%s\n", info->secstrings + strsect->sh_name);
2350 static void add_kallsyms(struct module *mod, const struct load_info *info)
2352 unsigned int i, ndst;
2356 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2358 mod->symtab = (void *)symsec->sh_addr;
2359 mod->num_symtab = symsec->sh_size / sizeof(Elf_Sym);
2360 /* Make sure we get permanent strtab: don't use info->strtab. */
2361 mod->strtab = (void *)info->sechdrs[info->index.str].sh_addr;
2363 /* Set types up while we still have access to sections. */
2364 for (i = 0; i < mod->num_symtab; i++)
2365 mod->symtab[i].st_info = elf_type(&mod->symtab[i], info);
2367 mod->core_symtab = dst = mod->module_core + info->symoffs;
2368 mod->core_strtab = s = mod->module_core + info->stroffs;
2370 for (ndst = i = 0; i < mod->num_symtab; i++) {
2372 is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum)) {
2374 dst[ndst++].st_name = s - mod->core_strtab;
2375 s += strlcpy(s, &mod->strtab[src[i].st_name],
2379 mod->core_num_syms = ndst;
2382 static inline void layout_symtab(struct module *mod, struct load_info *info)
2386 static void add_kallsyms(struct module *mod, const struct load_info *info)
2389 #endif /* CONFIG_KALLSYMS */
2391 static void dynamic_debug_setup(struct _ddebug *debug, unsigned int num)
2395 #ifdef CONFIG_DYNAMIC_DEBUG
2396 if (ddebug_add_module(debug, num, debug->modname))
2397 pr_err("dynamic debug error adding module: %s\n",
2402 static void dynamic_debug_remove(struct _ddebug *debug)
2405 ddebug_remove_module(debug->modname);
2408 void * __weak module_alloc(unsigned long size)
2410 return vmalloc_exec(size);
2413 static void *module_alloc_update_bounds(unsigned long size)
2415 void *ret = module_alloc(size);
2418 mutex_lock(&module_mutex);
2419 /* Update module bounds. */
2420 if ((unsigned long)ret < module_addr_min)
2421 module_addr_min = (unsigned long)ret;
2422 if ((unsigned long)ret + size > module_addr_max)
2423 module_addr_max = (unsigned long)ret + size;
2424 mutex_unlock(&module_mutex);
2429 #ifdef CONFIG_DEBUG_KMEMLEAK
2430 static void kmemleak_load_module(const struct module *mod,
2431 const struct load_info *info)
2435 /* only scan the sections containing data */
2436 kmemleak_scan_area(mod, sizeof(struct module), GFP_KERNEL);
2438 for (i = 1; i < info->hdr->e_shnum; i++) {
2439 /* Scan all writable sections that's not executable */
2440 if (!(info->sechdrs[i].sh_flags & SHF_ALLOC) ||
2441 !(info->sechdrs[i].sh_flags & SHF_WRITE) ||
2442 (info->sechdrs[i].sh_flags & SHF_EXECINSTR))
2445 kmemleak_scan_area((void *)info->sechdrs[i].sh_addr,
2446 info->sechdrs[i].sh_size, GFP_KERNEL);
2450 static inline void kmemleak_load_module(const struct module *mod,
2451 const struct load_info *info)
2456 #ifdef CONFIG_MODULE_SIG
2457 static int module_sig_check(struct load_info *info)
2460 const unsigned long markerlen = sizeof(MODULE_SIG_STRING) - 1;
2461 const void *mod = info->hdr;
2463 if (info->len > markerlen &&
2464 memcmp(mod + info->len - markerlen, MODULE_SIG_STRING, markerlen) == 0) {
2465 /* We truncate the module to discard the signature */
2466 info->len -= markerlen;
2467 err = mod_verify_sig(mod, &info->len);
2471 info->sig_ok = true;
2475 /* Not having a signature is only an error if we're strict. */
2476 if (err == -ENOKEY && !sig_enforce)
2481 #else /* !CONFIG_MODULE_SIG */
2482 static int module_sig_check(struct load_info *info)
2486 #endif /* !CONFIG_MODULE_SIG */
2488 /* Sanity checks against invalid binaries, wrong arch, weird elf version. */
2489 static int elf_header_check(struct load_info *info)
2491 if (info->len < sizeof(*(info->hdr)))
2494 if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0
2495 || info->hdr->e_type != ET_REL
2496 || !elf_check_arch(info->hdr)
2497 || info->hdr->e_shentsize != sizeof(Elf_Shdr))
2500 if (info->hdr->e_shoff >= info->len
2501 || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
2502 info->len - info->hdr->e_shoff))
2508 #define COPY_CHUNK_SIZE (16*PAGE_SIZE)
2510 static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len)
2513 unsigned long n = min(len, COPY_CHUNK_SIZE);
2515 if (copy_from_user(dst, usrc, n) != 0)
2525 /* Sets info->hdr and info->len. */
2526 static int copy_module_from_user(const void __user *umod, unsigned long len,
2527 struct load_info *info)
2532 if (info->len < sizeof(*(info->hdr)))
2535 err = security_kernel_module_from_file(NULL);
2539 /* Suck in entire file: we'll want most of it. */
2540 info->hdr = __vmalloc(info->len,
2541 GFP_KERNEL | __GFP_HIGHMEM | __GFP_NOWARN, PAGE_KERNEL);
2545 if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) {
2553 /* Sets info->hdr and info->len. */
2554 static int copy_module_from_fd(int fd, struct load_info *info)
2556 struct fd f = fdget(fd);
2565 err = security_kernel_module_from_file(f.file);
2569 err = vfs_getattr(&f.file->f_path, &stat);
2573 if (stat.size > INT_MAX) {
2578 /* Don't hand 0 to vmalloc, it whines. */
2579 if (stat.size == 0) {
2584 info->hdr = vmalloc(stat.size);
2591 while (pos < stat.size) {
2592 bytes = kernel_read(f.file, pos, (char *)(info->hdr) + pos,
2610 static void free_copy(struct load_info *info)
2615 static int rewrite_section_headers(struct load_info *info, int flags)
2619 /* This should always be true, but let's be sure. */
2620 info->sechdrs[0].sh_addr = 0;
2622 for (i = 1; i < info->hdr->e_shnum; i++) {
2623 Elf_Shdr *shdr = &info->sechdrs[i];
2624 if (shdr->sh_type != SHT_NOBITS
2625 && info->len < shdr->sh_offset + shdr->sh_size) {
2626 pr_err("Module len %lu truncated\n", info->len);
2630 /* Mark all sections sh_addr with their address in the
2632 shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
2634 #ifndef CONFIG_MODULE_UNLOAD
2635 /* Don't load .exit sections */
2636 if (strstarts(info->secstrings+shdr->sh_name, ".exit"))
2637 shdr->sh_flags &= ~(unsigned long)SHF_ALLOC;
2641 /* Track but don't keep modinfo and version sections. */
2642 if (flags & MODULE_INIT_IGNORE_MODVERSIONS)
2643 info->index.vers = 0; /* Pretend no __versions section! */
2645 info->index.vers = find_sec(info, "__versions");
2646 info->index.info = find_sec(info, ".modinfo");
2647 info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
2648 info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
2653 * Set up our basic convenience variables (pointers to section headers,
2654 * search for module section index etc), and do some basic section
2657 * Return the temporary module pointer (we'll replace it with the final
2658 * one when we move the module sections around).
2660 static struct module *setup_load_info(struct load_info *info, int flags)
2666 /* Set up the convenience variables */
2667 info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
2668 info->secstrings = (void *)info->hdr
2669 + info->sechdrs[info->hdr->e_shstrndx].sh_offset;
2671 err = rewrite_section_headers(info, flags);
2673 return ERR_PTR(err);
2675 /* Find internal symbols and strings. */
2676 for (i = 1; i < info->hdr->e_shnum; i++) {
2677 if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
2678 info->index.sym = i;
2679 info->index.str = info->sechdrs[i].sh_link;
2680 info->strtab = (char *)info->hdr
2681 + info->sechdrs[info->index.str].sh_offset;
2686 info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
2687 if (!info->index.mod) {
2688 pr_warn("No module found in object\n");
2689 return ERR_PTR(-ENOEXEC);
2691 /* This is temporary: point mod into copy of data. */
2692 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2694 if (info->index.sym == 0) {
2695 pr_warn("%s: module has no symbols (stripped?)\n", mod->name);
2696 return ERR_PTR(-ENOEXEC);
2699 info->index.pcpu = find_pcpusec(info);
2701 /* Check module struct version now, before we try to use module. */
2702 if (!check_modstruct_version(info->sechdrs, info->index.vers, mod))
2703 return ERR_PTR(-ENOEXEC);
2708 static int check_modinfo(struct module *mod, struct load_info *info, int flags)
2710 const char *modmagic = get_modinfo(info, "vermagic");
2713 if (flags & MODULE_INIT_IGNORE_VERMAGIC)
2716 /* This is allowed: modprobe --force will invalidate it. */
2718 err = try_to_force_load(mod, "bad vermagic");
2721 } else if (!same_magic(modmagic, vermagic, info->index.vers)) {
2722 pr_err("%s: version magic '%s' should be '%s'\n",
2723 mod->name, modmagic, vermagic);
2727 if (!get_modinfo(info, "intree"))
2728 add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
2730 if (get_modinfo(info, "staging")) {
2731 add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
2732 pr_warn("%s: module is from the staging directory, the quality "
2733 "is unknown, you have been warned.\n", mod->name);
2736 /* Set up license info based on the info section */
2737 set_license(mod, get_modinfo(info, "license"));
2742 static int find_module_sections(struct module *mod, struct load_info *info)
2744 mod->kp = section_objs(info, "__param",
2745 sizeof(*mod->kp), &mod->num_kp);
2746 mod->syms = section_objs(info, "__ksymtab",
2747 sizeof(*mod->syms), &mod->num_syms);
2748 mod->crcs = section_addr(info, "__kcrctab");
2749 mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
2750 sizeof(*mod->gpl_syms),
2751 &mod->num_gpl_syms);
2752 mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
2753 mod->gpl_future_syms = section_objs(info,
2754 "__ksymtab_gpl_future",
2755 sizeof(*mod->gpl_future_syms),
2756 &mod->num_gpl_future_syms);
2757 mod->gpl_future_crcs = section_addr(info, "__kcrctab_gpl_future");
2759 #ifdef CONFIG_UNUSED_SYMBOLS
2760 mod->unused_syms = section_objs(info, "__ksymtab_unused",
2761 sizeof(*mod->unused_syms),
2762 &mod->num_unused_syms);
2763 mod->unused_crcs = section_addr(info, "__kcrctab_unused");
2764 mod->unused_gpl_syms = section_objs(info, "__ksymtab_unused_gpl",
2765 sizeof(*mod->unused_gpl_syms),
2766 &mod->num_unused_gpl_syms);
2767 mod->unused_gpl_crcs = section_addr(info, "__kcrctab_unused_gpl");
2769 #ifdef CONFIG_CONSTRUCTORS
2770 mod->ctors = section_objs(info, ".ctors",
2771 sizeof(*mod->ctors), &mod->num_ctors);
2773 mod->ctors = section_objs(info, ".init_array",
2774 sizeof(*mod->ctors), &mod->num_ctors);
2775 else if (find_sec(info, ".init_array")) {
2777 * This shouldn't happen with same compiler and binutils
2778 * building all parts of the module.
2780 pr_warn("%s: has both .ctors and .init_array.\n",
2786 #ifdef CONFIG_TRACEPOINTS
2787 mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
2788 sizeof(*mod->tracepoints_ptrs),
2789 &mod->num_tracepoints);
2791 #ifdef HAVE_JUMP_LABEL
2792 mod->jump_entries = section_objs(info, "__jump_table",
2793 sizeof(*mod->jump_entries),
2794 &mod->num_jump_entries);
2796 #ifdef CONFIG_EVENT_TRACING
2797 mod->trace_events = section_objs(info, "_ftrace_events",
2798 sizeof(*mod->trace_events),
2799 &mod->num_trace_events);
2800 mod->trace_enums = section_objs(info, "_ftrace_enum_map",
2801 sizeof(*mod->trace_enums),
2802 &mod->num_trace_enums);
2804 #ifdef CONFIG_TRACING
2805 mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
2806 sizeof(*mod->trace_bprintk_fmt_start),
2807 &mod->num_trace_bprintk_fmt);
2809 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
2810 /* sechdrs[0].sh_size is always zero */
2811 mod->ftrace_callsites = section_objs(info, "__mcount_loc",
2812 sizeof(*mod->ftrace_callsites),
2813 &mod->num_ftrace_callsites);
2816 mod->extable = section_objs(info, "__ex_table",
2817 sizeof(*mod->extable), &mod->num_exentries);
2819 if (section_addr(info, "__obsparm"))
2820 pr_warn("%s: Ignoring obsolete parameters\n", mod->name);
2822 info->debug = section_objs(info, "__verbose",
2823 sizeof(*info->debug), &info->num_debug);
2828 static int move_module(struct module *mod, struct load_info *info)
2833 /* Do the allocs. */
2834 ptr = module_alloc_update_bounds(mod->core_size);
2836 * The pointer to this block is stored in the module structure
2837 * which is inside the block. Just mark it as not being a
2840 kmemleak_not_leak(ptr);
2844 memset(ptr, 0, mod->core_size);
2845 mod->module_core = ptr;
2847 if (mod->init_size) {
2848 ptr = module_alloc_update_bounds(mod->init_size);
2850 * The pointer to this block is stored in the module structure
2851 * which is inside the block. This block doesn't need to be
2852 * scanned as it contains data and code that will be freed
2853 * after the module is initialized.
2855 kmemleak_ignore(ptr);
2857 module_memfree(mod->module_core);
2860 memset(ptr, 0, mod->init_size);
2861 mod->module_init = ptr;
2863 mod->module_init = NULL;
2865 /* Transfer each section which specifies SHF_ALLOC */
2866 pr_debug("final section addresses:\n");
2867 for (i = 0; i < info->hdr->e_shnum; i++) {
2869 Elf_Shdr *shdr = &info->sechdrs[i];
2871 if (!(shdr->sh_flags & SHF_ALLOC))
2874 if (shdr->sh_entsize & INIT_OFFSET_MASK)
2875 dest = mod->module_init
2876 + (shdr->sh_entsize & ~INIT_OFFSET_MASK);
2878 dest = mod->module_core + shdr->sh_entsize;
2880 if (shdr->sh_type != SHT_NOBITS)
2881 memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
2882 /* Update sh_addr to point to copy in image. */
2883 shdr->sh_addr = (unsigned long)dest;
2884 pr_debug("\t0x%lx %s\n",
2885 (long)shdr->sh_addr, info->secstrings + shdr->sh_name);
2891 static int check_module_license_and_versions(struct module *mod)
2894 * ndiswrapper is under GPL by itself, but loads proprietary modules.
2895 * Don't use add_taint_module(), as it would prevent ndiswrapper from
2896 * using GPL-only symbols it needs.
2898 if (strcmp(mod->name, "ndiswrapper") == 0)
2899 add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
2901 /* driverloader was caught wrongly pretending to be under GPL */
2902 if (strcmp(mod->name, "driverloader") == 0)
2903 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2904 LOCKDEP_NOW_UNRELIABLE);
2906 /* lve claims to be GPL but upstream won't provide source */
2907 if (strcmp(mod->name, "lve") == 0)
2908 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2909 LOCKDEP_NOW_UNRELIABLE);
2911 #ifdef CONFIG_MODVERSIONS
2912 if ((mod->num_syms && !mod->crcs)
2913 || (mod->num_gpl_syms && !mod->gpl_crcs)
2914 || (mod->num_gpl_future_syms && !mod->gpl_future_crcs)
2915 #ifdef CONFIG_UNUSED_SYMBOLS
2916 || (mod->num_unused_syms && !mod->unused_crcs)
2917 || (mod->num_unused_gpl_syms && !mod->unused_gpl_crcs)
2920 return try_to_force_load(mod,
2921 "no versions for exported symbols");
2927 static void flush_module_icache(const struct module *mod)
2929 mm_segment_t old_fs;
2931 /* flush the icache in correct context */
2936 * Flush the instruction cache, since we've played with text.
2937 * Do it before processing of module parameters, so the module
2938 * can provide parameter accessor functions of its own.
2940 if (mod->module_init)
2941 flush_icache_range((unsigned long)mod->module_init,
2942 (unsigned long)mod->module_init
2944 flush_icache_range((unsigned long)mod->module_core,
2945 (unsigned long)mod->module_core + mod->core_size);
2950 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
2958 static struct module *layout_and_allocate(struct load_info *info, int flags)
2960 /* Module within temporary copy. */
2964 mod = setup_load_info(info, flags);
2968 err = check_modinfo(mod, info, flags);
2970 return ERR_PTR(err);
2972 /* Allow arches to frob section contents and sizes. */
2973 err = module_frob_arch_sections(info->hdr, info->sechdrs,
2974 info->secstrings, mod);
2976 return ERR_PTR(err);
2978 /* We will do a special allocation for per-cpu sections later. */
2979 info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
2981 /* Determine total sizes, and put offsets in sh_entsize. For now
2982 this is done generically; there doesn't appear to be any
2983 special cases for the architectures. */
2984 layout_sections(mod, info);
2985 layout_symtab(mod, info);
2987 /* Allocate and move to the final place */
2988 err = move_module(mod, info);
2990 return ERR_PTR(err);
2992 /* Module has been copied to its final place now: return it. */
2993 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2994 kmemleak_load_module(mod, info);
2998 /* mod is no longer valid after this! */
2999 static void module_deallocate(struct module *mod, struct load_info *info)
3001 percpu_modfree(mod);
3002 module_arch_freeing_init(mod);
3003 module_memfree(mod->module_init);
3004 module_memfree(mod->module_core);
3007 int __weak module_finalize(const Elf_Ehdr *hdr,
3008 const Elf_Shdr *sechdrs,
3014 static int post_relocation(struct module *mod, const struct load_info *info)
3016 /* Sort exception table now relocations are done. */
3017 sort_extable(mod->extable, mod->extable + mod->num_exentries);
3019 /* Copy relocated percpu area over. */
3020 percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
3021 info->sechdrs[info->index.pcpu].sh_size);
3023 /* Setup kallsyms-specific fields. */
3024 add_kallsyms(mod, info);
3026 /* Arch-specific module finalizing. */
3027 return module_finalize(info->hdr, info->sechdrs, mod);
3030 /* Is this module of this name done loading? No locks held. */
3031 static bool finished_loading(const char *name)
3037 * The module_mutex should not be a heavily contended lock;
3038 * if we get the occasional sleep here, we'll go an extra iteration
3039 * in the wait_event_interruptible(), which is harmless.
3041 sched_annotate_sleep();
3042 mutex_lock(&module_mutex);
3043 mod = find_module_all(name, strlen(name), true);
3044 ret = !mod || mod->state == MODULE_STATE_LIVE
3045 || mod->state == MODULE_STATE_GOING;
3046 mutex_unlock(&module_mutex);
3051 /* Call module constructors. */
3052 static void do_mod_ctors(struct module *mod)
3054 #ifdef CONFIG_CONSTRUCTORS
3057 for (i = 0; i < mod->num_ctors; i++)
3062 /* For freeing module_init on success, in case kallsyms traversing */
3063 struct mod_initfree {
3064 struct rcu_head rcu;
3068 static void do_free_init(struct rcu_head *head)
3070 struct mod_initfree *m = container_of(head, struct mod_initfree, rcu);
3071 module_memfree(m->module_init);
3076 * This is where the real work happens.
3078 * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb
3079 * helper command 'lx-symbols'.
3081 static noinline int do_init_module(struct module *mod)
3084 struct mod_initfree *freeinit;
3086 freeinit = kmalloc(sizeof(*freeinit), GFP_KERNEL);
3091 freeinit->module_init = mod->module_init;
3094 * We want to find out whether @mod uses async during init. Clear
3095 * PF_USED_ASYNC. async_schedule*() will set it.
3097 current->flags &= ~PF_USED_ASYNC;
3100 /* Start the module */
3101 if (mod->init != NULL)
3102 ret = do_one_initcall(mod->init);
3104 goto fail_free_freeinit;
3107 pr_warn("%s: '%s'->init suspiciously returned %d, it should "
3108 "follow 0/-E convention\n"
3109 "%s: loading module anyway...\n",
3110 __func__, mod->name, ret, __func__);
3114 /* Now it's a first class citizen! */
3115 mod->state = MODULE_STATE_LIVE;
3116 blocking_notifier_call_chain(&module_notify_list,
3117 MODULE_STATE_LIVE, mod);
3120 * We need to finish all async code before the module init sequence
3121 * is done. This has potential to deadlock. For example, a newly
3122 * detected block device can trigger request_module() of the
3123 * default iosched from async probing task. Once userland helper
3124 * reaches here, async_synchronize_full() will wait on the async
3125 * task waiting on request_module() and deadlock.
3127 * This deadlock is avoided by perfomring async_synchronize_full()
3128 * iff module init queued any async jobs. This isn't a full
3129 * solution as it will deadlock the same if module loading from
3130 * async jobs nests more than once; however, due to the various
3131 * constraints, this hack seems to be the best option for now.
3132 * Please refer to the following thread for details.
3134 * http://thread.gmane.org/gmane.linux.kernel/1420814
3136 if (current->flags & PF_USED_ASYNC)
3137 async_synchronize_full();
3139 mutex_lock(&module_mutex);
3140 /* Drop initial reference. */
3142 trim_init_extable(mod);
3143 #ifdef CONFIG_KALLSYMS
3144 mod->num_symtab = mod->core_num_syms;
3145 mod->symtab = mod->core_symtab;
3146 mod->strtab = mod->core_strtab;
3148 unset_module_init_ro_nx(mod);
3149 module_arch_freeing_init(mod);
3150 mod->module_init = NULL;
3152 mod->init_ro_size = 0;
3153 mod->init_text_size = 0;
3155 * We want to free module_init, but be aware that kallsyms may be
3156 * walking this with preempt disabled. In all the failure paths, we
3157 * call synchronize_sched(), but we don't want to slow down the success
3158 * path, so use actual RCU here.
3160 call_rcu_sched(&freeinit->rcu, do_free_init);
3161 mutex_unlock(&module_mutex);
3162 wake_up_all(&module_wq);
3169 /* Try to protect us from buggy refcounters. */
3170 mod->state = MODULE_STATE_GOING;
3171 synchronize_sched();
3173 blocking_notifier_call_chain(&module_notify_list,
3174 MODULE_STATE_GOING, mod);
3176 wake_up_all(&module_wq);
3180 static int may_init_module(void)
3182 if (!capable(CAP_SYS_MODULE) || modules_disabled)
3189 * We try to place it in the list now to make sure it's unique before
3190 * we dedicate too many resources. In particular, temporary percpu
3191 * memory exhaustion.
3193 static int add_unformed_module(struct module *mod)
3198 mod->state = MODULE_STATE_UNFORMED;
3201 mutex_lock(&module_mutex);
3202 old = find_module_all(mod->name, strlen(mod->name), true);
3204 if (old->state == MODULE_STATE_COMING
3205 || old->state == MODULE_STATE_UNFORMED) {
3206 /* Wait in case it fails to load. */
3207 mutex_unlock(&module_mutex);
3208 err = wait_event_interruptible(module_wq,
3209 finished_loading(mod->name));
3217 list_add_rcu(&mod->list, &modules);
3221 mutex_unlock(&module_mutex);
3226 static int complete_formation(struct module *mod, struct load_info *info)
3230 mutex_lock(&module_mutex);
3232 /* Find duplicate symbols (must be called under lock). */
3233 err = verify_export_symbols(mod);
3237 /* This relies on module_mutex for list integrity. */
3238 module_bug_finalize(info->hdr, info->sechdrs, mod);
3240 /* Set RO and NX regions for core */
3241 set_section_ro_nx(mod->module_core,
3242 mod->core_text_size,
3246 /* Set RO and NX regions for init */
3247 set_section_ro_nx(mod->module_init,
3248 mod->init_text_size,
3252 /* Mark state as coming so strong_try_module_get() ignores us,
3253 * but kallsyms etc. can see us. */
3254 mod->state = MODULE_STATE_COMING;
3255 mutex_unlock(&module_mutex);
3257 blocking_notifier_call_chain(&module_notify_list,
3258 MODULE_STATE_COMING, mod);
3262 mutex_unlock(&module_mutex);
3266 static int unknown_module_param_cb(char *param, char *val, const char *modname)
3268 /* Check for magic 'dyndbg' arg */
3269 int ret = ddebug_dyndbg_module_param_cb(param, val, modname);
3271 pr_warn("%s: unknown parameter '%s' ignored\n", modname, param);
3275 /* Allocate and load the module: note that size of section 0 is always
3276 zero, and we rely on this for optional sections. */
3277 static int load_module(struct load_info *info, const char __user *uargs,
3284 err = module_sig_check(info);
3288 err = elf_header_check(info);
3292 /* Figure out module layout, and allocate all the memory. */
3293 mod = layout_and_allocate(info, flags);
3299 /* Reserve our place in the list. */
3300 err = add_unformed_module(mod);
3304 #ifdef CONFIG_MODULE_SIG
3305 mod->sig_ok = info->sig_ok;
3307 pr_notice_once("%s: module verification failed: signature "
3308 "and/or required key missing - tainting "
3309 "kernel\n", mod->name);
3310 add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
3314 /* To avoid stressing percpu allocator, do this once we're unique. */
3315 err = percpu_modalloc(mod, info);
3319 /* Now module is in final location, initialize linked lists, etc. */
3320 err = module_unload_init(mod);
3324 /* Now we've got everything in the final locations, we can
3325 * find optional sections. */
3326 err = find_module_sections(mod, info);
3330 err = check_module_license_and_versions(mod);
3334 /* Set up MODINFO_ATTR fields */
3335 setup_modinfo(mod, info);
3337 /* Fix up syms, so that st_value is a pointer to location. */
3338 err = simplify_symbols(mod, info);
3342 err = apply_relocations(mod, info);
3346 err = post_relocation(mod, info);
3350 flush_module_icache(mod);
3352 /* Now copy in args */
3353 mod->args = strndup_user(uargs, ~0UL >> 1);
3354 if (IS_ERR(mod->args)) {
3355 err = PTR_ERR(mod->args);
3356 goto free_arch_cleanup;
3359 dynamic_debug_setup(info->debug, info->num_debug);
3361 /* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
3362 ftrace_module_init(mod);
3364 /* Finally it's fully formed, ready to start executing. */
3365 err = complete_formation(mod, info);
3367 goto ddebug_cleanup;
3369 /* Module is ready to execute: parsing args may do that. */
3370 after_dashes = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
3371 -32768, 32767, unknown_module_param_cb);
3372 if (IS_ERR(after_dashes)) {
3373 err = PTR_ERR(after_dashes);
3375 } else if (after_dashes) {
3376 pr_warn("%s: parameters '%s' after `--' ignored\n",
3377 mod->name, after_dashes);
3380 /* Link in to syfs. */
3381 err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
3385 /* Get rid of temporary copy. */
3389 trace_module_load(mod);
3391 return do_init_module(mod);
3394 /* module_bug_cleanup needs module_mutex protection */
3395 mutex_lock(&module_mutex);
3396 module_bug_cleanup(mod);
3397 mutex_unlock(&module_mutex);
3399 /* we can't deallocate the module until we clear memory protection */
3400 unset_module_init_ro_nx(mod);
3401 unset_module_core_ro_nx(mod);
3404 dynamic_debug_remove(info->debug);
3405 synchronize_sched();
3408 module_arch_cleanup(mod);
3412 module_unload_free(mod);
3414 mutex_lock(&module_mutex);
3415 /* Unlink carefully: kallsyms could be walking list. */
3416 list_del_rcu(&mod->list);
3417 wake_up_all(&module_wq);
3418 /* Wait for RCU-sched synchronizing before releasing mod->list. */
3419 synchronize_sched();
3420 mutex_unlock(&module_mutex);
3422 /* Free lock-classes; relies on the preceding sync_rcu() */
3423 lockdep_free_key_range(mod->module_core, mod->core_size);
3425 module_deallocate(mod, info);
3431 SYSCALL_DEFINE3(init_module, void __user *, umod,
3432 unsigned long, len, const char __user *, uargs)
3435 struct load_info info = { };
3437 err = may_init_module();
3441 pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
3444 err = copy_module_from_user(umod, len, &info);
3448 return load_module(&info, uargs, 0);
3451 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
3454 struct load_info info = { };
3456 err = may_init_module();
3460 pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
3462 if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
3463 |MODULE_INIT_IGNORE_VERMAGIC))
3466 err = copy_module_from_fd(fd, &info);
3470 return load_module(&info, uargs, flags);
3473 static inline int within(unsigned long addr, void *start, unsigned long size)
3475 return ((void *)addr >= start && (void *)addr < start + size);
3478 #ifdef CONFIG_KALLSYMS
3480 * This ignores the intensely annoying "mapping symbols" found
3481 * in ARM ELF files: $a, $t and $d.
3483 static inline int is_arm_mapping_symbol(const char *str)
3485 if (str[0] == '.' && str[1] == 'L')
3487 return str[0] == '$' && strchr("axtd", str[1])
3488 && (str[2] == '\0' || str[2] == '.');
3491 static const char *get_ksymbol(struct module *mod,
3493 unsigned long *size,
3494 unsigned long *offset)
3496 unsigned int i, best = 0;
3497 unsigned long nextval;
3499 /* At worse, next value is at end of module */
3500 if (within_module_init(addr, mod))
3501 nextval = (unsigned long)mod->module_init+mod->init_text_size;
3503 nextval = (unsigned long)mod->module_core+mod->core_text_size;
3505 /* Scan for closest preceding symbol, and next symbol. (ELF
3506 starts real symbols at 1). */
3507 for (i = 1; i < mod->num_symtab; i++) {
3508 if (mod->symtab[i].st_shndx == SHN_UNDEF)
3511 /* We ignore unnamed symbols: they're uninformative
3512 * and inserted at a whim. */
3513 if (mod->symtab[i].st_value <= addr
3514 && mod->symtab[i].st_value > mod->symtab[best].st_value
3515 && *(mod->strtab + mod->symtab[i].st_name) != '\0'
3516 && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
3518 if (mod->symtab[i].st_value > addr
3519 && mod->symtab[i].st_value < nextval
3520 && *(mod->strtab + mod->symtab[i].st_name) != '\0'
3521 && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
3522 nextval = mod->symtab[i].st_value;
3529 *size = nextval - mod->symtab[best].st_value;
3531 *offset = addr - mod->symtab[best].st_value;
3532 return mod->strtab + mod->symtab[best].st_name;
3535 /* For kallsyms to ask for address resolution. NULL means not found. Careful
3536 * not to lock to avoid deadlock on oopses, simply disable preemption. */
3537 const char *module_address_lookup(unsigned long addr,
3538 unsigned long *size,
3539 unsigned long *offset,
3544 const char *ret = NULL;
3547 list_for_each_entry_rcu(mod, &modules, list) {
3548 if (mod->state == MODULE_STATE_UNFORMED)
3550 if (within_module(addr, mod)) {
3552 *modname = mod->name;
3553 ret = get_ksymbol(mod, addr, size, offset);
3557 /* Make a copy in here where it's safe */
3559 strncpy(namebuf, ret, KSYM_NAME_LEN - 1);
3566 int lookup_module_symbol_name(unsigned long addr, char *symname)
3571 list_for_each_entry_rcu(mod, &modules, list) {
3572 if (mod->state == MODULE_STATE_UNFORMED)
3574 if (within_module(addr, mod)) {
3577 sym = get_ksymbol(mod, addr, NULL, NULL);
3580 strlcpy(symname, sym, KSYM_NAME_LEN);
3590 int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size,
3591 unsigned long *offset, char *modname, char *name)
3596 list_for_each_entry_rcu(mod, &modules, list) {
3597 if (mod->state == MODULE_STATE_UNFORMED)
3599 if (within_module(addr, mod)) {
3602 sym = get_ksymbol(mod, addr, size, offset);
3606 strlcpy(modname, mod->name, MODULE_NAME_LEN);
3608 strlcpy(name, sym, KSYM_NAME_LEN);
3618 int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
3619 char *name, char *module_name, int *exported)
3624 list_for_each_entry_rcu(mod, &modules, list) {
3625 if (mod->state == MODULE_STATE_UNFORMED)
3627 if (symnum < mod->num_symtab) {
3628 *value = mod->symtab[symnum].st_value;
3629 *type = mod->symtab[symnum].st_info;
3630 strlcpy(name, mod->strtab + mod->symtab[symnum].st_name,
3632 strlcpy(module_name, mod->name, MODULE_NAME_LEN);
3633 *exported = is_exported(name, *value, mod);
3637 symnum -= mod->num_symtab;
3643 static unsigned long mod_find_symname(struct module *mod, const char *name)
3647 for (i = 0; i < mod->num_symtab; i++)
3648 if (strcmp(name, mod->strtab+mod->symtab[i].st_name) == 0 &&
3649 mod->symtab[i].st_info != 'U')
3650 return mod->symtab[i].st_value;
3654 /* Look for this name: can be of form module:name. */
3655 unsigned long module_kallsyms_lookup_name(const char *name)
3659 unsigned long ret = 0;
3661 /* Don't lock: we're in enough trouble already. */
3663 if ((colon = strchr(name, ':')) != NULL) {
3664 if ((mod = find_module_all(name, colon - name, false)) != NULL)
3665 ret = mod_find_symname(mod, colon+1);
3667 list_for_each_entry_rcu(mod, &modules, list) {
3668 if (mod->state == MODULE_STATE_UNFORMED)
3670 if ((ret = mod_find_symname(mod, name)) != 0)
3678 int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
3679 struct module *, unsigned long),
3686 module_assert_mutex();
3688 list_for_each_entry(mod, &modules, list) {
3689 if (mod->state == MODULE_STATE_UNFORMED)
3691 for (i = 0; i < mod->num_symtab; i++) {
3692 ret = fn(data, mod->strtab + mod->symtab[i].st_name,
3693 mod, mod->symtab[i].st_value);
3700 #endif /* CONFIG_KALLSYMS */
3702 static char *module_flags(struct module *mod, char *buf)
3706 BUG_ON(mod->state == MODULE_STATE_UNFORMED);
3708 mod->state == MODULE_STATE_GOING ||
3709 mod->state == MODULE_STATE_COMING) {
3711 bx += module_flags_taint(mod, buf + bx);
3712 /* Show a - for module-is-being-unloaded */
3713 if (mod->state == MODULE_STATE_GOING)
3715 /* Show a + for module-is-being-loaded */
3716 if (mod->state == MODULE_STATE_COMING)
3725 #ifdef CONFIG_PROC_FS
3726 /* Called by the /proc file system to return a list of modules. */
3727 static void *m_start(struct seq_file *m, loff_t *pos)
3729 mutex_lock(&module_mutex);
3730 return seq_list_start(&modules, *pos);
3733 static void *m_next(struct seq_file *m, void *p, loff_t *pos)
3735 return seq_list_next(p, &modules, pos);
3738 static void m_stop(struct seq_file *m, void *p)
3740 mutex_unlock(&module_mutex);
3743 static int m_show(struct seq_file *m, void *p)
3745 struct module *mod = list_entry(p, struct module, list);
3748 /* We always ignore unformed modules. */
3749 if (mod->state == MODULE_STATE_UNFORMED)
3752 seq_printf(m, "%s %u",
3753 mod->name, mod->init_size + mod->core_size);
3754 print_unload_info(m, mod);
3756 /* Informative for users. */
3757 seq_printf(m, " %s",
3758 mod->state == MODULE_STATE_GOING ? "Unloading" :
3759 mod->state == MODULE_STATE_COMING ? "Loading" :
3761 /* Used by oprofile and other similar tools. */
3762 seq_printf(m, " 0x%pK", mod->module_core);
3766 seq_printf(m, " %s", module_flags(mod, buf));
3772 /* Format: modulename size refcount deps address
3774 Where refcount is a number or -, and deps is a comma-separated list
3777 static const struct seq_operations modules_op = {
3784 static int modules_open(struct inode *inode, struct file *file)
3786 return seq_open(file, &modules_op);
3789 static const struct file_operations proc_modules_operations = {
3790 .open = modules_open,
3792 .llseek = seq_lseek,
3793 .release = seq_release,
3796 static int __init proc_modules_init(void)
3798 proc_create("modules", 0, NULL, &proc_modules_operations);
3801 module_init(proc_modules_init);
3804 /* Given an address, look for it in the module exception tables. */
3805 const struct exception_table_entry *search_module_extables(unsigned long addr)
3807 const struct exception_table_entry *e = NULL;
3811 list_for_each_entry_rcu(mod, &modules, list) {
3812 if (mod->state == MODULE_STATE_UNFORMED)
3814 if (mod->num_exentries == 0)
3817 e = search_extable(mod->extable,
3818 mod->extable + mod->num_exentries - 1,
3825 /* Now, if we found one, we are running inside it now, hence
3826 we cannot unload the module, hence no refcnt needed. */
3831 * is_module_address - is this address inside a module?
3832 * @addr: the address to check.
3834 * See is_module_text_address() if you simply want to see if the address
3835 * is code (not data).
3837 bool is_module_address(unsigned long addr)
3842 ret = __module_address(addr) != NULL;
3849 * __module_address - get the module which contains an address.
3850 * @addr: the address.
3852 * Must be called with preempt disabled or module mutex held so that
3853 * module doesn't get freed during this.
3855 struct module *__module_address(unsigned long addr)
3859 if (addr < module_addr_min || addr > module_addr_max)
3862 module_assert_mutex_or_preempt();
3864 list_for_each_entry_rcu(mod, &modules, list) {
3865 if (mod->state == MODULE_STATE_UNFORMED)
3867 if (within_module(addr, mod))
3872 EXPORT_SYMBOL_GPL(__module_address);
3875 * is_module_text_address - is this address inside module code?
3876 * @addr: the address to check.
3878 * See is_module_address() if you simply want to see if the address is
3879 * anywhere in a module. See kernel_text_address() for testing if an
3880 * address corresponds to kernel or module code.
3882 bool is_module_text_address(unsigned long addr)
3887 ret = __module_text_address(addr) != NULL;
3894 * __module_text_address - get the module whose code contains an address.
3895 * @addr: the address.
3897 * Must be called with preempt disabled or module mutex held so that
3898 * module doesn't get freed during this.
3900 struct module *__module_text_address(unsigned long addr)
3902 struct module *mod = __module_address(addr);
3904 /* Make sure it's within the text section. */
3905 if (!within(addr, mod->module_init, mod->init_text_size)
3906 && !within(addr, mod->module_core, mod->core_text_size))
3911 EXPORT_SYMBOL_GPL(__module_text_address);
3913 /* Don't grab lock, we're oopsing. */
3914 void print_modules(void)
3919 printk(KERN_DEFAULT "Modules linked in:");
3920 /* Most callers should already have preempt disabled, but make sure */
3922 list_for_each_entry_rcu(mod, &modules, list) {
3923 if (mod->state == MODULE_STATE_UNFORMED)
3925 pr_cont(" %s%s", mod->name, module_flags(mod, buf));
3928 if (last_unloaded_module[0])
3929 pr_cont(" [last unloaded: %s]", last_unloaded_module);
3933 #ifdef CONFIG_MODVERSIONS
3934 /* Generate the signature for all relevant module structures here.
3935 * If these change, we don't want to try to parse the module. */
3936 void module_layout(struct module *mod,
3937 struct modversion_info *ver,
3938 struct kernel_param *kp,
3939 struct kernel_symbol *ks,
3940 struct tracepoint * const *tp)
3943 EXPORT_SYMBOL(module_layout);