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/stop_machine.h>
46 #include <linux/device.h>
47 #include <linux/string.h>
48 #include <linux/mutex.h>
49 #include <linux/rculist.h>
50 #include <asm/uaccess.h>
51 #include <asm/cacheflush.h>
52 #include <asm/mmu_context.h>
53 #include <linux/license.h>
54 #include <asm/sections.h>
55 #include <linux/tracepoint.h>
56 #include <linux/ftrace.h>
57 #include <linux/async.h>
58 #include <linux/percpu.h>
59 #include <linux/kmemleak.h>
60 #include <linux/jump_label.h>
61 #include <linux/pfn.h>
62 #include <linux/bsearch.h>
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/module.h>
67 #ifndef ARCH_SHF_SMALL
68 #define ARCH_SHF_SMALL 0
72 * Modules' sections will be aligned on page boundaries
73 * to ensure complete separation of code and data, but
74 * only when CONFIG_DEBUG_SET_MODULE_RONX=y
76 #ifdef CONFIG_DEBUG_SET_MODULE_RONX
77 # define debug_align(X) ALIGN(X, PAGE_SIZE)
79 # define debug_align(X) (X)
83 * Given BASE and SIZE this macro calculates the number of pages the
84 * memory regions occupies
86 #define MOD_NUMBER_OF_PAGES(BASE, SIZE) (((SIZE) > 0) ? \
87 (PFN_DOWN((unsigned long)(BASE) + (SIZE) - 1) - \
88 PFN_DOWN((unsigned long)BASE) + 1) \
91 /* If this is set, the section belongs in the init part of the module */
92 #define INIT_OFFSET_MASK (1UL << (BITS_PER_LONG-1))
96 * 1) List of modules (also safely readable with preempt_disable),
97 * 2) module_use links,
98 * 3) module_addr_min/module_addr_max.
99 * (delete uses stop_machine/add uses RCU list operations). */
100 DEFINE_MUTEX(module_mutex);
101 EXPORT_SYMBOL_GPL(module_mutex);
102 static LIST_HEAD(modules);
103 #ifdef CONFIG_KGDB_KDB
104 struct list_head *kdb_modules = &modules; /* kdb needs the list of modules */
105 #endif /* CONFIG_KGDB_KDB */
108 /* Block module loading/unloading? */
109 int modules_disabled = 0;
110 core_param(nomodule, modules_disabled, bint, 0);
112 /* Waiting for a module to finish initializing? */
113 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
115 static BLOCKING_NOTIFIER_HEAD(module_notify_list);
117 /* Bounds of module allocation, for speeding __module_address.
118 * Protected by module_mutex. */
119 static unsigned long module_addr_min = -1UL, module_addr_max = 0;
121 int register_module_notifier(struct notifier_block * nb)
123 return blocking_notifier_chain_register(&module_notify_list, nb);
125 EXPORT_SYMBOL(register_module_notifier);
127 int unregister_module_notifier(struct notifier_block * nb)
129 return blocking_notifier_chain_unregister(&module_notify_list, nb);
131 EXPORT_SYMBOL(unregister_module_notifier);
137 char *secstrings, *strtab;
138 unsigned long symoffs, stroffs;
139 struct _ddebug *debug;
140 unsigned int num_debug;
142 unsigned int sym, str, mod, vers, info, pcpu;
146 /* We require a truly strong try_module_get(): 0 means failure due to
147 ongoing or failed initialization etc. */
148 static inline int strong_try_module_get(struct module *mod)
150 if (mod && mod->state == MODULE_STATE_COMING)
152 if (try_module_get(mod))
158 static inline void add_taint_module(struct module *mod, unsigned flag)
161 mod->taints |= (1U << flag);
165 * A thread that wants to hold a reference to a module only while it
166 * is running can call this to safely exit. nfsd and lockd use this.
168 void __module_put_and_exit(struct module *mod, long code)
173 EXPORT_SYMBOL(__module_put_and_exit);
175 /* Find a module section: 0 means not found. */
176 static unsigned int find_sec(const struct load_info *info, const char *name)
180 for (i = 1; i < info->hdr->e_shnum; i++) {
181 Elf_Shdr *shdr = &info->sechdrs[i];
182 /* Alloc bit cleared means "ignore it." */
183 if ((shdr->sh_flags & SHF_ALLOC)
184 && strcmp(info->secstrings + shdr->sh_name, name) == 0)
190 /* Find a module section, or NULL. */
191 static void *section_addr(const struct load_info *info, const char *name)
193 /* Section 0 has sh_addr 0. */
194 return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
197 /* Find a module section, or NULL. Fill in number of "objects" in section. */
198 static void *section_objs(const struct load_info *info,
203 unsigned int sec = find_sec(info, name);
205 /* Section 0 has sh_addr 0 and sh_size 0. */
206 *num = info->sechdrs[sec].sh_size / object_size;
207 return (void *)info->sechdrs[sec].sh_addr;
210 /* Provided by the linker */
211 extern const struct kernel_symbol __start___ksymtab[];
212 extern const struct kernel_symbol __stop___ksymtab[];
213 extern const struct kernel_symbol __start___ksymtab_gpl[];
214 extern const struct kernel_symbol __stop___ksymtab_gpl[];
215 extern const struct kernel_symbol __start___ksymtab_gpl_future[];
216 extern const struct kernel_symbol __stop___ksymtab_gpl_future[];
217 extern const unsigned long __start___kcrctab[];
218 extern const unsigned long __start___kcrctab_gpl[];
219 extern const unsigned long __start___kcrctab_gpl_future[];
220 #ifdef CONFIG_UNUSED_SYMBOLS
221 extern const struct kernel_symbol __start___ksymtab_unused[];
222 extern const struct kernel_symbol __stop___ksymtab_unused[];
223 extern const struct kernel_symbol __start___ksymtab_unused_gpl[];
224 extern const struct kernel_symbol __stop___ksymtab_unused_gpl[];
225 extern const unsigned long __start___kcrctab_unused[];
226 extern const unsigned long __start___kcrctab_unused_gpl[];
229 #ifndef CONFIG_MODVERSIONS
230 #define symversion(base, idx) NULL
232 #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
235 static bool each_symbol_in_section(const struct symsearch *arr,
236 unsigned int arrsize,
237 struct module *owner,
238 bool (*fn)(const struct symsearch *syms,
239 struct module *owner,
245 for (j = 0; j < arrsize; j++) {
246 if (fn(&arr[j], owner, data))
253 /* Returns true as soon as fn returns true, otherwise false. */
254 bool each_symbol_section(bool (*fn)(const struct symsearch *arr,
255 struct module *owner,
260 static const struct symsearch arr[] = {
261 { __start___ksymtab, __stop___ksymtab, __start___kcrctab,
262 NOT_GPL_ONLY, false },
263 { __start___ksymtab_gpl, __stop___ksymtab_gpl,
264 __start___kcrctab_gpl,
266 { __start___ksymtab_gpl_future, __stop___ksymtab_gpl_future,
267 __start___kcrctab_gpl_future,
268 WILL_BE_GPL_ONLY, false },
269 #ifdef CONFIG_UNUSED_SYMBOLS
270 { __start___ksymtab_unused, __stop___ksymtab_unused,
271 __start___kcrctab_unused,
272 NOT_GPL_ONLY, true },
273 { __start___ksymtab_unused_gpl, __stop___ksymtab_unused_gpl,
274 __start___kcrctab_unused_gpl,
279 if (each_symbol_in_section(arr, ARRAY_SIZE(arr), NULL, fn, data))
282 list_for_each_entry_rcu(mod, &modules, list) {
283 struct symsearch arr[] = {
284 { mod->syms, mod->syms + mod->num_syms, mod->crcs,
285 NOT_GPL_ONLY, false },
286 { mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
289 { mod->gpl_future_syms,
290 mod->gpl_future_syms + mod->num_gpl_future_syms,
291 mod->gpl_future_crcs,
292 WILL_BE_GPL_ONLY, false },
293 #ifdef CONFIG_UNUSED_SYMBOLS
295 mod->unused_syms + mod->num_unused_syms,
297 NOT_GPL_ONLY, true },
298 { mod->unused_gpl_syms,
299 mod->unused_gpl_syms + mod->num_unused_gpl_syms,
300 mod->unused_gpl_crcs,
305 if (each_symbol_in_section(arr, ARRAY_SIZE(arr), mod, fn, data))
310 EXPORT_SYMBOL_GPL(each_symbol_section);
312 struct find_symbol_arg {
319 struct module *owner;
320 const unsigned long *crc;
321 const struct kernel_symbol *sym;
324 static bool check_symbol(const struct symsearch *syms,
325 struct module *owner,
326 unsigned int symnum, void *data)
328 struct find_symbol_arg *fsa = data;
331 if (syms->licence == GPL_ONLY)
333 if (syms->licence == WILL_BE_GPL_ONLY && fsa->warn) {
334 printk(KERN_WARNING "Symbol %s is being used "
335 "by a non-GPL module, which will not "
336 "be allowed in the future\n", fsa->name);
337 printk(KERN_WARNING "Please see the file "
338 "Documentation/feature-removal-schedule.txt "
339 "in the kernel source tree for more details.\n");
343 #ifdef CONFIG_UNUSED_SYMBOLS
344 if (syms->unused && fsa->warn) {
345 printk(KERN_WARNING "Symbol %s is marked as UNUSED, "
346 "however this module is using it.\n", fsa->name);
348 "This symbol will go away in the future.\n");
350 "Please evalute if this is the right api to use and if "
351 "it really is, submit a report the linux kernel "
352 "mailinglist together with submitting your code for "
358 fsa->crc = symversion(syms->crcs, symnum);
359 fsa->sym = &syms->start[symnum];
363 static int cmp_name(const void *va, const void *vb)
366 const struct kernel_symbol *b;
368 return strcmp(a, b->name);
371 static bool find_symbol_in_section(const struct symsearch *syms,
372 struct module *owner,
375 struct find_symbol_arg *fsa = data;
376 struct kernel_symbol *sym;
378 sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
379 sizeof(struct kernel_symbol), cmp_name);
381 if (sym != NULL && check_symbol(syms, owner, sym - syms->start, data))
387 /* Find a symbol and return it, along with, (optional) crc and
388 * (optional) module which owns it. Needs preempt disabled or module_mutex. */
389 const struct kernel_symbol *find_symbol(const char *name,
390 struct module **owner,
391 const unsigned long **crc,
395 struct find_symbol_arg fsa;
401 if (each_symbol_section(find_symbol_in_section, &fsa)) {
409 pr_debug("Failed to find symbol %s\n", name);
412 EXPORT_SYMBOL_GPL(find_symbol);
414 /* Search for module by name: must hold module_mutex. */
415 struct module *find_module(const char *name)
419 list_for_each_entry(mod, &modules, list) {
420 if (strcmp(mod->name, name) == 0)
425 EXPORT_SYMBOL_GPL(find_module);
429 static inline void __percpu *mod_percpu(struct module *mod)
434 static int percpu_modalloc(struct module *mod,
435 unsigned long size, unsigned long align)
437 if (align > PAGE_SIZE) {
438 printk(KERN_WARNING "%s: per-cpu alignment %li > %li\n",
439 mod->name, align, PAGE_SIZE);
443 mod->percpu = __alloc_reserved_percpu(size, align);
446 "%s: Could not allocate %lu bytes percpu data\n",
450 mod->percpu_size = size;
454 static void percpu_modfree(struct module *mod)
456 free_percpu(mod->percpu);
459 static unsigned int find_pcpusec(struct load_info *info)
461 return find_sec(info, ".data..percpu");
464 static void percpu_modcopy(struct module *mod,
465 const void *from, unsigned long size)
469 for_each_possible_cpu(cpu)
470 memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
474 * is_module_percpu_address - test whether address is from module static percpu
475 * @addr: address to test
477 * Test whether @addr belongs to module static percpu area.
480 * %true if @addr is from module static percpu area
482 bool is_module_percpu_address(unsigned long addr)
489 list_for_each_entry_rcu(mod, &modules, list) {
490 if (!mod->percpu_size)
492 for_each_possible_cpu(cpu) {
493 void *start = per_cpu_ptr(mod->percpu, cpu);
495 if ((void *)addr >= start &&
496 (void *)addr < start + mod->percpu_size) {
507 #else /* ... !CONFIG_SMP */
509 static inline void __percpu *mod_percpu(struct module *mod)
513 static inline int percpu_modalloc(struct module *mod,
514 unsigned long size, unsigned long align)
518 static inline void percpu_modfree(struct module *mod)
521 static unsigned int find_pcpusec(struct load_info *info)
525 static inline void percpu_modcopy(struct module *mod,
526 const void *from, unsigned long size)
528 /* pcpusec should be 0, and size of that section should be 0. */
531 bool is_module_percpu_address(unsigned long addr)
536 #endif /* CONFIG_SMP */
538 #define MODINFO_ATTR(field) \
539 static void setup_modinfo_##field(struct module *mod, const char *s) \
541 mod->field = kstrdup(s, GFP_KERNEL); \
543 static ssize_t show_modinfo_##field(struct module_attribute *mattr, \
544 struct module_kobject *mk, char *buffer) \
546 return sprintf(buffer, "%s\n", mk->mod->field); \
548 static int modinfo_##field##_exists(struct module *mod) \
550 return mod->field != NULL; \
552 static void free_modinfo_##field(struct module *mod) \
557 static struct module_attribute modinfo_##field = { \
558 .attr = { .name = __stringify(field), .mode = 0444 }, \
559 .show = show_modinfo_##field, \
560 .setup = setup_modinfo_##field, \
561 .test = modinfo_##field##_exists, \
562 .free = free_modinfo_##field, \
565 MODINFO_ATTR(version);
566 MODINFO_ATTR(srcversion);
568 static char last_unloaded_module[MODULE_NAME_LEN+1];
570 #ifdef CONFIG_MODULE_UNLOAD
572 EXPORT_TRACEPOINT_SYMBOL(module_get);
574 /* Init the unload section of the module. */
575 static int module_unload_init(struct module *mod)
577 mod->refptr = alloc_percpu(struct module_ref);
581 INIT_LIST_HEAD(&mod->source_list);
582 INIT_LIST_HEAD(&mod->target_list);
584 /* Hold reference count during initialization. */
585 __this_cpu_write(mod->refptr->incs, 1);
586 /* Backwards compatibility macros put refcount during init. */
587 mod->waiter = current;
592 /* Does a already use b? */
593 static int already_uses(struct module *a, struct module *b)
595 struct module_use *use;
597 list_for_each_entry(use, &b->source_list, source_list) {
598 if (use->source == a) {
599 pr_debug("%s uses %s!\n", a->name, b->name);
603 pr_debug("%s does not use %s!\n", a->name, b->name);
609 * - we add 'a' as a "source", 'b' as a "target" of module use
610 * - the module_use is added to the list of 'b' sources (so
611 * 'b' can walk the list to see who sourced them), and of 'a'
612 * targets (so 'a' can see what modules it targets).
614 static int add_module_usage(struct module *a, struct module *b)
616 struct module_use *use;
618 pr_debug("Allocating new usage for %s.\n", a->name);
619 use = kmalloc(sizeof(*use), GFP_ATOMIC);
621 printk(KERN_WARNING "%s: out of memory loading\n", a->name);
627 list_add(&use->source_list, &b->source_list);
628 list_add(&use->target_list, &a->target_list);
632 /* Module a uses b: caller needs module_mutex() */
633 int ref_module(struct module *a, struct module *b)
637 if (b == NULL || already_uses(a, b))
640 /* If module isn't available, we fail. */
641 err = strong_try_module_get(b);
645 err = add_module_usage(a, b);
652 EXPORT_SYMBOL_GPL(ref_module);
654 /* Clear the unload stuff of the module. */
655 static void module_unload_free(struct module *mod)
657 struct module_use *use, *tmp;
659 mutex_lock(&module_mutex);
660 list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
661 struct module *i = use->target;
662 pr_debug("%s unusing %s\n", mod->name, i->name);
664 list_del(&use->source_list);
665 list_del(&use->target_list);
668 mutex_unlock(&module_mutex);
670 free_percpu(mod->refptr);
673 #ifdef CONFIG_MODULE_FORCE_UNLOAD
674 static inline int try_force_unload(unsigned int flags)
676 int ret = (flags & O_TRUNC);
678 add_taint(TAINT_FORCED_RMMOD);
682 static inline int try_force_unload(unsigned int flags)
686 #endif /* CONFIG_MODULE_FORCE_UNLOAD */
695 /* Whole machine is stopped with interrupts off when this runs. */
696 static int __try_stop_module(void *_sref)
698 struct stopref *sref = _sref;
700 /* If it's not unused, quit unless we're forcing. */
701 if (module_refcount(sref->mod) != 0) {
702 if (!(*sref->forced = try_force_unload(sref->flags)))
706 /* Mark it as dying. */
707 sref->mod->state = MODULE_STATE_GOING;
711 static int try_stop_module(struct module *mod, int flags, int *forced)
713 if (flags & O_NONBLOCK) {
714 struct stopref sref = { mod, flags, forced };
716 return stop_machine(__try_stop_module, &sref, NULL);
718 /* We don't need to stop the machine for this. */
719 mod->state = MODULE_STATE_GOING;
725 unsigned long module_refcount(struct module *mod)
727 unsigned long incs = 0, decs = 0;
730 for_each_possible_cpu(cpu)
731 decs += per_cpu_ptr(mod->refptr, cpu)->decs;
733 * ensure the incs are added up after the decs.
734 * module_put ensures incs are visible before decs with smp_wmb.
736 * This 2-count scheme avoids the situation where the refcount
737 * for CPU0 is read, then CPU0 increments the module refcount,
738 * then CPU1 drops that refcount, then the refcount for CPU1 is
739 * read. We would record a decrement but not its corresponding
740 * increment so we would see a low count (disaster).
742 * Rare situation? But module_refcount can be preempted, and we
743 * might be tallying up 4096+ CPUs. So it is not impossible.
746 for_each_possible_cpu(cpu)
747 incs += per_cpu_ptr(mod->refptr, cpu)->incs;
750 EXPORT_SYMBOL(module_refcount);
752 /* This exists whether we can unload or not */
753 static void free_module(struct module *mod);
755 static void wait_for_zero_refcount(struct module *mod)
757 /* Since we might sleep for some time, release the mutex first */
758 mutex_unlock(&module_mutex);
760 pr_debug("Looking at refcount...\n");
761 set_current_state(TASK_UNINTERRUPTIBLE);
762 if (module_refcount(mod) == 0)
766 current->state = TASK_RUNNING;
767 mutex_lock(&module_mutex);
770 SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
774 char name[MODULE_NAME_LEN];
777 if (!capable(CAP_SYS_MODULE) || modules_disabled)
780 if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
782 name[MODULE_NAME_LEN-1] = '\0';
784 if (mutex_lock_interruptible(&module_mutex) != 0)
787 mod = find_module(name);
793 if (!list_empty(&mod->source_list)) {
794 /* Other modules depend on us: get rid of them first. */
799 /* Doing init or already dying? */
800 if (mod->state != MODULE_STATE_LIVE) {
801 /* FIXME: if (force), slam module count and wake up
803 pr_debug("%s already dying\n", mod->name);
808 /* If it has an init func, it must have an exit func to unload */
809 if (mod->init && !mod->exit) {
810 forced = try_force_unload(flags);
812 /* This module can't be removed */
818 /* Set this up before setting mod->state */
819 mod->waiter = current;
821 /* Stop the machine so refcounts can't move and disable module. */
822 ret = try_stop_module(mod, flags, &forced);
826 /* Never wait if forced. */
827 if (!forced && module_refcount(mod) != 0)
828 wait_for_zero_refcount(mod);
830 mutex_unlock(&module_mutex);
831 /* Final destruction now no one is using it. */
832 if (mod->exit != NULL)
834 blocking_notifier_call_chain(&module_notify_list,
835 MODULE_STATE_GOING, mod);
836 async_synchronize_full();
838 /* Store the name of the last unloaded module for diagnostic purposes */
839 strlcpy(last_unloaded_module, mod->name, sizeof(last_unloaded_module));
844 mutex_unlock(&module_mutex);
848 static inline void print_unload_info(struct seq_file *m, struct module *mod)
850 struct module_use *use;
851 int printed_something = 0;
853 seq_printf(m, " %lu ", module_refcount(mod));
855 /* Always include a trailing , so userspace can differentiate
856 between this and the old multi-field proc format. */
857 list_for_each_entry(use, &mod->source_list, source_list) {
858 printed_something = 1;
859 seq_printf(m, "%s,", use->source->name);
862 if (mod->init != NULL && mod->exit == NULL) {
863 printed_something = 1;
864 seq_printf(m, "[permanent],");
867 if (!printed_something)
871 void __symbol_put(const char *symbol)
873 struct module *owner;
876 if (!find_symbol(symbol, &owner, NULL, true, false))
881 EXPORT_SYMBOL(__symbol_put);
883 /* Note this assumes addr is a function, which it currently always is. */
884 void symbol_put_addr(void *addr)
886 struct module *modaddr;
887 unsigned long a = (unsigned long)dereference_function_descriptor(addr);
889 if (core_kernel_text(a))
892 /* module_text_address is safe here: we're supposed to have reference
893 * to module from symbol_get, so it can't go away. */
894 modaddr = __module_text_address(a);
898 EXPORT_SYMBOL_GPL(symbol_put_addr);
900 static ssize_t show_refcnt(struct module_attribute *mattr,
901 struct module_kobject *mk, char *buffer)
903 return sprintf(buffer, "%lu\n", module_refcount(mk->mod));
906 static struct module_attribute modinfo_refcnt =
907 __ATTR(refcnt, 0444, show_refcnt, NULL);
909 void __module_get(struct module *module)
913 __this_cpu_inc(module->refptr->incs);
914 trace_module_get(module, _RET_IP_);
918 EXPORT_SYMBOL(__module_get);
920 bool try_module_get(struct module *module)
927 if (likely(module_is_live(module))) {
928 __this_cpu_inc(module->refptr->incs);
929 trace_module_get(module, _RET_IP_);
937 EXPORT_SYMBOL(try_module_get);
939 void module_put(struct module *module)
943 smp_wmb(); /* see comment in module_refcount */
944 __this_cpu_inc(module->refptr->decs);
946 trace_module_put(module, _RET_IP_);
947 /* Maybe they're waiting for us to drop reference? */
948 if (unlikely(!module_is_live(module)))
949 wake_up_process(module->waiter);
953 EXPORT_SYMBOL(module_put);
955 #else /* !CONFIG_MODULE_UNLOAD */
956 static inline void print_unload_info(struct seq_file *m, struct module *mod)
958 /* We don't know the usage count, or what modules are using. */
959 seq_printf(m, " - -");
962 static inline void module_unload_free(struct module *mod)
966 int ref_module(struct module *a, struct module *b)
968 return strong_try_module_get(b);
970 EXPORT_SYMBOL_GPL(ref_module);
972 static inline int module_unload_init(struct module *mod)
976 #endif /* CONFIG_MODULE_UNLOAD */
978 static size_t module_flags_taint(struct module *mod, char *buf)
982 if (mod->taints & (1 << TAINT_PROPRIETARY_MODULE))
984 if (mod->taints & (1 << TAINT_OOT_MODULE))
986 if (mod->taints & (1 << TAINT_FORCED_MODULE))
988 if (mod->taints & (1 << TAINT_CRAP))
991 * TAINT_FORCED_RMMOD: could be added.
992 * TAINT_UNSAFE_SMP, TAINT_MACHINE_CHECK, TAINT_BAD_PAGE don't
998 static ssize_t show_initstate(struct module_attribute *mattr,
999 struct module_kobject *mk, char *buffer)
1001 const char *state = "unknown";
1003 switch (mk->mod->state) {
1004 case MODULE_STATE_LIVE:
1007 case MODULE_STATE_COMING:
1010 case MODULE_STATE_GOING:
1014 return sprintf(buffer, "%s\n", state);
1017 static struct module_attribute modinfo_initstate =
1018 __ATTR(initstate, 0444, show_initstate, NULL);
1020 static ssize_t store_uevent(struct module_attribute *mattr,
1021 struct module_kobject *mk,
1022 const char *buffer, size_t count)
1024 enum kobject_action action;
1026 if (kobject_action_type(buffer, count, &action) == 0)
1027 kobject_uevent(&mk->kobj, action);
1031 struct module_attribute module_uevent =
1032 __ATTR(uevent, 0200, NULL, store_uevent);
1034 static ssize_t show_coresize(struct module_attribute *mattr,
1035 struct module_kobject *mk, char *buffer)
1037 return sprintf(buffer, "%u\n", mk->mod->core_size);
1040 static struct module_attribute modinfo_coresize =
1041 __ATTR(coresize, 0444, show_coresize, NULL);
1043 static ssize_t show_initsize(struct module_attribute *mattr,
1044 struct module_kobject *mk, char *buffer)
1046 return sprintf(buffer, "%u\n", mk->mod->init_size);
1049 static struct module_attribute modinfo_initsize =
1050 __ATTR(initsize, 0444, show_initsize, NULL);
1052 static ssize_t show_taint(struct module_attribute *mattr,
1053 struct module_kobject *mk, char *buffer)
1057 l = module_flags_taint(mk->mod, buffer);
1062 static struct module_attribute modinfo_taint =
1063 __ATTR(taint, 0444, show_taint, NULL);
1065 static struct module_attribute *modinfo_attrs[] = {
1068 &modinfo_srcversion,
1073 #ifdef CONFIG_MODULE_UNLOAD
1079 static const char vermagic[] = VERMAGIC_STRING;
1081 static int try_to_force_load(struct module *mod, const char *reason)
1083 #ifdef CONFIG_MODULE_FORCE_LOAD
1084 if (!test_taint(TAINT_FORCED_MODULE))
1085 printk(KERN_WARNING "%s: %s: kernel tainted.\n",
1087 add_taint_module(mod, TAINT_FORCED_MODULE);
1094 #ifdef CONFIG_MODVERSIONS
1095 /* If the arch applies (non-zero) relocations to kernel kcrctab, unapply it. */
1096 static unsigned long maybe_relocated(unsigned long crc,
1097 const struct module *crc_owner)
1099 #ifdef ARCH_RELOCATES_KCRCTAB
1100 if (crc_owner == NULL)
1101 return crc - (unsigned long)reloc_start;
1106 static int check_version(Elf_Shdr *sechdrs,
1107 unsigned int versindex,
1108 const char *symname,
1110 const unsigned long *crc,
1111 const struct module *crc_owner)
1113 unsigned int i, num_versions;
1114 struct modversion_info *versions;
1116 /* Exporting module didn't supply crcs? OK, we're already tainted. */
1120 /* No versions at all? modprobe --force does this. */
1122 return try_to_force_load(mod, symname) == 0;
1124 versions = (void *) sechdrs[versindex].sh_addr;
1125 num_versions = sechdrs[versindex].sh_size
1126 / sizeof(struct modversion_info);
1128 for (i = 0; i < num_versions; i++) {
1129 if (strcmp(versions[i].name, symname) != 0)
1132 if (versions[i].crc == maybe_relocated(*crc, crc_owner))
1134 pr_debug("Found checksum %lX vs module %lX\n",
1135 maybe_relocated(*crc, crc_owner), versions[i].crc);
1139 printk(KERN_WARNING "%s: no symbol version for %s\n",
1140 mod->name, symname);
1144 printk("%s: disagrees about version of symbol %s\n",
1145 mod->name, symname);
1149 static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1150 unsigned int versindex,
1153 const unsigned long *crc;
1155 /* Since this should be found in kernel (which can't be removed),
1156 * no locking is necessary. */
1157 if (!find_symbol(MODULE_SYMBOL_PREFIX "module_layout", NULL,
1160 return check_version(sechdrs, versindex, "module_layout", mod, crc,
1164 /* First part is kernel version, which we ignore if module has crcs. */
1165 static inline int same_magic(const char *amagic, const char *bmagic,
1169 amagic += strcspn(amagic, " ");
1170 bmagic += strcspn(bmagic, " ");
1172 return strcmp(amagic, bmagic) == 0;
1175 static inline int check_version(Elf_Shdr *sechdrs,
1176 unsigned int versindex,
1177 const char *symname,
1179 const unsigned long *crc,
1180 const struct module *crc_owner)
1185 static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1186 unsigned int versindex,
1192 static inline int same_magic(const char *amagic, const char *bmagic,
1195 return strcmp(amagic, bmagic) == 0;
1197 #endif /* CONFIG_MODVERSIONS */
1199 /* Resolve a symbol for this module. I.e. if we find one, record usage. */
1200 static const struct kernel_symbol *resolve_symbol(struct module *mod,
1201 const struct load_info *info,
1205 struct module *owner;
1206 const struct kernel_symbol *sym;
1207 const unsigned long *crc;
1210 mutex_lock(&module_mutex);
1211 sym = find_symbol(name, &owner, &crc,
1212 !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)), true);
1216 if (!check_version(info->sechdrs, info->index.vers, name, mod, crc,
1218 sym = ERR_PTR(-EINVAL);
1222 err = ref_module(mod, owner);
1229 /* We must make copy under the lock if we failed to get ref. */
1230 strncpy(ownername, module_name(owner), MODULE_NAME_LEN);
1232 mutex_unlock(&module_mutex);
1236 static const struct kernel_symbol *
1237 resolve_symbol_wait(struct module *mod,
1238 const struct load_info *info,
1241 const struct kernel_symbol *ksym;
1242 char owner[MODULE_NAME_LEN];
1244 if (wait_event_interruptible_timeout(module_wq,
1245 !IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1246 || PTR_ERR(ksym) != -EBUSY,
1248 printk(KERN_WARNING "%s: gave up waiting for init of module %s.\n",
1255 * /sys/module/foo/sections stuff
1256 * J. Corbet <corbet@lwn.net>
1260 #ifdef CONFIG_KALLSYMS
1261 static inline bool sect_empty(const Elf_Shdr *sect)
1263 return !(sect->sh_flags & SHF_ALLOC) || sect->sh_size == 0;
1266 struct module_sect_attr
1268 struct module_attribute mattr;
1270 unsigned long address;
1273 struct module_sect_attrs
1275 struct attribute_group grp;
1276 unsigned int nsections;
1277 struct module_sect_attr attrs[0];
1280 static ssize_t module_sect_show(struct module_attribute *mattr,
1281 struct module_kobject *mk, char *buf)
1283 struct module_sect_attr *sattr =
1284 container_of(mattr, struct module_sect_attr, mattr);
1285 return sprintf(buf, "0x%pK\n", (void *)sattr->address);
1288 static void free_sect_attrs(struct module_sect_attrs *sect_attrs)
1290 unsigned int section;
1292 for (section = 0; section < sect_attrs->nsections; section++)
1293 kfree(sect_attrs->attrs[section].name);
1297 static void add_sect_attrs(struct module *mod, const struct load_info *info)
1299 unsigned int nloaded = 0, i, size[2];
1300 struct module_sect_attrs *sect_attrs;
1301 struct module_sect_attr *sattr;
1302 struct attribute **gattr;
1304 /* Count loaded sections and allocate structures */
1305 for (i = 0; i < info->hdr->e_shnum; i++)
1306 if (!sect_empty(&info->sechdrs[i]))
1308 size[0] = ALIGN(sizeof(*sect_attrs)
1309 + nloaded * sizeof(sect_attrs->attrs[0]),
1310 sizeof(sect_attrs->grp.attrs[0]));
1311 size[1] = (nloaded + 1) * sizeof(sect_attrs->grp.attrs[0]);
1312 sect_attrs = kzalloc(size[0] + size[1], GFP_KERNEL);
1313 if (sect_attrs == NULL)
1316 /* Setup section attributes. */
1317 sect_attrs->grp.name = "sections";
1318 sect_attrs->grp.attrs = (void *)sect_attrs + size[0];
1320 sect_attrs->nsections = 0;
1321 sattr = §_attrs->attrs[0];
1322 gattr = §_attrs->grp.attrs[0];
1323 for (i = 0; i < info->hdr->e_shnum; i++) {
1324 Elf_Shdr *sec = &info->sechdrs[i];
1325 if (sect_empty(sec))
1327 sattr->address = sec->sh_addr;
1328 sattr->name = kstrdup(info->secstrings + sec->sh_name,
1330 if (sattr->name == NULL)
1332 sect_attrs->nsections++;
1333 sysfs_attr_init(&sattr->mattr.attr);
1334 sattr->mattr.show = module_sect_show;
1335 sattr->mattr.store = NULL;
1336 sattr->mattr.attr.name = sattr->name;
1337 sattr->mattr.attr.mode = S_IRUGO;
1338 *(gattr++) = &(sattr++)->mattr.attr;
1342 if (sysfs_create_group(&mod->mkobj.kobj, §_attrs->grp))
1345 mod->sect_attrs = sect_attrs;
1348 free_sect_attrs(sect_attrs);
1351 static void remove_sect_attrs(struct module *mod)
1353 if (mod->sect_attrs) {
1354 sysfs_remove_group(&mod->mkobj.kobj,
1355 &mod->sect_attrs->grp);
1356 /* We are positive that no one is using any sect attrs
1357 * at this point. Deallocate immediately. */
1358 free_sect_attrs(mod->sect_attrs);
1359 mod->sect_attrs = NULL;
1364 * /sys/module/foo/notes/.section.name gives contents of SHT_NOTE sections.
1367 struct module_notes_attrs {
1368 struct kobject *dir;
1370 struct bin_attribute attrs[0];
1373 static ssize_t module_notes_read(struct file *filp, struct kobject *kobj,
1374 struct bin_attribute *bin_attr,
1375 char *buf, loff_t pos, size_t count)
1378 * The caller checked the pos and count against our size.
1380 memcpy(buf, bin_attr->private + pos, count);
1384 static void free_notes_attrs(struct module_notes_attrs *notes_attrs,
1387 if (notes_attrs->dir) {
1389 sysfs_remove_bin_file(notes_attrs->dir,
1390 ¬es_attrs->attrs[i]);
1391 kobject_put(notes_attrs->dir);
1396 static void add_notes_attrs(struct module *mod, const struct load_info *info)
1398 unsigned int notes, loaded, i;
1399 struct module_notes_attrs *notes_attrs;
1400 struct bin_attribute *nattr;
1402 /* failed to create section attributes, so can't create notes */
1403 if (!mod->sect_attrs)
1406 /* Count notes sections and allocate structures. */
1408 for (i = 0; i < info->hdr->e_shnum; i++)
1409 if (!sect_empty(&info->sechdrs[i]) &&
1410 (info->sechdrs[i].sh_type == SHT_NOTE))
1416 notes_attrs = kzalloc(sizeof(*notes_attrs)
1417 + notes * sizeof(notes_attrs->attrs[0]),
1419 if (notes_attrs == NULL)
1422 notes_attrs->notes = notes;
1423 nattr = ¬es_attrs->attrs[0];
1424 for (loaded = i = 0; i < info->hdr->e_shnum; ++i) {
1425 if (sect_empty(&info->sechdrs[i]))
1427 if (info->sechdrs[i].sh_type == SHT_NOTE) {
1428 sysfs_bin_attr_init(nattr);
1429 nattr->attr.name = mod->sect_attrs->attrs[loaded].name;
1430 nattr->attr.mode = S_IRUGO;
1431 nattr->size = info->sechdrs[i].sh_size;
1432 nattr->private = (void *) info->sechdrs[i].sh_addr;
1433 nattr->read = module_notes_read;
1439 notes_attrs->dir = kobject_create_and_add("notes", &mod->mkobj.kobj);
1440 if (!notes_attrs->dir)
1443 for (i = 0; i < notes; ++i)
1444 if (sysfs_create_bin_file(notes_attrs->dir,
1445 ¬es_attrs->attrs[i]))
1448 mod->notes_attrs = notes_attrs;
1452 free_notes_attrs(notes_attrs, i);
1455 static void remove_notes_attrs(struct module *mod)
1457 if (mod->notes_attrs)
1458 free_notes_attrs(mod->notes_attrs, mod->notes_attrs->notes);
1463 static inline void add_sect_attrs(struct module *mod,
1464 const struct load_info *info)
1468 static inline void remove_sect_attrs(struct module *mod)
1472 static inline void add_notes_attrs(struct module *mod,
1473 const struct load_info *info)
1477 static inline void remove_notes_attrs(struct module *mod)
1480 #endif /* CONFIG_KALLSYMS */
1482 static void add_usage_links(struct module *mod)
1484 #ifdef CONFIG_MODULE_UNLOAD
1485 struct module_use *use;
1488 mutex_lock(&module_mutex);
1489 list_for_each_entry(use, &mod->target_list, target_list) {
1490 nowarn = sysfs_create_link(use->target->holders_dir,
1491 &mod->mkobj.kobj, mod->name);
1493 mutex_unlock(&module_mutex);
1497 static void del_usage_links(struct module *mod)
1499 #ifdef CONFIG_MODULE_UNLOAD
1500 struct module_use *use;
1502 mutex_lock(&module_mutex);
1503 list_for_each_entry(use, &mod->target_list, target_list)
1504 sysfs_remove_link(use->target->holders_dir, mod->name);
1505 mutex_unlock(&module_mutex);
1509 static int module_add_modinfo_attrs(struct module *mod)
1511 struct module_attribute *attr;
1512 struct module_attribute *temp_attr;
1516 mod->modinfo_attrs = kzalloc((sizeof(struct module_attribute) *
1517 (ARRAY_SIZE(modinfo_attrs) + 1)),
1519 if (!mod->modinfo_attrs)
1522 temp_attr = mod->modinfo_attrs;
1523 for (i = 0; (attr = modinfo_attrs[i]) && !error; i++) {
1525 (attr->test && attr->test(mod))) {
1526 memcpy(temp_attr, attr, sizeof(*temp_attr));
1527 sysfs_attr_init(&temp_attr->attr);
1528 error = sysfs_create_file(&mod->mkobj.kobj,&temp_attr->attr);
1535 static void module_remove_modinfo_attrs(struct module *mod)
1537 struct module_attribute *attr;
1540 for (i = 0; (attr = &mod->modinfo_attrs[i]); i++) {
1541 /* pick a field to test for end of list */
1542 if (!attr->attr.name)
1544 sysfs_remove_file(&mod->mkobj.kobj,&attr->attr);
1548 kfree(mod->modinfo_attrs);
1551 static int mod_sysfs_init(struct module *mod)
1554 struct kobject *kobj;
1556 if (!module_sysfs_initialized) {
1557 printk(KERN_ERR "%s: module sysfs not initialized\n",
1563 kobj = kset_find_obj(module_kset, mod->name);
1565 printk(KERN_ERR "%s: module is already loaded\n", mod->name);
1571 mod->mkobj.mod = mod;
1573 memset(&mod->mkobj.kobj, 0, sizeof(mod->mkobj.kobj));
1574 mod->mkobj.kobj.kset = module_kset;
1575 err = kobject_init_and_add(&mod->mkobj.kobj, &module_ktype, NULL,
1578 kobject_put(&mod->mkobj.kobj);
1580 /* delay uevent until full sysfs population */
1585 static int mod_sysfs_setup(struct module *mod,
1586 const struct load_info *info,
1587 struct kernel_param *kparam,
1588 unsigned int num_params)
1592 err = mod_sysfs_init(mod);
1596 mod->holders_dir = kobject_create_and_add("holders", &mod->mkobj.kobj);
1597 if (!mod->holders_dir) {
1602 err = module_param_sysfs_setup(mod, kparam, num_params);
1604 goto out_unreg_holders;
1606 err = module_add_modinfo_attrs(mod);
1608 goto out_unreg_param;
1610 add_usage_links(mod);
1611 add_sect_attrs(mod, info);
1612 add_notes_attrs(mod, info);
1614 kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
1618 module_param_sysfs_remove(mod);
1620 kobject_put(mod->holders_dir);
1622 kobject_put(&mod->mkobj.kobj);
1627 static void mod_sysfs_fini(struct module *mod)
1629 remove_notes_attrs(mod);
1630 remove_sect_attrs(mod);
1631 kobject_put(&mod->mkobj.kobj);
1634 #else /* !CONFIG_SYSFS */
1636 static int mod_sysfs_setup(struct module *mod,
1637 const struct load_info *info,
1638 struct kernel_param *kparam,
1639 unsigned int num_params)
1644 static void mod_sysfs_fini(struct module *mod)
1648 static void module_remove_modinfo_attrs(struct module *mod)
1652 static void del_usage_links(struct module *mod)
1656 #endif /* CONFIG_SYSFS */
1658 static void mod_sysfs_teardown(struct module *mod)
1660 del_usage_links(mod);
1661 module_remove_modinfo_attrs(mod);
1662 module_param_sysfs_remove(mod);
1663 kobject_put(mod->mkobj.drivers_dir);
1664 kobject_put(mod->holders_dir);
1665 mod_sysfs_fini(mod);
1669 * unlink the module with the whole machine is stopped with interrupts off
1670 * - this defends against kallsyms not taking locks
1672 static int __unlink_module(void *_mod)
1674 struct module *mod = _mod;
1675 list_del(&mod->list);
1676 module_bug_cleanup(mod);
1680 #ifdef CONFIG_DEBUG_SET_MODULE_RONX
1682 * LKM RO/NX protection: protect module's text/ro-data
1683 * from modification and any data from execution.
1685 void set_page_attributes(void *start, void *end, int (*set)(unsigned long start, int num_pages))
1687 unsigned long begin_pfn = PFN_DOWN((unsigned long)start);
1688 unsigned long end_pfn = PFN_DOWN((unsigned long)end);
1690 if (end_pfn > begin_pfn)
1691 set(begin_pfn << PAGE_SHIFT, end_pfn - begin_pfn);
1694 static void set_section_ro_nx(void *base,
1695 unsigned long text_size,
1696 unsigned long ro_size,
1697 unsigned long total_size)
1699 /* begin and end PFNs of the current subsection */
1700 unsigned long begin_pfn;
1701 unsigned long end_pfn;
1704 * Set RO for module text and RO-data:
1705 * - Always protect first page.
1706 * - Do not protect last partial page.
1709 set_page_attributes(base, base + ro_size, set_memory_ro);
1712 * Set NX permissions for module data:
1713 * - Do not protect first partial page.
1714 * - Always protect last page.
1716 if (total_size > text_size) {
1717 begin_pfn = PFN_UP((unsigned long)base + text_size);
1718 end_pfn = PFN_UP((unsigned long)base + total_size);
1719 if (end_pfn > begin_pfn)
1720 set_memory_nx(begin_pfn << PAGE_SHIFT, end_pfn - begin_pfn);
1724 static void unset_module_core_ro_nx(struct module *mod)
1726 set_page_attributes(mod->module_core + mod->core_text_size,
1727 mod->module_core + mod->core_size,
1729 set_page_attributes(mod->module_core,
1730 mod->module_core + mod->core_ro_size,
1734 static void unset_module_init_ro_nx(struct module *mod)
1736 set_page_attributes(mod->module_init + mod->init_text_size,
1737 mod->module_init + mod->init_size,
1739 set_page_attributes(mod->module_init,
1740 mod->module_init + mod->init_ro_size,
1744 /* Iterate through all modules and set each module's text as RW */
1745 void set_all_modules_text_rw(void)
1749 mutex_lock(&module_mutex);
1750 list_for_each_entry_rcu(mod, &modules, list) {
1751 if ((mod->module_core) && (mod->core_text_size)) {
1752 set_page_attributes(mod->module_core,
1753 mod->module_core + mod->core_text_size,
1756 if ((mod->module_init) && (mod->init_text_size)) {
1757 set_page_attributes(mod->module_init,
1758 mod->module_init + mod->init_text_size,
1762 mutex_unlock(&module_mutex);
1765 /* Iterate through all modules and set each module's text as RO */
1766 void set_all_modules_text_ro(void)
1770 mutex_lock(&module_mutex);
1771 list_for_each_entry_rcu(mod, &modules, list) {
1772 if ((mod->module_core) && (mod->core_text_size)) {
1773 set_page_attributes(mod->module_core,
1774 mod->module_core + mod->core_text_size,
1777 if ((mod->module_init) && (mod->init_text_size)) {
1778 set_page_attributes(mod->module_init,
1779 mod->module_init + mod->init_text_size,
1783 mutex_unlock(&module_mutex);
1786 static inline void set_section_ro_nx(void *base, unsigned long text_size, unsigned long ro_size, unsigned long total_size) { }
1787 static void unset_module_core_ro_nx(struct module *mod) { }
1788 static void unset_module_init_ro_nx(struct module *mod) { }
1791 void __weak module_free(struct module *mod, void *module_region)
1793 vfree(module_region);
1796 void __weak module_arch_cleanup(struct module *mod)
1800 /* Free a module, remove from lists, etc. */
1801 static void free_module(struct module *mod)
1803 trace_module_free(mod);
1805 /* Delete from various lists */
1806 mutex_lock(&module_mutex);
1807 stop_machine(__unlink_module, mod, NULL);
1808 mutex_unlock(&module_mutex);
1809 mod_sysfs_teardown(mod);
1811 /* Remove dynamic debug info */
1812 ddebug_remove_module(mod->name);
1814 /* Arch-specific cleanup. */
1815 module_arch_cleanup(mod);
1817 /* Module unload stuff */
1818 module_unload_free(mod);
1820 /* Free any allocated parameters. */
1821 destroy_params(mod->kp, mod->num_kp);
1823 /* This may be NULL, but that's OK */
1824 unset_module_init_ro_nx(mod);
1825 module_free(mod, mod->module_init);
1827 percpu_modfree(mod);
1829 /* Free lock-classes: */
1830 lockdep_free_key_range(mod->module_core, mod->core_size);
1832 /* Finally, free the core (containing the module structure) */
1833 unset_module_core_ro_nx(mod);
1834 module_free(mod, mod->module_core);
1837 update_protections(current->mm);
1841 void *__symbol_get(const char *symbol)
1843 struct module *owner;
1844 const struct kernel_symbol *sym;
1847 sym = find_symbol(symbol, &owner, NULL, true, true);
1848 if (sym && strong_try_module_get(owner))
1852 return sym ? (void *)sym->value : NULL;
1854 EXPORT_SYMBOL_GPL(__symbol_get);
1857 * Ensure that an exported symbol [global namespace] does not already exist
1858 * in the kernel or in some other module's exported symbol table.
1860 * You must hold the module_mutex.
1862 static int verify_export_symbols(struct module *mod)
1865 struct module *owner;
1866 const struct kernel_symbol *s;
1868 const struct kernel_symbol *sym;
1871 { mod->syms, mod->num_syms },
1872 { mod->gpl_syms, mod->num_gpl_syms },
1873 { mod->gpl_future_syms, mod->num_gpl_future_syms },
1874 #ifdef CONFIG_UNUSED_SYMBOLS
1875 { mod->unused_syms, mod->num_unused_syms },
1876 { mod->unused_gpl_syms, mod->num_unused_gpl_syms },
1880 for (i = 0; i < ARRAY_SIZE(arr); i++) {
1881 for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
1882 if (find_symbol(s->name, &owner, NULL, true, false)) {
1884 "%s: exports duplicate symbol %s"
1886 mod->name, s->name, module_name(owner));
1894 /* Change all symbols so that st_value encodes the pointer directly. */
1895 static int simplify_symbols(struct module *mod, const struct load_info *info)
1897 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
1898 Elf_Sym *sym = (void *)symsec->sh_addr;
1899 unsigned long secbase;
1902 const struct kernel_symbol *ksym;
1904 for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
1905 const char *name = info->strtab + sym[i].st_name;
1907 switch (sym[i].st_shndx) {
1909 /* We compiled with -fno-common. These are not
1910 supposed to happen. */
1911 pr_debug("Common symbol: %s\n", name);
1912 printk("%s: please compile with -fno-common\n",
1918 /* Don't need to do anything */
1919 pr_debug("Absolute symbol: 0x%08lx\n",
1920 (long)sym[i].st_value);
1924 ksym = resolve_symbol_wait(mod, info, name);
1925 /* Ok if resolved. */
1926 if (ksym && !IS_ERR(ksym)) {
1927 sym[i].st_value = ksym->value;
1932 if (!ksym && ELF_ST_BIND(sym[i].st_info) == STB_WEAK)
1935 printk(KERN_WARNING "%s: Unknown symbol %s (err %li)\n",
1936 mod->name, name, PTR_ERR(ksym));
1937 ret = PTR_ERR(ksym) ?: -ENOENT;
1941 /* Divert to percpu allocation if a percpu var. */
1942 if (sym[i].st_shndx == info->index.pcpu)
1943 secbase = (unsigned long)mod_percpu(mod);
1945 secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
1946 sym[i].st_value += secbase;
1954 int __weak apply_relocate(Elf_Shdr *sechdrs,
1956 unsigned int symindex,
1957 unsigned int relsec,
1960 pr_err("module %s: REL relocation unsupported\n", me->name);
1964 int __weak apply_relocate_add(Elf_Shdr *sechdrs,
1966 unsigned int symindex,
1967 unsigned int relsec,
1970 pr_err("module %s: RELA relocation unsupported\n", me->name);
1974 static int apply_relocations(struct module *mod, const struct load_info *info)
1979 /* Now do relocations. */
1980 for (i = 1; i < info->hdr->e_shnum; i++) {
1981 unsigned int infosec = info->sechdrs[i].sh_info;
1983 /* Not a valid relocation section? */
1984 if (infosec >= info->hdr->e_shnum)
1987 /* Don't bother with non-allocated sections */
1988 if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
1991 if (info->sechdrs[i].sh_type == SHT_REL)
1992 err = apply_relocate(info->sechdrs, info->strtab,
1993 info->index.sym, i, mod);
1994 else if (info->sechdrs[i].sh_type == SHT_RELA)
1995 err = apply_relocate_add(info->sechdrs, info->strtab,
1996 info->index.sym, i, mod);
2003 /* Additional bytes needed by arch in front of individual sections */
2004 unsigned int __weak arch_mod_section_prepend(struct module *mod,
2005 unsigned int section)
2007 /* default implementation just returns zero */
2011 /* Update size with this section: return offset. */
2012 static long get_offset(struct module *mod, unsigned int *size,
2013 Elf_Shdr *sechdr, unsigned int section)
2017 *size += arch_mod_section_prepend(mod, section);
2018 ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
2019 *size = ret + sechdr->sh_size;
2023 /* Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
2024 might -- code, read-only data, read-write data, small data. Tally
2025 sizes, and place the offsets into sh_entsize fields: high bit means it
2027 static void layout_sections(struct module *mod, struct load_info *info)
2029 static unsigned long const masks[][2] = {
2030 /* NOTE: all executable code must be the first section
2031 * in this array; otherwise modify the text_size
2032 * finder in the two loops below */
2033 { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
2034 { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
2035 { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
2036 { ARCH_SHF_SMALL | SHF_ALLOC, 0 }
2040 for (i = 0; i < info->hdr->e_shnum; i++)
2041 info->sechdrs[i].sh_entsize = ~0UL;
2043 pr_debug("Core section allocation order:\n");
2044 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2045 for (i = 0; i < info->hdr->e_shnum; ++i) {
2046 Elf_Shdr *s = &info->sechdrs[i];
2047 const char *sname = info->secstrings + s->sh_name;
2049 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2050 || (s->sh_flags & masks[m][1])
2051 || s->sh_entsize != ~0UL
2052 || strstarts(sname, ".init"))
2054 s->sh_entsize = get_offset(mod, &mod->core_size, s, i);
2055 pr_debug("\t%s\n", sname);
2058 case 0: /* executable */
2059 mod->core_size = debug_align(mod->core_size);
2060 mod->core_text_size = mod->core_size;
2062 case 1: /* RO: text and ro-data */
2063 mod->core_size = debug_align(mod->core_size);
2064 mod->core_ro_size = mod->core_size;
2066 case 3: /* whole core */
2067 mod->core_size = debug_align(mod->core_size);
2072 pr_debug("Init section allocation order:\n");
2073 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2074 for (i = 0; i < info->hdr->e_shnum; ++i) {
2075 Elf_Shdr *s = &info->sechdrs[i];
2076 const char *sname = info->secstrings + s->sh_name;
2078 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2079 || (s->sh_flags & masks[m][1])
2080 || s->sh_entsize != ~0UL
2081 || !strstarts(sname, ".init"))
2083 s->sh_entsize = (get_offset(mod, &mod->init_size, s, i)
2084 | INIT_OFFSET_MASK);
2085 pr_debug("\t%s\n", sname);
2088 case 0: /* executable */
2089 mod->init_size = debug_align(mod->init_size);
2090 mod->init_text_size = mod->init_size;
2092 case 1: /* RO: text and ro-data */
2093 mod->init_size = debug_align(mod->init_size);
2094 mod->init_ro_size = mod->init_size;
2096 case 3: /* whole init */
2097 mod->init_size = debug_align(mod->init_size);
2103 static void set_license(struct module *mod, const char *license)
2106 license = "unspecified";
2108 if (!license_is_gpl_compatible(license)) {
2109 if (!test_taint(TAINT_PROPRIETARY_MODULE))
2110 printk(KERN_WARNING "%s: module license '%s' taints "
2111 "kernel.\n", mod->name, license);
2112 add_taint_module(mod, TAINT_PROPRIETARY_MODULE);
2116 /* Parse tag=value strings from .modinfo section */
2117 static char *next_string(char *string, unsigned long *secsize)
2119 /* Skip non-zero chars */
2122 if ((*secsize)-- <= 1)
2126 /* Skip any zero padding. */
2127 while (!string[0]) {
2129 if ((*secsize)-- <= 1)
2135 static char *get_modinfo(struct load_info *info, const char *tag)
2138 unsigned int taglen = strlen(tag);
2139 Elf_Shdr *infosec = &info->sechdrs[info->index.info];
2140 unsigned long size = infosec->sh_size;
2142 for (p = (char *)infosec->sh_addr; p; p = next_string(p, &size)) {
2143 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
2144 return p + taglen + 1;
2149 static void setup_modinfo(struct module *mod, struct load_info *info)
2151 struct module_attribute *attr;
2154 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2156 attr->setup(mod, get_modinfo(info, attr->attr.name));
2160 static void free_modinfo(struct module *mod)
2162 struct module_attribute *attr;
2165 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2171 #ifdef CONFIG_KALLSYMS
2173 /* lookup symbol in given range of kernel_symbols */
2174 static const struct kernel_symbol *lookup_symbol(const char *name,
2175 const struct kernel_symbol *start,
2176 const struct kernel_symbol *stop)
2178 return bsearch(name, start, stop - start,
2179 sizeof(struct kernel_symbol), cmp_name);
2182 static int is_exported(const char *name, unsigned long value,
2183 const struct module *mod)
2185 const struct kernel_symbol *ks;
2187 ks = lookup_symbol(name, __start___ksymtab, __stop___ksymtab);
2189 ks = lookup_symbol(name, mod->syms, mod->syms + mod->num_syms);
2190 return ks != NULL && ks->value == value;
2194 static char elf_type(const Elf_Sym *sym, const struct load_info *info)
2196 const Elf_Shdr *sechdrs = info->sechdrs;
2198 if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
2199 if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT)
2204 if (sym->st_shndx == SHN_UNDEF)
2206 if (sym->st_shndx == SHN_ABS)
2208 if (sym->st_shndx >= SHN_LORESERVE)
2210 if (sechdrs[sym->st_shndx].sh_flags & SHF_EXECINSTR)
2212 if (sechdrs[sym->st_shndx].sh_flags & SHF_ALLOC
2213 && sechdrs[sym->st_shndx].sh_type != SHT_NOBITS) {
2214 if (!(sechdrs[sym->st_shndx].sh_flags & SHF_WRITE))
2216 else if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2221 if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
2222 if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2227 if (strstarts(info->secstrings + sechdrs[sym->st_shndx].sh_name,
2234 static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
2237 const Elf_Shdr *sec;
2239 if (src->st_shndx == SHN_UNDEF
2240 || src->st_shndx >= shnum
2244 sec = sechdrs + src->st_shndx;
2245 if (!(sec->sh_flags & SHF_ALLOC)
2246 #ifndef CONFIG_KALLSYMS_ALL
2247 || !(sec->sh_flags & SHF_EXECINSTR)
2249 || (sec->sh_entsize & INIT_OFFSET_MASK))
2256 * We only allocate and copy the strings needed by the parts of symtab
2257 * we keep. This is simple, but has the effect of making multiple
2258 * copies of duplicates. We could be more sophisticated, see
2259 * linux-kernel thread starting with
2260 * <73defb5e4bca04a6431392cc341112b1@localhost>.
2262 static void layout_symtab(struct module *mod, struct load_info *info)
2264 Elf_Shdr *symsect = info->sechdrs + info->index.sym;
2265 Elf_Shdr *strsect = info->sechdrs + info->index.str;
2267 unsigned int i, nsrc, ndst, strtab_size;
2269 /* Put symbol section at end of init part of module. */
2270 symsect->sh_flags |= SHF_ALLOC;
2271 symsect->sh_entsize = get_offset(mod, &mod->init_size, symsect,
2272 info->index.sym) | INIT_OFFSET_MASK;
2273 pr_debug("\t%s\n", info->secstrings + symsect->sh_name);
2275 src = (void *)info->hdr + symsect->sh_offset;
2276 nsrc = symsect->sh_size / sizeof(*src);
2278 /* Compute total space required for the core symbols' strtab. */
2279 for (ndst = i = strtab_size = 1; i < nsrc; ++i, ++src)
2280 if (is_core_symbol(src, info->sechdrs, info->hdr->e_shnum)) {
2281 strtab_size += strlen(&info->strtab[src->st_name]) + 1;
2285 /* Append room for core symbols at end of core part. */
2286 info->symoffs = ALIGN(mod->core_size, symsect->sh_addralign ?: 1);
2287 info->stroffs = mod->core_size = info->symoffs + ndst * sizeof(Elf_Sym);
2288 mod->core_size += strtab_size;
2290 /* Put string table section at end of init part of module. */
2291 strsect->sh_flags |= SHF_ALLOC;
2292 strsect->sh_entsize = get_offset(mod, &mod->init_size, strsect,
2293 info->index.str) | INIT_OFFSET_MASK;
2294 pr_debug("\t%s\n", info->secstrings + strsect->sh_name);
2297 static void add_kallsyms(struct module *mod, const struct load_info *info)
2299 unsigned int i, ndst;
2303 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2305 mod->symtab = (void *)symsec->sh_addr;
2306 mod->num_symtab = symsec->sh_size / sizeof(Elf_Sym);
2307 /* Make sure we get permanent strtab: don't use info->strtab. */
2308 mod->strtab = (void *)info->sechdrs[info->index.str].sh_addr;
2310 /* Set types up while we still have access to sections. */
2311 for (i = 0; i < mod->num_symtab; i++)
2312 mod->symtab[i].st_info = elf_type(&mod->symtab[i], info);
2314 mod->core_symtab = dst = mod->module_core + info->symoffs;
2315 mod->core_strtab = s = mod->module_core + info->stroffs;
2319 for (ndst = i = 1; i < mod->num_symtab; ++i, ++src) {
2320 if (!is_core_symbol(src, info->sechdrs, info->hdr->e_shnum))
2324 dst[ndst++].st_name = s - mod->core_strtab;
2325 s += strlcpy(s, &mod->strtab[src->st_name], KSYM_NAME_LEN) + 1;
2327 mod->core_num_syms = ndst;
2330 static inline void layout_symtab(struct module *mod, struct load_info *info)
2334 static void add_kallsyms(struct module *mod, const struct load_info *info)
2337 #endif /* CONFIG_KALLSYMS */
2339 static void dynamic_debug_setup(struct _ddebug *debug, unsigned int num)
2343 #ifdef CONFIG_DYNAMIC_DEBUG
2344 if (ddebug_add_module(debug, num, debug->modname))
2345 printk(KERN_ERR "dynamic debug error adding module: %s\n",
2350 static void dynamic_debug_remove(struct _ddebug *debug)
2353 ddebug_remove_module(debug->modname);
2356 void * __weak module_alloc(unsigned long size)
2358 return size == 0 ? NULL : vmalloc_exec(size);
2361 static void *module_alloc_update_bounds(unsigned long size)
2363 void *ret = module_alloc(size);
2366 mutex_lock(&module_mutex);
2367 /* Update module bounds. */
2368 if ((unsigned long)ret < module_addr_min)
2369 module_addr_min = (unsigned long)ret;
2370 if ((unsigned long)ret + size > module_addr_max)
2371 module_addr_max = (unsigned long)ret + size;
2372 mutex_unlock(&module_mutex);
2377 #ifdef CONFIG_DEBUG_KMEMLEAK
2378 static void kmemleak_load_module(const struct module *mod,
2379 const struct load_info *info)
2383 /* only scan the sections containing data */
2384 kmemleak_scan_area(mod, sizeof(struct module), GFP_KERNEL);
2386 for (i = 1; i < info->hdr->e_shnum; i++) {
2387 const char *name = info->secstrings + info->sechdrs[i].sh_name;
2388 if (!(info->sechdrs[i].sh_flags & SHF_ALLOC))
2390 if (!strstarts(name, ".data") && !strstarts(name, ".bss"))
2393 kmemleak_scan_area((void *)info->sechdrs[i].sh_addr,
2394 info->sechdrs[i].sh_size, GFP_KERNEL);
2398 static inline void kmemleak_load_module(const struct module *mod,
2399 const struct load_info *info)
2404 /* Sanity checks against invalid binaries, wrong arch, weird elf version. */
2405 static int check_info(struct load_info *info)
2407 if (info->len < sizeof(*(info->hdr)))
2410 if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0
2411 || info->hdr->e_type != ET_REL
2412 || !elf_check_arch(info->hdr)
2413 || info->hdr->e_shentsize != sizeof(Elf_Shdr))
2416 if (info->hdr->e_shoff >= info->len
2417 || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
2418 info->len - info->hdr->e_shoff))
2424 /* Sets info->hdr and info->len. */
2425 int copy_module_from_user(const void __user *umod, unsigned long len,
2426 struct load_info *info)
2431 if (info->len < sizeof(*(info->hdr)))
2434 err = security_kernel_module_from_file(NULL);
2438 /* Suck in entire file: we'll want most of it. */
2439 info->hdr = vmalloc(info->len);
2443 err = copy_from_user(info->hdr, umod, info->len);
2447 err = check_info(info);
2458 /* Sets info->hdr and info->len. */
2459 int copy_module_from_fd(int fd, struct load_info *info)
2472 err = vfs_getattr(file->f_vfsmnt, file->f_dentry, &stat);
2476 err = security_kernel_module_from_file(file);
2481 info->hdr = vmalloc(size);
2488 while (pos < size) {
2489 bytes = kernel_read(file, pos, (char *)(info->hdr) + pos,
2502 err = check_info(info);
2511 static void free_copy(struct load_info *info)
2516 static int rewrite_section_headers(struct load_info *info)
2520 /* This should always be true, but let's be sure. */
2521 info->sechdrs[0].sh_addr = 0;
2523 for (i = 1; i < info->hdr->e_shnum; i++) {
2524 Elf_Shdr *shdr = &info->sechdrs[i];
2525 if (shdr->sh_type != SHT_NOBITS
2526 && info->len < shdr->sh_offset + shdr->sh_size) {
2527 printk(KERN_ERR "Module len %lu truncated\n",
2532 /* Mark all sections sh_addr with their address in the
2534 shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
2536 #ifndef CONFIG_MODULE_UNLOAD
2537 /* Don't load .exit sections */
2538 if (strstarts(info->secstrings+shdr->sh_name, ".exit"))
2539 shdr->sh_flags &= ~(unsigned long)SHF_ALLOC;
2543 /* Track but don't keep modinfo and version sections. */
2544 info->index.vers = find_sec(info, "__versions");
2545 info->index.info = find_sec(info, ".modinfo");
2546 info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
2547 info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
2552 * Set up our basic convenience variables (pointers to section headers,
2553 * search for module section index etc), and do some basic section
2556 * Return the temporary module pointer (we'll replace it with the final
2557 * one when we move the module sections around).
2559 static struct module *setup_load_info(struct load_info *info)
2565 /* Set up the convenience variables */
2566 info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
2567 info->secstrings = (void *)info->hdr
2568 + info->sechdrs[info->hdr->e_shstrndx].sh_offset;
2570 err = rewrite_section_headers(info);
2572 return ERR_PTR(err);
2574 /* Find internal symbols and strings. */
2575 for (i = 1; i < info->hdr->e_shnum; i++) {
2576 if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
2577 info->index.sym = i;
2578 info->index.str = info->sechdrs[i].sh_link;
2579 info->strtab = (char *)info->hdr
2580 + info->sechdrs[info->index.str].sh_offset;
2585 info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
2586 if (!info->index.mod) {
2587 printk(KERN_WARNING "No module found in object\n");
2588 return ERR_PTR(-ENOEXEC);
2590 /* This is temporary: point mod into copy of data. */
2591 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2593 if (info->index.sym == 0) {
2594 printk(KERN_WARNING "%s: module has no symbols (stripped?)\n",
2596 return ERR_PTR(-ENOEXEC);
2599 info->index.pcpu = find_pcpusec(info);
2601 /* Check module struct version now, before we try to use module. */
2602 if (!check_modstruct_version(info->sechdrs, info->index.vers, mod))
2603 return ERR_PTR(-ENOEXEC);
2608 static int check_modinfo(struct module *mod, struct load_info *info)
2610 const char *modmagic = get_modinfo(info, "vermagic");
2613 /* This is allowed: modprobe --force will invalidate it. */
2615 err = try_to_force_load(mod, "bad vermagic");
2618 } else if (!same_magic(modmagic, vermagic, info->index.vers)) {
2619 printk(KERN_ERR "%s: version magic '%s' should be '%s'\n",
2620 mod->name, modmagic, vermagic);
2624 if (!get_modinfo(info, "intree"))
2625 add_taint_module(mod, TAINT_OOT_MODULE);
2627 if (get_modinfo(info, "staging")) {
2628 add_taint_module(mod, TAINT_CRAP);
2629 printk(KERN_WARNING "%s: module is from the staging directory,"
2630 " the quality is unknown, you have been warned.\n",
2634 /* Set up license info based on the info section */
2635 set_license(mod, get_modinfo(info, "license"));
2640 static void find_module_sections(struct module *mod, struct load_info *info)
2642 mod->kp = section_objs(info, "__param",
2643 sizeof(*mod->kp), &mod->num_kp);
2644 mod->syms = section_objs(info, "__ksymtab",
2645 sizeof(*mod->syms), &mod->num_syms);
2646 mod->crcs = section_addr(info, "__kcrctab");
2647 mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
2648 sizeof(*mod->gpl_syms),
2649 &mod->num_gpl_syms);
2650 mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
2651 mod->gpl_future_syms = section_objs(info,
2652 "__ksymtab_gpl_future",
2653 sizeof(*mod->gpl_future_syms),
2654 &mod->num_gpl_future_syms);
2655 mod->gpl_future_crcs = section_addr(info, "__kcrctab_gpl_future");
2657 #ifdef CONFIG_UNUSED_SYMBOLS
2658 mod->unused_syms = section_objs(info, "__ksymtab_unused",
2659 sizeof(*mod->unused_syms),
2660 &mod->num_unused_syms);
2661 mod->unused_crcs = section_addr(info, "__kcrctab_unused");
2662 mod->unused_gpl_syms = section_objs(info, "__ksymtab_unused_gpl",
2663 sizeof(*mod->unused_gpl_syms),
2664 &mod->num_unused_gpl_syms);
2665 mod->unused_gpl_crcs = section_addr(info, "__kcrctab_unused_gpl");
2667 #ifdef CONFIG_CONSTRUCTORS
2668 mod->ctors = section_objs(info, ".ctors",
2669 sizeof(*mod->ctors), &mod->num_ctors);
2672 #ifdef CONFIG_TRACEPOINTS
2673 mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
2674 sizeof(*mod->tracepoints_ptrs),
2675 &mod->num_tracepoints);
2677 #ifdef HAVE_JUMP_LABEL
2678 mod->jump_entries = section_objs(info, "__jump_table",
2679 sizeof(*mod->jump_entries),
2680 &mod->num_jump_entries);
2682 #ifdef CONFIG_EVENT_TRACING
2683 mod->trace_events = section_objs(info, "_ftrace_events",
2684 sizeof(*mod->trace_events),
2685 &mod->num_trace_events);
2687 * This section contains pointers to allocated objects in the trace
2688 * code and not scanning it leads to false positives.
2690 kmemleak_scan_area(mod->trace_events, sizeof(*mod->trace_events) *
2691 mod->num_trace_events, GFP_KERNEL);
2693 #ifdef CONFIG_TRACING
2694 mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
2695 sizeof(*mod->trace_bprintk_fmt_start),
2696 &mod->num_trace_bprintk_fmt);
2698 * This section contains pointers to allocated objects in the trace
2699 * code and not scanning it leads to false positives.
2701 kmemleak_scan_area(mod->trace_bprintk_fmt_start,
2702 sizeof(*mod->trace_bprintk_fmt_start) *
2703 mod->num_trace_bprintk_fmt, GFP_KERNEL);
2705 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
2706 /* sechdrs[0].sh_size is always zero */
2707 mod->ftrace_callsites = section_objs(info, "__mcount_loc",
2708 sizeof(*mod->ftrace_callsites),
2709 &mod->num_ftrace_callsites);
2712 mod->extable = section_objs(info, "__ex_table",
2713 sizeof(*mod->extable), &mod->num_exentries);
2715 if (section_addr(info, "__obsparm"))
2716 printk(KERN_WARNING "%s: Ignoring obsolete parameters\n",
2719 info->debug = section_objs(info, "__verbose",
2720 sizeof(*info->debug), &info->num_debug);
2723 static int move_module(struct module *mod, struct load_info *info)
2728 /* Do the allocs. */
2729 ptr = module_alloc_update_bounds(mod->core_size);
2731 * The pointer to this block is stored in the module structure
2732 * which is inside the block. Just mark it as not being a
2735 kmemleak_not_leak(ptr);
2739 memset(ptr, 0, mod->core_size);
2740 mod->module_core = ptr;
2742 ptr = module_alloc_update_bounds(mod->init_size);
2744 * The pointer to this block is stored in the module structure
2745 * which is inside the block. This block doesn't need to be
2746 * scanned as it contains data and code that will be freed
2747 * after the module is initialized.
2749 kmemleak_ignore(ptr);
2750 if (!ptr && mod->init_size) {
2751 module_free(mod, mod->module_core);
2754 memset(ptr, 0, mod->init_size);
2755 mod->module_init = ptr;
2757 /* Transfer each section which specifies SHF_ALLOC */
2758 pr_debug("final section addresses:\n");
2759 for (i = 0; i < info->hdr->e_shnum; i++) {
2761 Elf_Shdr *shdr = &info->sechdrs[i];
2763 if (!(shdr->sh_flags & SHF_ALLOC))
2766 if (shdr->sh_entsize & INIT_OFFSET_MASK)
2767 dest = mod->module_init
2768 + (shdr->sh_entsize & ~INIT_OFFSET_MASK);
2770 dest = mod->module_core + shdr->sh_entsize;
2772 if (shdr->sh_type != SHT_NOBITS)
2773 memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
2774 /* Update sh_addr to point to copy in image. */
2775 shdr->sh_addr = (unsigned long)dest;
2776 pr_debug("\t0x%lx %s\n",
2777 (long)shdr->sh_addr, info->secstrings + shdr->sh_name);
2783 static int check_module_license_and_versions(struct module *mod)
2786 * ndiswrapper is under GPL by itself, but loads proprietary modules.
2787 * Don't use add_taint_module(), as it would prevent ndiswrapper from
2788 * using GPL-only symbols it needs.
2790 if (strcmp(mod->name, "ndiswrapper") == 0)
2791 add_taint(TAINT_PROPRIETARY_MODULE);
2793 /* driverloader was caught wrongly pretending to be under GPL */
2794 if (strcmp(mod->name, "driverloader") == 0)
2795 add_taint_module(mod, TAINT_PROPRIETARY_MODULE);
2797 #ifdef CONFIG_MODVERSIONS
2798 if ((mod->num_syms && !mod->crcs)
2799 || (mod->num_gpl_syms && !mod->gpl_crcs)
2800 || (mod->num_gpl_future_syms && !mod->gpl_future_crcs)
2801 #ifdef CONFIG_UNUSED_SYMBOLS
2802 || (mod->num_unused_syms && !mod->unused_crcs)
2803 || (mod->num_unused_gpl_syms && !mod->unused_gpl_crcs)
2806 return try_to_force_load(mod,
2807 "no versions for exported symbols");
2813 static void flush_module_icache(const struct module *mod)
2815 mm_segment_t old_fs;
2817 /* flush the icache in correct context */
2822 * Flush the instruction cache, since we've played with text.
2823 * Do it before processing of module parameters, so the module
2824 * can provide parameter accessor functions of its own.
2826 if (mod->module_init)
2827 flush_icache_range((unsigned long)mod->module_init,
2828 (unsigned long)mod->module_init
2830 flush_icache_range((unsigned long)mod->module_core,
2831 (unsigned long)mod->module_core + mod->core_size);
2836 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
2844 static struct module *layout_and_allocate(struct load_info *info)
2846 /* Module within temporary copy. */
2851 mod = setup_load_info(info);
2855 err = check_modinfo(mod, info);
2857 return ERR_PTR(err);
2859 /* Allow arches to frob section contents and sizes. */
2860 err = module_frob_arch_sections(info->hdr, info->sechdrs,
2861 info->secstrings, mod);
2865 pcpusec = &info->sechdrs[info->index.pcpu];
2866 if (pcpusec->sh_size) {
2867 /* We have a special allocation for this section. */
2868 err = percpu_modalloc(mod,
2869 pcpusec->sh_size, pcpusec->sh_addralign);
2872 pcpusec->sh_flags &= ~(unsigned long)SHF_ALLOC;
2875 /* Determine total sizes, and put offsets in sh_entsize. For now
2876 this is done generically; there doesn't appear to be any
2877 special cases for the architectures. */
2878 layout_sections(mod, info);
2879 layout_symtab(mod, info);
2881 /* Allocate and move to the final place */
2882 err = move_module(mod, info);
2886 /* Module has been copied to its final place now: return it. */
2887 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2888 kmemleak_load_module(mod, info);
2892 percpu_modfree(mod);
2894 return ERR_PTR(err);
2897 /* mod is no longer valid after this! */
2898 static void module_deallocate(struct module *mod, struct load_info *info)
2900 percpu_modfree(mod);
2901 module_free(mod, mod->module_init);
2902 module_free(mod, mod->module_core);
2905 int __weak module_finalize(const Elf_Ehdr *hdr,
2906 const Elf_Shdr *sechdrs,
2912 static int post_relocation(struct module *mod, const struct load_info *info)
2914 /* Sort exception table now relocations are done. */
2915 sort_extable(mod->extable, mod->extable + mod->num_exentries);
2917 /* Copy relocated percpu area over. */
2918 percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
2919 info->sechdrs[info->index.pcpu].sh_size);
2921 /* Setup kallsyms-specific fields. */
2922 add_kallsyms(mod, info);
2924 /* Arch-specific module finalizing. */
2925 return module_finalize(info->hdr, info->sechdrs, mod);
2928 static int do_init_module(struct module *mod);
2930 /* Allocate and load the module: note that size of section 0 is always
2931 zero, and we rely on this for optional sections. */
2932 static int load_module(struct load_info *info, const char __user *uargs)
2937 /* Figure out module layout, and allocate all the memory. */
2938 mod = layout_and_allocate(info);
2944 /* Now module is in final location, initialize linked lists, etc. */
2945 err = module_unload_init(mod);
2949 /* Now we've got everything in the final locations, we can
2950 * find optional sections. */
2951 find_module_sections(mod, info);
2953 err = check_module_license_and_versions(mod);
2957 /* Set up MODINFO_ATTR fields */
2958 setup_modinfo(mod, info);
2960 /* Fix up syms, so that st_value is a pointer to location. */
2961 err = simplify_symbols(mod, info);
2965 err = apply_relocations(mod, info);
2969 err = post_relocation(mod, info);
2973 flush_module_icache(mod);
2975 /* Now copy in args */
2976 mod->args = strndup_user(uargs, ~0UL >> 1);
2977 if (IS_ERR(mod->args)) {
2978 err = PTR_ERR(mod->args);
2979 goto free_arch_cleanup;
2982 /* Mark state as coming so strong_try_module_get() ignores us. */
2983 mod->state = MODULE_STATE_COMING;
2985 /* Now sew it into the lists so we can get lockdep and oops
2986 * info during argument parsing. No one should access us, since
2987 * strong_try_module_get() will fail.
2988 * lockdep/oops can run asynchronous, so use the RCU list insertion
2989 * function to insert in a way safe to concurrent readers.
2990 * The mutex protects against concurrent writers.
2992 mutex_lock(&module_mutex);
2993 if (find_module(mod->name)) {
2998 /* This has to be done once we're sure module name is unique. */
2999 dynamic_debug_setup(info->debug, info->num_debug);
3001 /* Find duplicate symbols */
3002 err = verify_export_symbols(mod);
3006 module_bug_finalize(info->hdr, info->sechdrs, mod);
3007 list_add_rcu(&mod->list, &modules);
3008 mutex_unlock(&module_mutex);
3010 /* Module is ready to execute: parsing args may do that. */
3011 err = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
3012 -32768, 32767, NULL);
3016 /* Link in to syfs. */
3017 err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
3021 /* Get rid of temporary copy. */
3025 trace_module_load(mod);
3027 return do_init_module(mod);
3030 mutex_lock(&module_mutex);
3031 /* Unlink carefully: kallsyms could be walking list. */
3032 list_del_rcu(&mod->list);
3033 module_bug_cleanup(mod);
3036 dynamic_debug_remove(info->debug);
3038 mutex_unlock(&module_mutex);
3039 synchronize_sched();
3042 module_arch_cleanup(mod);
3046 module_unload_free(mod);
3048 module_deallocate(mod, info);
3054 /* Call module constructors. */
3055 static void do_mod_ctors(struct module *mod)
3057 #ifdef CONFIG_CONSTRUCTORS
3060 for (i = 0; i < mod->num_ctors; i++)
3065 /* This is where the real work happens */
3066 static int do_init_module(struct module *mod)
3070 blocking_notifier_call_chain(&module_notify_list,
3071 MODULE_STATE_COMING, mod);
3073 /* Set RO and NX regions for core */
3074 set_section_ro_nx(mod->module_core,
3075 mod->core_text_size,
3079 /* Set RO and NX regions for init */
3080 set_section_ro_nx(mod->module_init,
3081 mod->init_text_size,
3086 /* Start the module */
3087 if (mod->init != NULL)
3088 ret = do_one_initcall(mod->init);
3090 /* Init routine failed: abort. Try to protect us from
3091 buggy refcounters. */
3092 mod->state = MODULE_STATE_GOING;
3093 synchronize_sched();
3095 blocking_notifier_call_chain(&module_notify_list,
3096 MODULE_STATE_GOING, mod);
3098 wake_up(&module_wq);
3103 "%s: '%s'->init suspiciously returned %d, it should follow 0/-E convention\n"
3104 "%s: loading module anyway...\n",
3105 __func__, mod->name, ret,
3110 /* Now it's a first class citizen! Wake up anyone waiting for it. */
3111 mod->state = MODULE_STATE_LIVE;
3112 wake_up(&module_wq);
3113 blocking_notifier_call_chain(&module_notify_list,
3114 MODULE_STATE_LIVE, mod);
3116 /* We need to finish all async code before the module init sequence is done */
3117 async_synchronize_full();
3119 mutex_lock(&module_mutex);
3120 /* Drop initial reference. */
3122 trim_init_extable(mod);
3123 #ifdef CONFIG_KALLSYMS
3124 mod->num_symtab = mod->core_num_syms;
3125 mod->symtab = mod->core_symtab;
3126 mod->strtab = mod->core_strtab;
3128 unset_module_init_ro_nx(mod);
3129 module_free(mod, mod->module_init);
3130 mod->module_init = NULL;
3132 mod->init_ro_size = 0;
3133 mod->init_text_size = 0;
3134 mutex_unlock(&module_mutex);
3139 static int init_module_permission(void)
3141 /* Must have permission */
3142 if (!capable(CAP_SYS_MODULE) || modules_disabled)
3148 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
3151 struct load_info info = { };
3153 err = init_module_permission();
3157 pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
3165 err = copy_module_from_fd(fd, &info);
3169 return load_module(&info, uargs);
3172 SYSCALL_DEFINE3(init_module, void __user *, umod,
3173 unsigned long, len, const char __user *, uargs)
3176 struct load_info info = { };
3178 err = init_module_permission();
3182 pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
3185 err = copy_module_from_user(umod, len, &info);
3189 return load_module(&info, uargs);
3192 static inline int within(unsigned long addr, void *start, unsigned long size)
3194 return ((void *)addr >= start && (void *)addr < start + size);
3197 #ifdef CONFIG_KALLSYMS
3199 * This ignores the intensely annoying "mapping symbols" found
3200 * in ARM ELF files: $a, $t and $d.
3202 static inline int is_arm_mapping_symbol(const char *str)
3204 return str[0] == '$' && strchr("atd", str[1])
3205 && (str[2] == '\0' || str[2] == '.');
3208 static const char *get_ksymbol(struct module *mod,
3210 unsigned long *size,
3211 unsigned long *offset)
3213 unsigned int i, best = 0;
3214 unsigned long nextval;
3216 /* At worse, next value is at end of module */
3217 if (within_module_init(addr, mod))
3218 nextval = (unsigned long)mod->module_init+mod->init_text_size;
3220 nextval = (unsigned long)mod->module_core+mod->core_text_size;
3222 /* Scan for closest preceding symbol, and next symbol. (ELF
3223 starts real symbols at 1). */
3224 for (i = 1; i < mod->num_symtab; i++) {
3225 if (mod->symtab[i].st_shndx == SHN_UNDEF)
3228 /* We ignore unnamed symbols: they're uninformative
3229 * and inserted at a whim. */
3230 if (mod->symtab[i].st_value <= addr
3231 && mod->symtab[i].st_value > mod->symtab[best].st_value
3232 && *(mod->strtab + mod->symtab[i].st_name) != '\0'
3233 && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
3235 if (mod->symtab[i].st_value > addr
3236 && mod->symtab[i].st_value < nextval
3237 && *(mod->strtab + mod->symtab[i].st_name) != '\0'
3238 && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
3239 nextval = mod->symtab[i].st_value;
3246 *size = nextval - mod->symtab[best].st_value;
3248 *offset = addr - mod->symtab[best].st_value;
3249 return mod->strtab + mod->symtab[best].st_name;
3252 /* For kallsyms to ask for address resolution. NULL means not found. Careful
3253 * not to lock to avoid deadlock on oopses, simply disable preemption. */
3254 const char *module_address_lookup(unsigned long addr,
3255 unsigned long *size,
3256 unsigned long *offset,
3261 const char *ret = NULL;
3264 list_for_each_entry_rcu(mod, &modules, list) {
3265 if (within_module_init(addr, mod) ||
3266 within_module_core(addr, mod)) {
3268 *modname = mod->name;
3269 ret = get_ksymbol(mod, addr, size, offset);
3273 /* Make a copy in here where it's safe */
3275 strncpy(namebuf, ret, KSYM_NAME_LEN - 1);
3282 int lookup_module_symbol_name(unsigned long addr, char *symname)
3287 list_for_each_entry_rcu(mod, &modules, list) {
3288 if (within_module_init(addr, mod) ||
3289 within_module_core(addr, mod)) {
3292 sym = get_ksymbol(mod, addr, NULL, NULL);
3295 strlcpy(symname, sym, KSYM_NAME_LEN);
3305 int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size,
3306 unsigned long *offset, char *modname, char *name)
3311 list_for_each_entry_rcu(mod, &modules, list) {
3312 if (within_module_init(addr, mod) ||
3313 within_module_core(addr, mod)) {
3316 sym = get_ksymbol(mod, addr, size, offset);
3320 strlcpy(modname, mod->name, MODULE_NAME_LEN);
3322 strlcpy(name, sym, KSYM_NAME_LEN);
3332 int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
3333 char *name, char *module_name, int *exported)
3338 list_for_each_entry_rcu(mod, &modules, list) {
3339 if (symnum < mod->num_symtab) {
3340 *value = mod->symtab[symnum].st_value;
3341 *type = mod->symtab[symnum].st_info;
3342 strlcpy(name, mod->strtab + mod->symtab[symnum].st_name,
3344 strlcpy(module_name, mod->name, MODULE_NAME_LEN);
3345 *exported = is_exported(name, *value, mod);
3349 symnum -= mod->num_symtab;
3355 static unsigned long mod_find_symname(struct module *mod, const char *name)
3359 for (i = 0; i < mod->num_symtab; i++)
3360 if (strcmp(name, mod->strtab+mod->symtab[i].st_name) == 0 &&
3361 mod->symtab[i].st_info != 'U')
3362 return mod->symtab[i].st_value;
3366 /* Look for this name: can be of form module:name. */
3367 unsigned long module_kallsyms_lookup_name(const char *name)
3371 unsigned long ret = 0;
3373 /* Don't lock: we're in enough trouble already. */
3375 if ((colon = strchr(name, ':')) != NULL) {
3377 if ((mod = find_module(name)) != NULL)
3378 ret = mod_find_symname(mod, colon+1);
3381 list_for_each_entry_rcu(mod, &modules, list)
3382 if ((ret = mod_find_symname(mod, name)) != 0)
3389 int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
3390 struct module *, unsigned long),
3397 list_for_each_entry(mod, &modules, list) {
3398 for (i = 0; i < mod->num_symtab; i++) {
3399 ret = fn(data, mod->strtab + mod->symtab[i].st_name,
3400 mod, mod->symtab[i].st_value);
3407 #endif /* CONFIG_KALLSYMS */
3409 static char *module_flags(struct module *mod, char *buf)
3414 mod->state == MODULE_STATE_GOING ||
3415 mod->state == MODULE_STATE_COMING) {
3417 bx += module_flags_taint(mod, buf + bx);
3418 /* Show a - for module-is-being-unloaded */
3419 if (mod->state == MODULE_STATE_GOING)
3421 /* Show a + for module-is-being-loaded */
3422 if (mod->state == MODULE_STATE_COMING)
3431 #ifdef CONFIG_PROC_FS
3432 /* Called by the /proc file system to return a list of modules. */
3433 static void *m_start(struct seq_file *m, loff_t *pos)
3435 mutex_lock(&module_mutex);
3436 return seq_list_start(&modules, *pos);
3439 static void *m_next(struct seq_file *m, void *p, loff_t *pos)
3441 return seq_list_next(p, &modules, pos);
3444 static void m_stop(struct seq_file *m, void *p)
3446 mutex_unlock(&module_mutex);
3449 static int m_show(struct seq_file *m, void *p)
3451 struct module *mod = list_entry(p, struct module, list);
3454 seq_printf(m, "%s %u",
3455 mod->name, mod->init_size + mod->core_size);
3456 print_unload_info(m, mod);
3458 /* Informative for users. */
3459 seq_printf(m, " %s",
3460 mod->state == MODULE_STATE_GOING ? "Unloading":
3461 mod->state == MODULE_STATE_COMING ? "Loading":
3463 /* Used by oprofile and other similar tools. */
3464 seq_printf(m, " 0x%pK", mod->module_core);
3468 seq_printf(m, " %s", module_flags(mod, buf));
3470 seq_printf(m, "\n");
3474 /* Format: modulename size refcount deps address
3476 Where refcount is a number or -, and deps is a comma-separated list
3479 static const struct seq_operations modules_op = {
3486 static int modules_open(struct inode *inode, struct file *file)
3488 return seq_open(file, &modules_op);
3491 static const struct file_operations proc_modules_operations = {
3492 .open = modules_open,
3494 .llseek = seq_lseek,
3495 .release = seq_release,
3498 static int __init proc_modules_init(void)
3500 proc_create("modules", 0, NULL, &proc_modules_operations);
3503 module_init(proc_modules_init);
3506 /* Given an address, look for it in the module exception tables. */
3507 const struct exception_table_entry *search_module_extables(unsigned long addr)
3509 const struct exception_table_entry *e = NULL;
3513 list_for_each_entry_rcu(mod, &modules, list) {
3514 if (mod->num_exentries == 0)
3517 e = search_extable(mod->extable,
3518 mod->extable + mod->num_exentries - 1,
3525 /* Now, if we found one, we are running inside it now, hence
3526 we cannot unload the module, hence no refcnt needed. */
3531 * is_module_address - is this address inside a module?
3532 * @addr: the address to check.
3534 * See is_module_text_address() if you simply want to see if the address
3535 * is code (not data).
3537 bool is_module_address(unsigned long addr)
3542 ret = __module_address(addr) != NULL;
3549 * __module_address - get the module which contains an address.
3550 * @addr: the address.
3552 * Must be called with preempt disabled or module mutex held so that
3553 * module doesn't get freed during this.
3555 struct module *__module_address(unsigned long addr)
3559 if (addr < module_addr_min || addr > module_addr_max)
3562 list_for_each_entry_rcu(mod, &modules, list)
3563 if (within_module_core(addr, mod)
3564 || within_module_init(addr, mod))
3568 EXPORT_SYMBOL_GPL(__module_address);
3571 * is_module_text_address - is this address inside module code?
3572 * @addr: the address to check.
3574 * See is_module_address() if you simply want to see if the address is
3575 * anywhere in a module. See kernel_text_address() for testing if an
3576 * address corresponds to kernel or module code.
3578 bool is_module_text_address(unsigned long addr)
3583 ret = __module_text_address(addr) != NULL;
3590 * __module_text_address - get the module whose code contains an address.
3591 * @addr: the address.
3593 * Must be called with preempt disabled or module mutex held so that
3594 * module doesn't get freed during this.
3596 struct module *__module_text_address(unsigned long addr)
3598 struct module *mod = __module_address(addr);
3600 /* Make sure it's within the text section. */
3601 if (!within(addr, mod->module_init, mod->init_text_size)
3602 && !within(addr, mod->module_core, mod->core_text_size))
3607 EXPORT_SYMBOL_GPL(__module_text_address);
3609 /* Don't grab lock, we're oopsing. */
3610 void print_modules(void)
3615 printk(KERN_DEFAULT "Modules linked in:");
3616 /* Most callers should already have preempt disabled, but make sure */
3618 list_for_each_entry_rcu(mod, &modules, list)
3619 printk(" %s%s", mod->name, module_flags(mod, buf));
3621 if (last_unloaded_module[0])
3622 printk(" [last unloaded: %s]", last_unloaded_module);
3626 #ifdef CONFIG_MODVERSIONS
3627 /* Generate the signature for all relevant module structures here.
3628 * If these change, we don't want to try to parse the module. */
3629 void module_layout(struct module *mod,
3630 struct modversion_info *ver,
3631 struct kernel_param *kp,
3632 struct kernel_symbol *ks,
3633 struct tracepoint * const *tp)
3636 EXPORT_SYMBOL(module_layout);