blob: 6b3d0ad3c299e1edaa8b6631a1d429dfbc254b10 [file] [log] [blame]
lh9ed821d2023-04-07 01:36:19 -07001/*
2 Copyright (C) 2002 Richard Henderson
3 Copyright (C) 2001 Rusty Russell, 2002, 2010 Rusty Russell IBM.
4
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.
9
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.
14
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
18*/
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/fs.h>
25#include <linux/sysfs.h>
26#include <linux/kernel.h>
27#include <linux/slab.h>
28#include <linux/vmalloc.h>
29#include <linux/elf.h>
30#include <linux/proc_fs.h>
31#include <linux/seq_file.h>
32#include <linux/syscalls.h>
33#include <linux/fcntl.h>
34#include <linux/rcupdate.h>
35#include <linux/capability.h>
36#include <linux/cpu.h>
37#include <linux/moduleparam.h>
38#include <linux/errno.h>
39#include <linux/err.h>
40#include <linux/vermagic.h>
41#include <linux/notifier.h>
42#include <linux/sched.h>
43#include <linux/stop_machine.h>
44#include <linux/device.h>
45#include <linux/string.h>
46#include <linux/mutex.h>
47#include <linux/rculist.h>
48#include <asm/uaccess.h>
49#include <asm/cacheflush.h>
50#include <asm/mmu_context.h>
51#include <linux/license.h>
52#include <asm/sections.h>
53#include <linux/tracepoint.h>
54#include <linux/ftrace.h>
55#include <linux/async.h>
56#include <linux/percpu.h>
57#include <linux/kmemleak.h>
58#include <linux/jump_label.h>
59#include <linux/pfn.h>
60#include <linux/bsearch.h>
61
62#define CREATE_TRACE_POINTS
63#include <trace/events/module.h>
64
65#ifndef ARCH_SHF_SMALL
66#define ARCH_SHF_SMALL 0
67#endif
68
69/* zhouguopo enable CONFIG_KALLSYMS in module for trace32 ko and ramdump ko */
70#define CONFIG_KALLSYMS 1
71
72/*
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
76 */
77#ifdef CONFIG_DEBUG_SET_MODULE_RONX
78# define debug_align(X) ALIGN(X, PAGE_SIZE)
79#else
80# define debug_align(X) (X)
81#endif
82
83/*
84 * Given BASE and SIZE this macro calculates the number of pages the
85 * memory regions occupies
86 */
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) \
90 : (0UL))
91
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))
94
95/*
96 * Mutex protects:
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 uses stop_machine/add uses RCU list operations). */
101DEFINE_MUTEX(module_mutex);
102EXPORT_SYMBOL_GPL(module_mutex);
103static LIST_HEAD(modules);
104#ifdef CONFIG_KGDB_KDB
105struct list_head *kdb_modules = &modules; /* kdb needs the list of modules */
106#endif /* CONFIG_KGDB_KDB */
107
108
109/* Block module loading/unloading? */
110int modules_disabled = 0;
111
112core_param(nomodule, modules_disabled, bint, 0);
113
114/* Waiting for a module to finish initializing? */
115static DECLARE_WAIT_QUEUE_HEAD(module_wq);
116
117static BLOCKING_NOTIFIER_HEAD(module_notify_list);
118
119/* Bounds of module allocation, for speeding __module_address.
120 * Protected by module_mutex. */
121static unsigned long module_addr_min = -1UL, module_addr_max = 0;
122
123int register_module_notifier(struct notifier_block * nb)
124{
125 return blocking_notifier_chain_register(&module_notify_list, nb);
126}
127EXPORT_SYMBOL(register_module_notifier);
128
129int unregister_module_notifier(struct notifier_block * nb)
130{
131 return blocking_notifier_chain_unregister(&module_notify_list, nb);
132}
133EXPORT_SYMBOL(unregister_module_notifier);
134
135struct load_info {
136 Elf_Ehdr *hdr;
137 unsigned long len;
138 Elf_Shdr *sechdrs;
139 char *secstrings, *strtab;
140 unsigned long symoffs, stroffs;
141 struct _ddebug *debug;
142 unsigned int num_debug;
143 struct {
144 unsigned int sym, str, mod, vers, info, pcpu;
145 } index;
146};
147
148/* We require a truly strong try_module_get(): 0 means failure due to
149 ongoing or failed initialization etc. */
150static inline int strong_try_module_get(struct module *mod)
151{
152 if (mod && mod->state == MODULE_STATE_COMING)
153 return -EBUSY;
154 if (try_module_get(mod))
155 return 0;
156 else
157 return -ENOENT;
158}
159
160static inline void add_taint_module(struct module *mod, unsigned flag)
161{
162 add_taint(flag);
163 mod->taints |= (1U << flag);
164}
165
166/*
167 * A thread that wants to hold a reference to a module only while it
168 * is running can call this to safely exit. nfsd and lockd use this.
169 */
170void __module_put_and_exit(struct module *mod, long code)
171{
172 module_put(mod);
173 do_exit(code);
174}
175EXPORT_SYMBOL(__module_put_and_exit);
176
177/* Find a module section: 0 means not found. */
178static unsigned int find_sec(const struct load_info *info, const char *name)
179{
180 unsigned int i;
181
182 for (i = 1; i < info->hdr->e_shnum; i++) {
183 Elf_Shdr *shdr = &info->sechdrs[i];
184 /* Alloc bit cleared means "ignore it." */
185 if ((shdr->sh_flags & SHF_ALLOC)
186 && strcmp(info->secstrings + shdr->sh_name, name) == 0)
187 return i;
188 }
189 return 0;
190}
191
192/* Find a module section, or NULL. */
193static void *section_addr(const struct load_info *info, const char *name)
194{
195 /* Section 0 has sh_addr 0. */
196 return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
197}
198#ifdef CONFIG_MODEM_CODE_IS_MAPPING
199/* Find a module offset, or NULL. */
200static unsigned int section_addr_offset(const struct load_info *info, const char *name)
201{
202 /* Section 0 has sh_addr 0. */
203 return (void *)info->sechdrs[find_sec(info, name)].sh_offset;
204}
205#endif
206/* Find a module section, or NULL. Fill in number of "objects" in section. */
207static void *section_objs(const struct load_info *info,
208 const char *name,
209 size_t object_size,
210 unsigned int *num)
211{
212 unsigned int sec = find_sec(info, name);
213
214 /* Section 0 has sh_addr 0 and sh_size 0. */
215 *num = info->sechdrs[sec].sh_size / object_size;
216 return (void *)info->sechdrs[sec].sh_addr;
217}
218
219/* Provided by the linker */
220extern const struct kernel_symbol __start___ksymtab[];
221extern const struct kernel_symbol __stop___ksymtab[];
222extern const struct kernel_symbol __start___ksymtab_gpl[];
223extern const struct kernel_symbol __stop___ksymtab_gpl[];
224extern const struct kernel_symbol __start___ksymtab_gpl_future[];
225extern const struct kernel_symbol __stop___ksymtab_gpl_future[];
226extern const unsigned long __start___kcrctab[];
227extern const unsigned long __start___kcrctab_gpl[];
228extern const unsigned long __start___kcrctab_gpl_future[];
229#ifdef CONFIG_UNUSED_SYMBOLS
230extern const struct kernel_symbol __start___ksymtab_unused[];
231extern const struct kernel_symbol __stop___ksymtab_unused[];
232extern const struct kernel_symbol __start___ksymtab_unused_gpl[];
233extern const struct kernel_symbol __stop___ksymtab_unused_gpl[];
234extern const unsigned long __start___kcrctab_unused[];
235extern const unsigned long __start___kcrctab_unused_gpl[];
236#endif
237
238#ifndef CONFIG_MODVERSIONS
239#define symversion(base, idx) NULL
240#else
241#define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
242#endif
243
244static bool each_symbol_in_section(const struct symsearch *arr,
245 unsigned int arrsize,
246 struct module *owner,
247 bool (*fn)(const struct symsearch *syms,
248 struct module *owner,
249 void *data),
250 void *data)
251{
252 unsigned int j;
253
254 for (j = 0; j < arrsize; j++) {
255 if (fn(&arr[j], owner, data))
256 return true;
257 }
258
259 return false;
260}
261
262/* Returns true as soon as fn returns true, otherwise false. */
263bool each_symbol_section(bool (*fn)(const struct symsearch *arr,
264 struct module *owner,
265 void *data),
266 void *data)
267{
268 struct module *mod;
269 static const struct symsearch arr[] = {
270 { __start___ksymtab, __stop___ksymtab, __start___kcrctab,
271 NOT_GPL_ONLY, false },
272 { __start___ksymtab_gpl, __stop___ksymtab_gpl,
273 __start___kcrctab_gpl,
274 GPL_ONLY, false },
275 { __start___ksymtab_gpl_future, __stop___ksymtab_gpl_future,
276 __start___kcrctab_gpl_future,
277 WILL_BE_GPL_ONLY, false },
278#ifdef CONFIG_UNUSED_SYMBOLS
279 { __start___ksymtab_unused, __stop___ksymtab_unused,
280 __start___kcrctab_unused,
281 NOT_GPL_ONLY, true },
282 { __start___ksymtab_unused_gpl, __stop___ksymtab_unused_gpl,
283 __start___kcrctab_unused_gpl,
284 GPL_ONLY, true },
285#endif
286 };
287
288 if (each_symbol_in_section(arr, ARRAY_SIZE(arr), NULL, fn, data))
289 return true;
290
291 list_for_each_entry_rcu(mod, &modules, list) {
292 struct symsearch arr[] = {
293 { mod->syms, mod->syms + mod->num_syms, mod->crcs,
294 NOT_GPL_ONLY, false },
295 { mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
296 mod->gpl_crcs,
297 GPL_ONLY, false },
298 { mod->gpl_future_syms,
299 mod->gpl_future_syms + mod->num_gpl_future_syms,
300 mod->gpl_future_crcs,
301 WILL_BE_GPL_ONLY, false },
302#ifdef CONFIG_UNUSED_SYMBOLS
303 { mod->unused_syms,
304 mod->unused_syms + mod->num_unused_syms,
305 mod->unused_crcs,
306 NOT_GPL_ONLY, true },
307 { mod->unused_gpl_syms,
308 mod->unused_gpl_syms + mod->num_unused_gpl_syms,
309 mod->unused_gpl_crcs,
310 GPL_ONLY, true },
311#endif
312 };
313
314 if (each_symbol_in_section(arr, ARRAY_SIZE(arr), mod, fn, data))
315 return true;
316 }
317 return false;
318}
319EXPORT_SYMBOL_GPL(each_symbol_section);
320
321struct find_symbol_arg {
322 /* Input */
323 const char *name;
324 bool gplok;
325 bool warn;
326
327 /* Output */
328 struct module *owner;
329 const unsigned long *crc;
330 const struct kernel_symbol *sym;
331};
332
333static bool check_symbol(const struct symsearch *syms,
334 struct module *owner,
335 unsigned int symnum, void *data)
336{
337 struct find_symbol_arg *fsa = data;
338
339 if (!fsa->gplok) {
340 if (syms->licence == GPL_ONLY)
341 return false;
342 if (syms->licence == WILL_BE_GPL_ONLY && fsa->warn) {
343 printk(KERN_WARNING "Symbol %s is being used "
344 "by a non-GPL module, which will not "
345 "be allowed in the future\n", fsa->name);
346 printk(KERN_WARNING "Please see the file "
347 "Documentation/feature-removal-schedule.txt "
348 "in the kernel source tree for more details.\n");
349 }
350 }
351
352#ifdef CONFIG_UNUSED_SYMBOLS
353 if (syms->unused && fsa->warn) {
354 printk(KERN_WARNING "Symbol %s is marked as UNUSED, "
355 "however this module is using it.\n", fsa->name);
356 printk(KERN_WARNING
357 "This symbol will go away in the future.\n");
358 printk(KERN_WARNING
359 "Please evalute if this is the right api to use and if "
360 "it really is, submit a report the linux kernel "
361 "mailinglist together with submitting your code for "
362 "inclusion.\n");
363 }
364#endif
365
366 fsa->owner = owner;
367 fsa->crc = symversion(syms->crcs, symnum);
368 fsa->sym = &syms->start[symnum];
369 return true;
370}
371
372static int cmp_name(const void *va, const void *vb)
373{
374 const char *a;
375 const struct kernel_symbol *b;
376 a = va; b = vb;
377 return strcmp(a, b->name);
378}
379
380static bool find_symbol_in_section(const struct symsearch *syms,
381 struct module *owner,
382 void *data)
383{
384 struct find_symbol_arg *fsa = data;
385 struct kernel_symbol *sym;
386
387 sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
388 sizeof(struct kernel_symbol), cmp_name);
389
390 if (sym != NULL && check_symbol(syms, owner, sym - syms->start, data))
391 return true;
392
393 return false;
394}
395
396/* Find a symbol and return it, along with, (optional) crc and
397 * (optional) module which owns it. Needs preempt disabled or module_mutex. */
398const struct kernel_symbol *find_symbol(const char *name,
399 struct module **owner,
400 const unsigned long **crc,
401 bool gplok,
402 bool warn)
403{
404 struct find_symbol_arg fsa;
405
406 fsa.name = name;
407 fsa.gplok = gplok;
408 fsa.warn = warn;
409
410 if (each_symbol_section(find_symbol_in_section, &fsa)) {
411 if (owner)
412 *owner = fsa.owner;
413 if (crc)
414 *crc = fsa.crc;
415 return fsa.sym;
416 }
417
418 pr_debug("Failed to find symbol %s\n", name);
419 return NULL;
420}
421EXPORT_SYMBOL_GPL(find_symbol);
422
423/* Search for module by name: must hold module_mutex. */
424struct module *find_module(const char *name)
425{
426 struct module *mod;
427
428 list_for_each_entry(mod, &modules, list) {
429 if (strcmp(mod->name, name) == 0)
430 return mod;
431 }
432 return NULL;
433}
434EXPORT_SYMBOL_GPL(find_module);
435
436#ifdef CONFIG_SMP
437
438static inline void __percpu *mod_percpu(struct module *mod)
439{
440 return mod->percpu;
441}
442
443static int percpu_modalloc(struct module *mod,
444 unsigned long size, unsigned long align)
445{
446 if (align > PAGE_SIZE) {
447 printk(KERN_WARNING "%s: per-cpu alignment %li > %li\n",
448 mod->name, align, PAGE_SIZE);
449 align = PAGE_SIZE;
450 }
451
452 mod->percpu = __alloc_reserved_percpu(size, align);
453 if (!mod->percpu) {
454 printk(KERN_WARNING
455 "%s: Could not allocate %lu bytes percpu data\n",
456 mod->name, size);
457 return -ENOMEM;
458 }
459 mod->percpu_size = size;
460 return 0;
461}
462
463static void percpu_modfree(struct module *mod)
464{
465 free_percpu(mod->percpu);
466}
467
468static unsigned int find_pcpusec(struct load_info *info)
469{
470 return find_sec(info, ".data..percpu");
471}
472
473static void percpu_modcopy(struct module *mod,
474 const void *from, unsigned long size)
475{
476 int cpu;
477
478 for_each_possible_cpu(cpu)
479 memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
480}
481
482/**
483 * is_module_percpu_address - test whether address is from module static percpu
484 * @addr: address to test
485 *
486 * Test whether @addr belongs to module static percpu area.
487 *
488 * RETURNS:
489 * %true if @addr is from module static percpu area
490 */
491bool is_module_percpu_address(unsigned long addr)
492{
493 struct module *mod;
494 unsigned int cpu;
495
496 preempt_disable();
497
498 list_for_each_entry_rcu(mod, &modules, list) {
499 if (!mod->percpu_size)
500 continue;
501 for_each_possible_cpu(cpu) {
502 void *start = per_cpu_ptr(mod->percpu, cpu);
503
504 if ((void *)addr >= start &&
505 (void *)addr < start + mod->percpu_size) {
506 preempt_enable();
507 return true;
508 }
509 }
510 }
511
512 preempt_enable();
513 return false;
514}
515
516#else /* ... !CONFIG_SMP */
517
518static inline void __percpu *mod_percpu(struct module *mod)
519{
520 return NULL;
521}
522static inline int percpu_modalloc(struct module *mod,
523 unsigned long size, unsigned long align)
524{
525 return -ENOMEM;
526}
527static inline void percpu_modfree(struct module *mod)
528{
529}
530static unsigned int find_pcpusec(struct load_info *info)
531{
532 return 0;
533}
534static inline void percpu_modcopy(struct module *mod,
535 const void *from, unsigned long size)
536{
537 /* pcpusec should be 0, and size of that section should be 0. */
538 BUG_ON(size != 0);
539}
540bool is_module_percpu_address(unsigned long addr)
541{
542 return false;
543}
544
545#endif /* CONFIG_SMP */
546
547#define MODINFO_ATTR(field) \
548static void setup_modinfo_##field(struct module *mod, const char *s) \
549{ \
550 mod->field = kstrdup(s, GFP_KERNEL); \
551} \
552static ssize_t show_modinfo_##field(struct module_attribute *mattr, \
553 struct module_kobject *mk, char *buffer) \
554{ \
555 return sprintf(buffer, "%s\n", mk->mod->field); \
556} \
557static int modinfo_##field##_exists(struct module *mod) \
558{ \
559 return mod->field != NULL; \
560} \
561static void free_modinfo_##field(struct module *mod) \
562{ \
563 kfree(mod->field); \
564 mod->field = NULL; \
565} \
566static struct module_attribute modinfo_##field = { \
567 .attr = { .name = __stringify(field), .mode = 0444 }, \
568 .show = show_modinfo_##field, \
569 .setup = setup_modinfo_##field, \
570 .test = modinfo_##field##_exists, \
571 .free = free_modinfo_##field, \
572};
573
574MODINFO_ATTR(version);
575MODINFO_ATTR(srcversion);
576
577static char last_unloaded_module[MODULE_NAME_LEN+1];
578
579#ifdef CONFIG_MODULE_UNLOAD
580
581EXPORT_TRACEPOINT_SYMBOL(module_get);
582
583/* Init the unload section of the module. */
584static int module_unload_init(struct module *mod)
585{
586 mod->refptr = alloc_percpu(struct module_ref);
587 if (!mod->refptr)
588 return -ENOMEM;
589
590 INIT_LIST_HEAD(&mod->source_list);
591 INIT_LIST_HEAD(&mod->target_list);
592
593 /* Hold reference count during initialization. */
594 __this_cpu_write(mod->refptr->incs, 1);
595 /* Backwards compatibility macros put refcount during init. */
596 mod->waiter = current;
597
598 return 0;
599}
600
601/* Does a already use b? */
602static int already_uses(struct module *a, struct module *b)
603{
604 struct module_use *use;
605
606 list_for_each_entry(use, &b->source_list, source_list) {
607 if (use->source == a) {
608 pr_debug("%s uses %s!\n", a->name, b->name);
609 return 1;
610 }
611 }
612 pr_debug("%s does not use %s!\n", a->name, b->name);
613 return 0;
614}
615
616/*
617 * Module a uses b
618 * - we add 'a' as a "source", 'b' as a "target" of module use
619 * - the module_use is added to the list of 'b' sources (so
620 * 'b' can walk the list to see who sourced them), and of 'a'
621 * targets (so 'a' can see what modules it targets).
622 */
623static int add_module_usage(struct module *a, struct module *b)
624{
625 struct module_use *use;
626
627 pr_debug("Allocating new usage for %s.\n", a->name);
628 use = kmalloc(sizeof(*use), GFP_ATOMIC);
629 if (!use) {
630 printk(KERN_WARNING "%s: out of memory loading\n", a->name);
631 return -ENOMEM;
632 }
633
634 use->source = a;
635 use->target = b;
636 list_add(&use->source_list, &b->source_list);
637 list_add(&use->target_list, &a->target_list);
638 return 0;
639}
640
641/* Module a uses b: caller needs module_mutex() */
642int ref_module(struct module *a, struct module *b)
643{
644 int err;
645
646 if (b == NULL || already_uses(a, b))
647 return 0;
648
649 /* If module isn't available, we fail. */
650 err = strong_try_module_get(b);
651 if (err)
652 return err;
653
654 err = add_module_usage(a, b);
655 if (err) {
656 module_put(b);
657 return err;
658 }
659 return 0;
660}
661EXPORT_SYMBOL_GPL(ref_module);
662
663/* Clear the unload stuff of the module. */
664static void module_unload_free(struct module *mod)
665{
666 struct module_use *use, *tmp;
667
668 mutex_lock(&module_mutex);
669 list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
670 struct module *i = use->target;
671 pr_debug("%s unusing %s\n", mod->name, i->name);
672 module_put(i);
673 list_del(&use->source_list);
674 list_del(&use->target_list);
675 kfree(use);
676 }
677 mutex_unlock(&module_mutex);
678
679 free_percpu(mod->refptr);
680}
681
682#ifdef CONFIG_MODULE_FORCE_UNLOAD
683static inline int try_force_unload(unsigned int flags)
684{
685 int ret = (flags & O_TRUNC);
686 if (ret)
687 add_taint(TAINT_FORCED_RMMOD);
688 return ret;
689}
690#else
691static inline int try_force_unload(unsigned int flags)
692{
693 return 0;
694}
695#endif /* CONFIG_MODULE_FORCE_UNLOAD */
696
697struct stopref
698{
699 struct module *mod;
700 int flags;
701 int *forced;
702};
703
704/* Whole machine is stopped with interrupts off when this runs. */
705static int __try_stop_module(void *_sref)
706{
707 struct stopref *sref = _sref;
708
709 /* If it's not unused, quit unless we're forcing. */
710 if (module_refcount(sref->mod) != 0) {
711 if (!(*sref->forced = try_force_unload(sref->flags)))
712 return -EWOULDBLOCK;
713 }
714
715 /* Mark it as dying. */
716 sref->mod->state = MODULE_STATE_GOING;
717 return 0;
718}
719
720static int try_stop_module(struct module *mod, int flags, int *forced)
721{
722 if (flags & O_NONBLOCK) {
723 struct stopref sref = { mod, flags, forced };
724
725 return stop_machine(__try_stop_module, &sref, NULL);
726 } else {
727 /* We don't need to stop the machine for this. */
728 mod->state = MODULE_STATE_GOING;
729 synchronize_sched();
730 return 0;
731 }
732}
733
734unsigned long module_refcount(struct module *mod)
735{
736 unsigned long incs = 0, decs = 0;
737 int cpu;
738
739 for_each_possible_cpu(cpu)
740 decs += per_cpu_ptr(mod->refptr, cpu)->decs;
741 /*
742 * ensure the incs are added up after the decs.
743 * module_put ensures incs are visible before decs with smp_wmb.
744 *
745 * This 2-count scheme avoids the situation where the refcount
746 * for CPU0 is read, then CPU0 increments the module refcount,
747 * then CPU1 drops that refcount, then the refcount for CPU1 is
748 * read. We would record a decrement but not its corresponding
749 * increment so we would see a low count (disaster).
750 *
751 * Rare situation? But module_refcount can be preempted, and we
752 * might be tallying up 4096+ CPUs. So it is not impossible.
753 */
754 smp_rmb();
755 for_each_possible_cpu(cpu)
756 incs += per_cpu_ptr(mod->refptr, cpu)->incs;
757 return incs - decs;
758}
759EXPORT_SYMBOL(module_refcount);
760
761/* This exists whether we can unload or not */
762static void free_module(struct module *mod);
763
764static void wait_for_zero_refcount(struct module *mod)
765{
766 /* Since we might sleep for some time, release the mutex first */
767 mutex_unlock(&module_mutex);
768 for (;;) {
769 pr_debug("Looking at refcount...\n");
770 set_current_state(TASK_UNINTERRUPTIBLE);
771 if (module_refcount(mod) == 0)
772 break;
773 schedule();
774 }
775 current->state = TASK_RUNNING;
776 mutex_lock(&module_mutex);
777}
778
779SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
780 unsigned int, flags)
781{
782 struct module *mod;
783 char name[MODULE_NAME_LEN];
784 int ret, forced = 0;
785
786 if (!capable(CAP_SYS_MODULE) || modules_disabled)
787 return -EPERM;
788
789 if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
790 return -EFAULT;
791 name[MODULE_NAME_LEN-1] = '\0';
792
793 if (mutex_lock_interruptible(&module_mutex) != 0)
794 return -EINTR;
795
796 mod = find_module(name);
797 if (!mod) {
798 ret = -ENOENT;
799 goto out;
800 }
801
802 if (!list_empty(&mod->source_list)) {
803 /* Other modules depend on us: get rid of them first. */
804 ret = -EWOULDBLOCK;
805 goto out;
806 }
807
808 /* Doing init or already dying? */
809 if (mod->state != MODULE_STATE_LIVE) {
810 /* FIXME: if (force), slam module count and wake up
811 waiter --RR */
812 pr_debug("%s already dying\n", mod->name);
813 ret = -EBUSY;
814 goto out;
815 }
816
817 /* If it has an init func, it must have an exit func to unload */
818 if (mod->init && !mod->exit) {
819 forced = try_force_unload(flags);
820 if (!forced) {
821 /* This module can't be removed */
822 ret = -EBUSY;
823 goto out;
824 }
825 }
826
827 /* Set this up before setting mod->state */
828 mod->waiter = current;
829
830 /* Stop the machine so refcounts can't move and disable module. */
831 ret = try_stop_module(mod, flags, &forced);
832 if (ret != 0)
833 goto out;
834
835 /* Never wait if forced. */
836 if (!forced && module_refcount(mod) != 0)
837 wait_for_zero_refcount(mod);
838
839 mutex_unlock(&module_mutex);
840 /* Final destruction now no one is using it. */
841 if (mod->exit != NULL)
842 mod->exit();
843 blocking_notifier_call_chain(&module_notify_list,
844 MODULE_STATE_GOING, mod);
845 async_synchronize_full();
846
847 /* Store the name of the last unloaded module for diagnostic purposes */
848 strlcpy(last_unloaded_module, mod->name, sizeof(last_unloaded_module));
849
850 free_module(mod);
851 return 0;
852out:
853 mutex_unlock(&module_mutex);
854 return ret;
855}
856
857static inline void print_unload_info(struct seq_file *m, struct module *mod)
858{
859 struct module_use *use;
860 int printed_something = 0;
861
862 seq_printf(m, " %lu ", module_refcount(mod));
863
864 /* Always include a trailing , so userspace can differentiate
865 between this and the old multi-field proc format. */
866 list_for_each_entry(use, &mod->source_list, source_list) {
867 printed_something = 1;
868 seq_printf(m, "%s,", use->source->name);
869 }
870
871 if (mod->init != NULL && mod->exit == NULL) {
872 printed_something = 1;
873 seq_printf(m, "[permanent],");
874 }
875
876 if (!printed_something)
877 seq_printf(m, "-");
878}
879
880void __symbol_put(const char *symbol)
881{
882 struct module *owner;
883
884 preempt_disable();
885 if (!find_symbol(symbol, &owner, NULL, true, false))
886 BUG();
887 module_put(owner);
888 preempt_enable();
889}
890EXPORT_SYMBOL(__symbol_put);
891
892/* Note this assumes addr is a function, which it currently always is. */
893void symbol_put_addr(void *addr)
894{
895 struct module *modaddr;
896 unsigned long a = (unsigned long)dereference_function_descriptor(addr);
897
898 if (core_kernel_text(a))
899 return;
900
901 /* module_text_address is safe here: we're supposed to have reference
902 * to module from symbol_get, so it can't go away. */
903 modaddr = __module_text_address(a);
904 BUG_ON(!modaddr);
905 module_put(modaddr);
906}
907EXPORT_SYMBOL_GPL(symbol_put_addr);
908
909static ssize_t show_refcnt(struct module_attribute *mattr,
910 struct module_kobject *mk, char *buffer)
911{
912 return sprintf(buffer, "%lu\n", module_refcount(mk->mod));
913}
914
915static struct module_attribute modinfo_refcnt =
916 __ATTR(refcnt, 0444, show_refcnt, NULL);
917
918void __module_get(struct module *module)
919{
920 if (module) {
921 preempt_disable();
922 __this_cpu_inc(module->refptr->incs);
923 trace_module_get(module, _RET_IP_);
924 preempt_enable();
925 }
926}
927EXPORT_SYMBOL(__module_get);
928
929bool try_module_get(struct module *module)
930{
931 bool ret = true;
932
933 if (module) {
934 preempt_disable();
935
936 if (likely(module_is_live(module))) {
937 __this_cpu_inc(module->refptr->incs);
938 trace_module_get(module, _RET_IP_);
939 } else
940 ret = false;
941
942 preempt_enable();
943 }
944 return ret;
945}
946EXPORT_SYMBOL(try_module_get);
947
948void module_put(struct module *module)
949{
950 if (module) {
951 preempt_disable();
952 smp_wmb(); /* see comment in module_refcount */
953 __this_cpu_inc(module->refptr->decs);
954
955 trace_module_put(module, _RET_IP_);
956 /* Maybe they're waiting for us to drop reference? */
957 if (unlikely(!module_is_live(module)))
958 wake_up_process(module->waiter);
959 preempt_enable();
960 }
961}
962EXPORT_SYMBOL(module_put);
963
964#else /* !CONFIG_MODULE_UNLOAD */
965static inline void print_unload_info(struct seq_file *m, struct module *mod)
966{
967 /* We don't know the usage count, or what modules are using. */
968 seq_printf(m, " - -");
969}
970
971static inline void module_unload_free(struct module *mod)
972{
973}
974
975int ref_module(struct module *a, struct module *b)
976{
977 return strong_try_module_get(b);
978}
979EXPORT_SYMBOL_GPL(ref_module);
980
981static inline int module_unload_init(struct module *mod)
982{
983 return 0;
984}
985#endif /* CONFIG_MODULE_UNLOAD */
986
987static size_t module_flags_taint(struct module *mod, char *buf)
988{
989 size_t l = 0;
990
991 if (mod->taints & (1 << TAINT_PROPRIETARY_MODULE))
992 buf[l++] = 'P';
993 if (mod->taints & (1 << TAINT_OOT_MODULE))
994 buf[l++] = 'O';
995 if (mod->taints & (1 << TAINT_FORCED_MODULE))
996 buf[l++] = 'F';
997 if (mod->taints & (1 << TAINT_CRAP))
998 buf[l++] = 'C';
999 /*
1000 * TAINT_FORCED_RMMOD: could be added.
1001 * TAINT_UNSAFE_SMP, TAINT_MACHINE_CHECK, TAINT_BAD_PAGE don't
1002 * apply to modules.
1003 */
1004 return l;
1005}
1006
1007static ssize_t show_initstate(struct module_attribute *mattr,
1008 struct module_kobject *mk, char *buffer)
1009{
1010 const char *state = "unknown";
1011
1012 switch (mk->mod->state) {
1013 case MODULE_STATE_LIVE:
1014 state = "live";
1015 break;
1016 case MODULE_STATE_COMING:
1017 state = "coming";
1018 break;
1019 case MODULE_STATE_GOING:
1020 state = "going";
1021 break;
1022 }
1023 return sprintf(buffer, "%s\n", state);
1024}
1025
1026static struct module_attribute modinfo_initstate =
1027 __ATTR(initstate, 0444, show_initstate, NULL);
1028
1029static ssize_t store_uevent(struct module_attribute *mattr,
1030 struct module_kobject *mk,
1031 const char *buffer, size_t count)
1032{
1033 enum kobject_action action;
1034
1035 if (kobject_action_type(buffer, count, &action) == 0)
1036 kobject_uevent(&mk->kobj, action);
1037 return count;
1038}
1039
1040struct module_attribute module_uevent =
1041 __ATTR(uevent, 0200, NULL, store_uevent);
1042
1043static ssize_t show_coresize(struct module_attribute *mattr,
1044 struct module_kobject *mk, char *buffer)
1045{
1046 return sprintf(buffer, "%u\n", mk->mod->core_size);
1047}
1048
1049static struct module_attribute modinfo_coresize =
1050 __ATTR(coresize, 0444, show_coresize, NULL);
1051
1052static ssize_t show_initsize(struct module_attribute *mattr,
1053 struct module_kobject *mk, char *buffer)
1054{
1055 return sprintf(buffer, "%u\n", mk->mod->init_size);
1056}
1057
1058static struct module_attribute modinfo_initsize =
1059 __ATTR(initsize, 0444, show_initsize, NULL);
1060
1061static ssize_t show_taint(struct module_attribute *mattr,
1062 struct module_kobject *mk, char *buffer)
1063{
1064 size_t l;
1065
1066 l = module_flags_taint(mk->mod, buffer);
1067 buffer[l++] = '\n';
1068 return l;
1069}
1070
1071static struct module_attribute modinfo_taint =
1072 __ATTR(taint, 0444, show_taint, NULL);
1073
1074static struct module_attribute *modinfo_attrs[] = {
1075 &module_uevent,
1076 &modinfo_version,
1077 &modinfo_srcversion,
1078 &modinfo_initstate,
1079 &modinfo_coresize,
1080 &modinfo_initsize,
1081 &modinfo_taint,
1082#ifdef CONFIG_MODULE_UNLOAD
1083 &modinfo_refcnt,
1084#endif
1085 NULL,
1086};
1087
1088static const char vermagic[] = VERMAGIC_STRING;
1089
1090static int try_to_force_load(struct module *mod, const char *reason)
1091{
1092#ifdef CONFIG_MODULE_FORCE_LOAD
1093 if (!test_taint(TAINT_FORCED_MODULE))
1094 printk(KERN_WARNING "%s: %s: kernel tainted.\n",
1095 mod->name, reason);
1096 add_taint_module(mod, TAINT_FORCED_MODULE);
1097 return 0;
1098#else
1099 return -ENOEXEC;
1100#endif
1101}
1102
1103#ifdef CONFIG_MODVERSIONS
1104/* If the arch applies (non-zero) relocations to kernel kcrctab, unapply it. */
1105static unsigned long maybe_relocated(unsigned long crc,
1106 const struct module *crc_owner)
1107{
1108#ifdef ARCH_RELOCATES_KCRCTAB
1109 if (crc_owner == NULL)
1110 return crc - (unsigned long)reloc_start;
1111#endif
1112 return crc;
1113}
1114
1115static int check_version(Elf_Shdr *sechdrs,
1116 unsigned int versindex,
1117 const char *symname,
1118 struct module *mod,
1119 const unsigned long *crc,
1120 const struct module *crc_owner)
1121{
1122 unsigned int i, num_versions;
1123 struct modversion_info *versions;
1124
1125 /* Exporting module didn't supply crcs? OK, we're already tainted. */
1126 if (!crc)
1127 return 1;
1128
1129 /* No versions at all? modprobe --force does this. */
1130 if (versindex == 0)
1131 return try_to_force_load(mod, symname) == 0;
1132
1133 versions = (void *) sechdrs[versindex].sh_addr;
1134 num_versions = sechdrs[versindex].sh_size
1135 / sizeof(struct modversion_info);
1136
1137 for (i = 0; i < num_versions; i++) {
1138 if (strcmp(versions[i].name, symname) != 0)
1139 continue;
1140
1141 if (versions[i].crc == maybe_relocated(*crc, crc_owner))
1142 return 1;
1143 pr_debug("Found checksum %lX vs module %lX\n",
1144 maybe_relocated(*crc, crc_owner), versions[i].crc);
1145 goto bad_version;
1146 }
1147
1148 printk(KERN_WARNING "%s: no symbol version for %s\n",
1149 mod->name, symname);
1150 return 0;
1151
1152bad_version:
1153 printk("%s: disagrees about version of symbol %s\n",
1154 mod->name, symname);
1155 return 0;
1156}
1157
1158static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1159 unsigned int versindex,
1160 struct module *mod)
1161{
1162 const unsigned long *crc;
1163
1164 /* Since this should be found in kernel (which can't be removed),
1165 * no locking is necessary. */
1166 if (!find_symbol(MODULE_SYMBOL_PREFIX "module_layout", NULL,
1167 &crc, true, false))
1168 BUG();
1169 return check_version(sechdrs, versindex, "module_layout", mod, crc,
1170 NULL);
1171}
1172
1173/* First part is kernel version, which we ignore if module has crcs. */
1174static inline int same_magic(const char *amagic, const char *bmagic,
1175 bool has_crcs)
1176{
1177 if (has_crcs) {
1178 amagic += strcspn(amagic, " ");
1179 bmagic += strcspn(bmagic, " ");
1180 }
1181 return strcmp(amagic, bmagic) == 0;
1182}
1183#else
1184static inline int check_version(Elf_Shdr *sechdrs,
1185 unsigned int versindex,
1186 const char *symname,
1187 struct module *mod,
1188 const unsigned long *crc,
1189 const struct module *crc_owner)
1190{
1191 return 1;
1192}
1193
1194static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1195 unsigned int versindex,
1196 struct module *mod)
1197{
1198 return 1;
1199}
1200
1201static inline int same_magic(const char *amagic, const char *bmagic,
1202 bool has_crcs)
1203{
1204 return strcmp(amagic, bmagic) == 0;
1205}
1206#endif /* CONFIG_MODVERSIONS */
1207
1208/* Resolve a symbol for this module. I.e. if we find one, record usage. */
1209static const struct kernel_symbol *resolve_symbol(struct module *mod,
1210 const struct load_info *info,
1211 const char *name,
1212 char ownername[])
1213{
1214 struct module *owner;
1215 const struct kernel_symbol *sym;
1216 const unsigned long *crc;
1217 int err;
1218
1219 mutex_lock(&module_mutex);
1220 sym = find_symbol(name, &owner, &crc,
1221 !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)), true);
1222 if (!sym)
1223 goto unlock;
1224
1225 if (!check_version(info->sechdrs, info->index.vers, name, mod, crc,
1226 owner)) {
1227 sym = ERR_PTR(-EINVAL);
1228 goto getname;
1229 }
1230
1231 err = ref_module(mod, owner);
1232 if (err) {
1233 sym = ERR_PTR(err);
1234 goto getname;
1235 }
1236
1237getname:
1238 /* We must make copy under the lock if we failed to get ref. */
1239 strncpy(ownername, module_name(owner), MODULE_NAME_LEN);
1240unlock:
1241 mutex_unlock(&module_mutex);
1242 return sym;
1243}
1244
1245static const struct kernel_symbol *
1246resolve_symbol_wait(struct module *mod,
1247 const struct load_info *info,
1248 const char *name)
1249{
1250 const struct kernel_symbol *ksym;
1251 char owner[MODULE_NAME_LEN];
1252
1253 if (wait_event_interruptible_timeout(module_wq,
1254 !IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1255 || PTR_ERR(ksym) != -EBUSY,
1256 30 * HZ) <= 0) {
1257 printk(KERN_WARNING "%s: gave up waiting for init of module %s.\n",
1258 mod->name, owner);
1259 }
1260 return ksym;
1261}
1262
1263/*
1264 * /sys/module/foo/sections stuff
1265 * J. Corbet <corbet@lwn.net>
1266 */
1267#ifdef CONFIG_SYSFS
1268
1269#ifdef CONFIG_KALLSYMS
1270static inline bool sect_empty(const Elf_Shdr *sect)
1271{
1272 return !(sect->sh_flags & SHF_ALLOC) || sect->sh_size == 0;
1273}
1274
1275struct module_sect_attr
1276{
1277 struct module_attribute mattr;
1278 char *name;
1279 unsigned long address;
1280};
1281
1282struct module_sect_attrs
1283{
1284 struct attribute_group grp;
1285 unsigned int nsections;
1286 struct module_sect_attr attrs[0];
1287};
1288
1289static ssize_t module_sect_show(struct module_attribute *mattr,
1290 struct module_kobject *mk, char *buf)
1291{
1292 struct module_sect_attr *sattr =
1293 container_of(mattr, struct module_sect_attr, mattr);
1294 return sprintf(buf, "0x%pK\n", (void *)sattr->address);
1295}
1296
1297static void free_sect_attrs(struct module_sect_attrs *sect_attrs)
1298{
1299 unsigned int section;
1300
1301 for (section = 0; section < sect_attrs->nsections; section++)
1302 kfree(sect_attrs->attrs[section].name);
1303 kfree(sect_attrs);
1304}
1305
1306static void add_sect_attrs(struct module *mod, const struct load_info *info)
1307{
1308 unsigned int nloaded = 0, i, size[2];
1309 struct module_sect_attrs *sect_attrs;
1310 struct module_sect_attr *sattr;
1311 struct attribute **gattr;
1312
1313 /* Count loaded sections and allocate structures */
1314 for (i = 0; i < info->hdr->e_shnum; i++)
1315 if (!sect_empty(&info->sechdrs[i]))
1316 nloaded++;
1317 size[0] = ALIGN(sizeof(*sect_attrs)
1318 + nloaded * sizeof(sect_attrs->attrs[0]),
1319 sizeof(sect_attrs->grp.attrs[0]));
1320 size[1] = (nloaded + 1) * sizeof(sect_attrs->grp.attrs[0]);
1321 sect_attrs = kzalloc(size[0] + size[1], GFP_KERNEL);
1322 if (sect_attrs == NULL)
1323 return;
1324
1325 /* Setup section attributes. */
1326 sect_attrs->grp.name = "sections";
1327 sect_attrs->grp.attrs = (void *)sect_attrs + size[0];
1328
1329 sect_attrs->nsections = 0;
1330 sattr = &sect_attrs->attrs[0];
1331 gattr = &sect_attrs->grp.attrs[0];
1332 for (i = 0; i < info->hdr->e_shnum; i++) {
1333 Elf_Shdr *sec = &info->sechdrs[i];
1334 if (sect_empty(sec))
1335 continue;
1336 sattr->address = sec->sh_addr;
1337 sattr->name = kstrdup(info->secstrings + sec->sh_name,
1338 GFP_KERNEL);
1339 if (sattr->name == NULL)
1340 goto out;
1341 sect_attrs->nsections++;
1342 sysfs_attr_init(&sattr->mattr.attr);
1343 sattr->mattr.show = module_sect_show;
1344 sattr->mattr.store = NULL;
1345 sattr->mattr.attr.name = sattr->name;
1346 sattr->mattr.attr.mode = S_IRUGO;
1347 *(gattr++) = &(sattr++)->mattr.attr;
1348 }
1349 *gattr = NULL;
1350
1351 if (sysfs_create_group(&mod->mkobj.kobj, &sect_attrs->grp))
1352 goto out;
1353
1354 mod->sect_attrs = sect_attrs;
1355 return;
1356 out:
1357 free_sect_attrs(sect_attrs);
1358}
1359
1360static void remove_sect_attrs(struct module *mod)
1361{
1362 if (mod->sect_attrs) {
1363 sysfs_remove_group(&mod->mkobj.kobj,
1364 &mod->sect_attrs->grp);
1365 /* We are positive that no one is using any sect attrs
1366 * at this point. Deallocate immediately. */
1367 free_sect_attrs(mod->sect_attrs);
1368 mod->sect_attrs = NULL;
1369 }
1370}
1371
1372/*
1373 * /sys/module/foo/notes/.section.name gives contents of SHT_NOTE sections.
1374 */
1375
1376struct module_notes_attrs {
1377 struct kobject *dir;
1378 unsigned int notes;
1379 struct bin_attribute attrs[0];
1380};
1381
1382static ssize_t module_notes_read(struct file *filp, struct kobject *kobj,
1383 struct bin_attribute *bin_attr,
1384 char *buf, loff_t pos, size_t count)
1385{
1386 /*
1387 * The caller checked the pos and count against our size.
1388 */
1389 memcpy(buf, bin_attr->private + pos, count);
1390 return count;
1391}
1392
1393static void free_notes_attrs(struct module_notes_attrs *notes_attrs,
1394 unsigned int i)
1395{
1396 if (notes_attrs->dir) {
1397 while (i-- > 0)
1398 sysfs_remove_bin_file(notes_attrs->dir,
1399 &notes_attrs->attrs[i]);
1400 kobject_put(notes_attrs->dir);
1401 }
1402 kfree(notes_attrs);
1403}
1404
1405static void add_notes_attrs(struct module *mod, const struct load_info *info)
1406{
1407 unsigned int notes, loaded, i;
1408 struct module_notes_attrs *notes_attrs;
1409 struct bin_attribute *nattr;
1410
1411 /* failed to create section attributes, so can't create notes */
1412 if (!mod->sect_attrs)
1413 return;
1414
1415 /* Count notes sections and allocate structures. */
1416 notes = 0;
1417 for (i = 0; i < info->hdr->e_shnum; i++)
1418 if (!sect_empty(&info->sechdrs[i]) &&
1419 (info->sechdrs[i].sh_type == SHT_NOTE))
1420 ++notes;
1421
1422 if (notes == 0)
1423 return;
1424
1425 notes_attrs = kzalloc(sizeof(*notes_attrs)
1426 + notes * sizeof(notes_attrs->attrs[0]),
1427 GFP_KERNEL);
1428 if (notes_attrs == NULL)
1429 return;
1430
1431 notes_attrs->notes = notes;
1432 nattr = &notes_attrs->attrs[0];
1433 for (loaded = i = 0; i < info->hdr->e_shnum; ++i) {
1434 if (sect_empty(&info->sechdrs[i]))
1435 continue;
1436 if (info->sechdrs[i].sh_type == SHT_NOTE) {
1437 sysfs_bin_attr_init(nattr);
1438 nattr->attr.name = mod->sect_attrs->attrs[loaded].name;
1439 nattr->attr.mode = S_IRUGO;
1440 nattr->size = info->sechdrs[i].sh_size;
1441 nattr->private = (void *) info->sechdrs[i].sh_addr;
1442 nattr->read = module_notes_read;
1443 ++nattr;
1444 }
1445 ++loaded;
1446 }
1447
1448 notes_attrs->dir = kobject_create_and_add("notes", &mod->mkobj.kobj);
1449 if (!notes_attrs->dir)
1450 goto out;
1451
1452 for (i = 0; i < notes; ++i)
1453 if (sysfs_create_bin_file(notes_attrs->dir,
1454 &notes_attrs->attrs[i]))
1455 goto out;
1456
1457 mod->notes_attrs = notes_attrs;
1458 return;
1459
1460 out:
1461 free_notes_attrs(notes_attrs, i);
1462}
1463
1464static void remove_notes_attrs(struct module *mod)
1465{
1466 if (mod->notes_attrs)
1467 free_notes_attrs(mod->notes_attrs, mod->notes_attrs->notes);
1468}
1469
1470#else
1471
1472static inline void add_sect_attrs(struct module *mod,
1473 const struct load_info *info)
1474{
1475}
1476
1477static inline void remove_sect_attrs(struct module *mod)
1478{
1479}
1480
1481static inline void add_notes_attrs(struct module *mod,
1482 const struct load_info *info)
1483{
1484}
1485
1486static inline void remove_notes_attrs(struct module *mod)
1487{
1488}
1489#endif /* CONFIG_KALLSYMS */
1490
1491static void add_usage_links(struct module *mod)
1492{
1493#ifdef CONFIG_MODULE_UNLOAD
1494 struct module_use *use;
1495 int nowarn;
1496
1497 mutex_lock(&module_mutex);
1498 list_for_each_entry(use, &mod->target_list, target_list) {
1499 nowarn = sysfs_create_link(use->target->holders_dir,
1500 &mod->mkobj.kobj, mod->name);
1501 }
1502 mutex_unlock(&module_mutex);
1503#endif
1504}
1505
1506static void del_usage_links(struct module *mod)
1507{
1508#ifdef CONFIG_MODULE_UNLOAD
1509 struct module_use *use;
1510
1511 mutex_lock(&module_mutex);
1512 list_for_each_entry(use, &mod->target_list, target_list)
1513 sysfs_remove_link(use->target->holders_dir, mod->name);
1514 mutex_unlock(&module_mutex);
1515#endif
1516}
1517
1518static int module_add_modinfo_attrs(struct module *mod)
1519{
1520 struct module_attribute *attr;
1521 struct module_attribute *temp_attr;
1522 int error = 0;
1523 int i;
1524
1525 mod->modinfo_attrs = kzalloc((sizeof(struct module_attribute) *
1526 (ARRAY_SIZE(modinfo_attrs) + 1)),
1527 GFP_KERNEL);
1528 if (!mod->modinfo_attrs)
1529 return -ENOMEM;
1530
1531 temp_attr = mod->modinfo_attrs;
1532 for (i = 0; (attr = modinfo_attrs[i]) && !error; i++) {
1533 if (!attr->test ||
1534 (attr->test && attr->test(mod))) {
1535 memcpy(temp_attr, attr, sizeof(*temp_attr));
1536 sysfs_attr_init(&temp_attr->attr);
1537 error = sysfs_create_file(&mod->mkobj.kobj,&temp_attr->attr);
1538 ++temp_attr;
1539 }
1540 }
1541 return error;
1542}
1543
1544static void module_remove_modinfo_attrs(struct module *mod)
1545{
1546 struct module_attribute *attr;
1547 int i;
1548
1549 for (i = 0; (attr = &mod->modinfo_attrs[i]); i++) {
1550 /* pick a field to test for end of list */
1551 if (!attr->attr.name)
1552 break;
1553 sysfs_remove_file(&mod->mkobj.kobj,&attr->attr);
1554 if (attr->free)
1555 attr->free(mod);
1556 }
1557 kfree(mod->modinfo_attrs);
1558}
1559
1560static int mod_sysfs_init(struct module *mod)
1561{
1562 int err;
1563 struct kobject *kobj;
1564
1565 if (!module_sysfs_initialized) {
1566 printk(KERN_ERR "%s: module sysfs not initialized\n",
1567 mod->name);
1568 err = -EINVAL;
1569 goto out;
1570 }
1571
1572 kobj = kset_find_obj(module_kset, mod->name);
1573 if (kobj) {
1574 printk(KERN_ERR "%s: module is already loaded\n", mod->name);
1575 kobject_put(kobj);
1576 err = -EINVAL;
1577 goto out;
1578 }
1579
1580 mod->mkobj.mod = mod;
1581
1582 memset(&mod->mkobj.kobj, 0, sizeof(mod->mkobj.kobj));
1583 mod->mkobj.kobj.kset = module_kset;
1584 err = kobject_init_and_add(&mod->mkobj.kobj, &module_ktype, NULL,
1585 "%s", mod->name);
1586 if (err)
1587 kobject_put(&mod->mkobj.kobj);
1588
1589 /* delay uevent until full sysfs population */
1590out:
1591 return err;
1592}
1593
1594static int mod_sysfs_setup(struct module *mod,
1595 const struct load_info *info,
1596 struct kernel_param *kparam,
1597 unsigned int num_params)
1598{
1599 int err;
1600
1601 err = mod_sysfs_init(mod);
1602 if (err)
1603 goto out;
1604
1605 mod->holders_dir = kobject_create_and_add("holders", &mod->mkobj.kobj);
1606 if (!mod->holders_dir) {
1607 err = -ENOMEM;
1608 goto out_unreg;
1609 }
1610
1611 err = module_param_sysfs_setup(mod, kparam, num_params);
1612 if (err)
1613 goto out_unreg_holders;
1614
1615 err = module_add_modinfo_attrs(mod);
1616 if (err)
1617 goto out_unreg_param;
1618
1619 add_usage_links(mod);
1620 add_sect_attrs(mod, info);
1621 add_notes_attrs(mod, info);
1622
1623 kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
1624 return 0;
1625
1626out_unreg_param:
1627 module_param_sysfs_remove(mod);
1628out_unreg_holders:
1629 kobject_put(mod->holders_dir);
1630out_unreg:
1631 kobject_put(&mod->mkobj.kobj);
1632out:
1633 return err;
1634}
1635
1636static void mod_sysfs_fini(struct module *mod)
1637{
1638 remove_notes_attrs(mod);
1639 remove_sect_attrs(mod);
1640 kobject_put(&mod->mkobj.kobj);
1641}
1642
1643#else /* !CONFIG_SYSFS */
1644
1645static int mod_sysfs_setup(struct module *mod,
1646 const struct load_info *info,
1647 struct kernel_param *kparam,
1648 unsigned int num_params)
1649{
1650 return 0;
1651}
1652
1653static void mod_sysfs_fini(struct module *mod)
1654{
1655}
1656
1657static void module_remove_modinfo_attrs(struct module *mod)
1658{
1659}
1660
1661static void del_usage_links(struct module *mod)
1662{
1663}
1664
1665#endif /* CONFIG_SYSFS */
1666
1667static void mod_sysfs_teardown(struct module *mod)
1668{
1669 del_usage_links(mod);
1670 module_remove_modinfo_attrs(mod);
1671 module_param_sysfs_remove(mod);
1672 kobject_put(mod->mkobj.drivers_dir);
1673 kobject_put(mod->holders_dir);
1674 mod_sysfs_fini(mod);
1675}
1676
1677/*
1678 * unlink the module with the whole machine is stopped with interrupts off
1679 * - this defends against kallsyms not taking locks
1680 */
1681static int __unlink_module(void *_mod)
1682{
1683 struct module *mod = _mod;
1684 list_del(&mod->list);
1685 module_bug_cleanup(mod);
1686 return 0;
1687}
1688
1689#ifdef CONFIG_DEBUG_SET_MODULE_RONX
1690/*
1691 * LKM RO/NX protection: protect module's text/ro-data
1692 * from modification and any data from execution.
1693 */
1694void set_page_attributes(void *start, void *end, int (*set)(unsigned long start, int num_pages))
1695{
1696 unsigned long begin_pfn = PFN_DOWN((unsigned long)start);
1697 unsigned long end_pfn = PFN_DOWN((unsigned long)end);
1698
1699 if (end_pfn > begin_pfn)
1700 set(begin_pfn << PAGE_SHIFT, end_pfn - begin_pfn);
1701}
1702
1703static void set_section_ro_nx(void *base,
1704 unsigned long text_size,
1705 unsigned long ro_size,
1706 unsigned long total_size)
1707{
1708 /* begin and end PFNs of the current subsection */
1709 unsigned long begin_pfn;
1710 unsigned long end_pfn;
1711
1712 /*
1713 * Set RO for module text and RO-data:
1714 * - Always protect first page.
1715 * - Do not protect last partial page.
1716 */
1717 if (ro_size > 0)
1718 set_page_attributes(base, base + ro_size, set_memory_ro);
1719
1720 /*
1721 * Set NX permissions for module data:
1722 * - Do not protect first partial page.
1723 * - Always protect last page.
1724 */
1725 if (total_size > text_size) {
1726 begin_pfn = PFN_UP((unsigned long)base + text_size);
1727 end_pfn = PFN_UP((unsigned long)base + total_size);
1728 if (end_pfn > begin_pfn)
1729 set_memory_nx(begin_pfn << PAGE_SHIFT, end_pfn - begin_pfn);
1730 }
1731}
1732
1733static void unset_module_core_ro_nx(struct module *mod)
1734{
1735 set_page_attributes(mod->module_core + mod->core_text_size,
1736 mod->module_core + mod->core_size,
1737 set_memory_x);
1738 set_page_attributes(mod->module_core,
1739 mod->module_core + mod->core_ro_size,
1740 set_memory_rw);
1741}
1742
1743static void unset_module_init_ro_nx(struct module *mod)
1744{
1745 set_page_attributes(mod->module_init + mod->init_text_size,
1746 mod->module_init + mod->init_size,
1747 set_memory_x);
1748 set_page_attributes(mod->module_init,
1749 mod->module_init + mod->init_ro_size,
1750 set_memory_rw);
1751}
1752
1753/* Iterate through all modules and set each module's text as RW */
1754void set_all_modules_text_rw(void)
1755{
1756 struct module *mod;
1757
1758 mutex_lock(&module_mutex);
1759 list_for_each_entry_rcu(mod, &modules, list) {
1760 if ((mod->module_core) && (mod->core_text_size)) {
1761 set_page_attributes(mod->module_core,
1762 mod->module_core + mod->core_text_size,
1763 set_memory_rw);
1764 }
1765 if ((mod->module_init) && (mod->init_text_size)) {
1766 set_page_attributes(mod->module_init,
1767 mod->module_init + mod->init_text_size,
1768 set_memory_rw);
1769 }
1770 }
1771 mutex_unlock(&module_mutex);
1772}
1773
1774/* Iterate through all modules and set each module's text as RO */
1775void set_all_modules_text_ro(void)
1776{
1777 struct module *mod;
1778
1779 mutex_lock(&module_mutex);
1780 list_for_each_entry_rcu(mod, &modules, list) {
1781 if ((mod->module_core) && (mod->core_text_size)) {
1782 set_page_attributes(mod->module_core,
1783 mod->module_core + mod->core_text_size,
1784 set_memory_ro);
1785 }
1786 if ((mod->module_init) && (mod->init_text_size)) {
1787 set_page_attributes(mod->module_init,
1788 mod->module_init + mod->init_text_size,
1789 set_memory_ro);
1790 }
1791 }
1792 mutex_unlock(&module_mutex);
1793}
1794#else
1795static inline void set_section_ro_nx(void *base, unsigned long text_size, unsigned long ro_size, unsigned long total_size) { }
1796static void unset_module_core_ro_nx(struct module *mod) { }
1797static void unset_module_init_ro_nx(struct module *mod) { }
1798#endif
1799
1800void __weak module_free(struct module *mod, void *module_region)
1801{
1802 vfree(module_region);
1803}
1804
1805void __weak module_arch_cleanup(struct module *mod)
1806{
1807}
1808
1809/* Free a module, remove from lists, etc. */
1810static void free_module(struct module *mod)
1811{
1812 trace_module_free(mod);
1813
1814 /* Delete from various lists */
1815 mutex_lock(&module_mutex);
1816 stop_machine(__unlink_module, mod, NULL);
1817 mutex_unlock(&module_mutex);
1818 mod_sysfs_teardown(mod);
1819
1820 /* Remove dynamic debug info */
1821 ddebug_remove_module(mod->name);
1822
1823 /* Arch-specific cleanup. */
1824 module_arch_cleanup(mod);
1825
1826 /* Module unload stuff */
1827 module_unload_free(mod);
1828
1829 /* Free any allocated parameters. */
1830 destroy_params(mod->kp, mod->num_kp);
1831
1832 /* This may be NULL, but that's OK */
1833 unset_module_init_ro_nx(mod);
1834 module_free(mod, mod->module_init);
1835 kfree(mod->args);
1836 percpu_modfree(mod);
1837
1838 /* Free lock-classes: */
1839 lockdep_free_key_range(mod->module_core, mod->core_size);
1840
1841 /* Finally, free the core (containing the module structure) */
1842 unset_module_core_ro_nx(mod);
1843 module_free(mod, mod->module_core);
1844
1845#ifdef CONFIG_MPU
1846 update_protections(current->mm);
1847#endif
1848}
1849
1850void *__symbol_get(const char *symbol)
1851{
1852 struct module *owner;
1853 const struct kernel_symbol *sym;
1854
1855 preempt_disable();
1856 sym = find_symbol(symbol, &owner, NULL, true, true);
1857 if (sym && strong_try_module_get(owner))
1858 sym = NULL;
1859 preempt_enable();
1860
1861 return sym ? (void *)sym->value : NULL;
1862}
1863EXPORT_SYMBOL_GPL(__symbol_get);
1864
1865/*
1866 * Ensure that an exported symbol [global namespace] does not already exist
1867 * in the kernel or in some other module's exported symbol table.
1868 *
1869 * You must hold the module_mutex.
1870 */
1871static int verify_export_symbols(struct module *mod)
1872{
1873 unsigned int i;
1874 struct module *owner;
1875 const struct kernel_symbol *s;
1876 struct {
1877 const struct kernel_symbol *sym;
1878 unsigned int num;
1879 } arr[] = {
1880 { mod->syms, mod->num_syms },
1881 { mod->gpl_syms, mod->num_gpl_syms },
1882 { mod->gpl_future_syms, mod->num_gpl_future_syms },
1883#ifdef CONFIG_UNUSED_SYMBOLS
1884 { mod->unused_syms, mod->num_unused_syms },
1885 { mod->unused_gpl_syms, mod->num_unused_gpl_syms },
1886#endif
1887 };
1888
1889 for (i = 0; i < ARRAY_SIZE(arr); i++) {
1890 for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
1891 if (find_symbol(s->name, &owner, NULL, true, false)) {
1892 printk(KERN_ERR
1893 "%s: exports duplicate symbol %s"
1894 " (owned by %s)\n",
1895 mod->name, s->name, module_name(owner));
1896 return -ENOEXEC;
1897 }
1898 }
1899 }
1900 return 0;
1901}
1902
1903/* Change all symbols so that st_value encodes the pointer directly. */
1904static int simplify_symbols(struct module *mod, const struct load_info *info)
1905{
1906 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
1907 Elf_Sym *sym = (void *)symsec->sh_addr;
1908 unsigned long secbase;
1909 unsigned int i;
1910 int ret = 0;
1911 const struct kernel_symbol *ksym;
1912
1913 for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
1914 const char *name = info->strtab + sym[i].st_name;
1915
1916 switch (sym[i].st_shndx) {
1917 case SHN_COMMON:
1918 /* We compiled with -fno-common. These are not
1919 supposed to happen. */
1920 pr_debug("Common symbol: %s\n", name);
1921 printk("%s: please compile with -fno-common\n",
1922 mod->name);
1923 ret = -ENOEXEC;
1924 break;
1925
1926 case SHN_ABS:
1927 /* Don't need to do anything */
1928 pr_debug("Absolute symbol: 0x%08lx\n",
1929 (long)sym[i].st_value);
1930 break;
1931
1932 case SHN_UNDEF:
1933 ksym = resolve_symbol_wait(mod, info, name);
1934 /* Ok if resolved. */
1935 if (ksym && !IS_ERR(ksym)) {
1936 sym[i].st_value = ksym->value;
1937 break;
1938 }
1939
1940 /* Ok if weak. */
1941 if (!ksym && ELF_ST_BIND(sym[i].st_info) == STB_WEAK)
1942 break;
1943
1944 printk(KERN_WARNING "%s: Unknown symbol %s (err %li)\n",
1945 mod->name, name, PTR_ERR(ksym));
1946 ret = PTR_ERR(ksym) ?: -ENOENT;
1947 break;
1948
1949 default:
1950 /* Divert to percpu allocation if a percpu var. */
1951 if (sym[i].st_shndx == info->index.pcpu)
1952 secbase = (unsigned long)mod_percpu(mod);
1953 else
1954 secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
1955 sym[i].st_value += secbase;
1956 break;
1957 }
1958 }
1959
1960 return ret;
1961}
1962
1963int __weak apply_relocate(Elf_Shdr *sechdrs,
1964 const char *strtab,
1965 unsigned int symindex,
1966 unsigned int relsec,
1967 struct module *me)
1968{
1969 pr_err("module %s: REL relocation unsupported\n", me->name);
1970 return -ENOEXEC;
1971}
1972
1973int __weak apply_relocate_add(Elf_Shdr *sechdrs,
1974 const char *strtab,
1975 unsigned int symindex,
1976 unsigned int relsec,
1977 struct module *me)
1978{
1979 pr_err("module %s: RELA relocation unsupported\n", me->name);
1980 return -ENOEXEC;
1981}
1982
1983static int apply_relocations(struct module *mod, const struct load_info *info)
1984{
1985 unsigned int i;
1986 int err = 0;
1987
1988 /* Now do relocations. */
1989 for (i = 1; i < info->hdr->e_shnum; i++) {
1990 unsigned int infosec = info->sechdrs[i].sh_info;
1991
1992 /* Not a valid relocation section? */
1993 if (infosec >= info->hdr->e_shnum)
1994 continue;
1995
1996 /* Don't bother with non-allocated sections */
1997 if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
1998 continue;
1999
2000 if (info->sechdrs[i].sh_type == SHT_REL) {
2001 err = apply_relocate(info->sechdrs, info->strtab,
2002 info->index.sym, i, mod);
2003 }
2004 else if (info->sechdrs[i].sh_type == SHT_RELA)
2005 err = apply_relocate_add(info->sechdrs, info->strtab,
2006 info->index.sym, i, mod);
2007 if (err < 0)
2008 break;
2009 }
2010 return err;
2011}
2012
2013/* Additional bytes needed by arch in front of individual sections */
2014unsigned int __weak arch_mod_section_prepend(struct module *mod,
2015 unsigned int section)
2016{
2017 /* default implementation just returns zero */
2018 return 0;
2019}
2020
2021/* Update size with this section: return offset. */
2022static long get_offset(struct module *mod, unsigned int *size,
2023 Elf_Shdr *sechdr, unsigned int section)
2024{
2025 long ret;
2026
2027 *size += arch_mod_section_prepend(mod, section);
2028 //ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
2029 ret = ALIGN(*size, 0x1000);
2030 *size = ret + sechdr->sh_size;
2031 return ret;
2032}
2033
2034/* Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
2035 might -- code, read-only data, read-write data, small data. Tally
2036 sizes, and place the offsets into sh_entsize fields: high bit means it
2037 belongs in init. */
2038static void layout_sections(struct module *mod, struct load_info *info)
2039{
2040 static unsigned long const masks[][2] = {
2041 /* NOTE: all executable code must be the first section
2042 * in this array; otherwise modify the text_size
2043 * finder in the two loops below */
2044 { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
2045 { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
2046 { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
2047 { ARCH_SHF_SMALL | SHF_ALLOC, 0 }
2048 };
2049 unsigned int m, i;
2050
2051 for (i = 0; i < info->hdr->e_shnum; i++)
2052 info->sechdrs[i].sh_entsize = ~0UL;
2053
2054 pr_debug("Core section allocation order:\n");
2055 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2056 for (i = 0; i < info->hdr->e_shnum; ++i) {
2057 Elf_Shdr *s = &info->sechdrs[i];
2058 const char *sname = info->secstrings + s->sh_name;
2059
2060 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2061 || (s->sh_flags & masks[m][1])
2062 || s->sh_entsize != ~0UL
2063 || strstarts(sname, ".init"))
2064 continue;
2065 s->sh_entsize = get_offset(mod, &mod->core_size, s, i);
2066 pr_debug("\t%s\n", sname);
2067 }
2068 switch (m) {
2069 case 0: /* executable */
2070 mod->core_size = debug_align(mod->core_size);
2071 mod->core_text_size = mod->core_size;
2072 break;
2073 case 1: /* RO: text and ro-data */
2074 mod->core_size = debug_align(mod->core_size);
2075 mod->core_ro_size = mod->core_size;
2076 break;
2077 case 3: /* whole core */
2078 mod->core_size = debug_align(mod->core_size);
2079 break;
2080 }
2081 }
2082
2083 pr_debug("Init section allocation order:\n");
2084 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2085 for (i = 0; i < info->hdr->e_shnum; ++i) {
2086 Elf_Shdr *s = &info->sechdrs[i];
2087 const char *sname = info->secstrings + s->sh_name;
2088
2089 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2090 || (s->sh_flags & masks[m][1])
2091 || s->sh_entsize != ~0UL
2092 || !strstarts(sname, ".init"))
2093 continue;
2094 s->sh_entsize = (get_offset(mod, &mod->init_size, s, i)
2095 | INIT_OFFSET_MASK);
2096 pr_debug("\t%s\n", sname);
2097 }
2098 switch (m) {
2099 case 0: /* executable */
2100 mod->init_size = debug_align(mod->init_size);
2101 mod->init_text_size = mod->init_size;
2102 break;
2103 case 1: /* RO: text and ro-data */
2104 mod->init_size = debug_align(mod->init_size);
2105 mod->init_ro_size = mod->init_size;
2106 break;
2107 case 3: /* whole init */
2108 mod->init_size = debug_align(mod->init_size);
2109 break;
2110 }
2111 }
2112}
2113
2114static void set_license(struct module *mod, const char *license)
2115{
2116 if (!license)
2117 license = "unspecified";
2118
2119 if (!license_is_gpl_compatible(license)) {
2120 if (!test_taint(TAINT_PROPRIETARY_MODULE))
2121 printk(KERN_WARNING "%s: module license '%s' taints "
2122 "kernel.\n", mod->name, license);
2123 add_taint_module(mod, TAINT_PROPRIETARY_MODULE);
2124 }
2125}
2126
2127/* Parse tag=value strings from .modinfo section */
2128static char *next_string(char *string, unsigned long *secsize)
2129{
2130 /* Skip non-zero chars */
2131 while (string[0]) {
2132 string++;
2133 if ((*secsize)-- <= 1)
2134 return NULL;
2135 }
2136
2137 /* Skip any zero padding. */
2138 while (!string[0]) {
2139 string++;
2140 if ((*secsize)-- <= 1)
2141 return NULL;
2142 }
2143 return string;
2144}
2145
2146static char *get_modinfo(struct load_info *info, const char *tag)
2147{
2148 char *p;
2149 unsigned int taglen = strlen(tag);
2150 Elf_Shdr *infosec = &info->sechdrs[info->index.info];
2151 unsigned long size = infosec->sh_size;
2152
2153 for (p = (char *)infosec->sh_addr; p; p = next_string(p, &size)) {
2154 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
2155 return p + taglen + 1;
2156 }
2157 return NULL;
2158}
2159
2160static void setup_modinfo(struct module *mod, struct load_info *info)
2161{
2162 struct module_attribute *attr;
2163 int i;
2164
2165 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2166 if (attr->setup)
2167 attr->setup(mod, get_modinfo(info, attr->attr.name));
2168 }
2169}
2170
2171static void free_modinfo(struct module *mod)
2172{
2173 struct module_attribute *attr;
2174 int i;
2175
2176 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2177 if (attr->free)
2178 attr->free(mod);
2179 }
2180}
2181
2182#ifdef CONFIG_KALLSYMS
2183
2184/* lookup symbol in given range of kernel_symbols */
2185static const struct kernel_symbol *lookup_symbol(const char *name,
2186 const struct kernel_symbol *start,
2187 const struct kernel_symbol *stop)
2188{
2189 return bsearch(name, start, stop - start,
2190 sizeof(struct kernel_symbol), cmp_name);
2191}
2192
2193static int is_exported(const char *name, unsigned long value,
2194 const struct module *mod)
2195{
2196 const struct kernel_symbol *ks;
2197 if (!mod)
2198 ks = lookup_symbol(name, __start___ksymtab, __stop___ksymtab);
2199 else
2200 ks = lookup_symbol(name, mod->syms, mod->syms + mod->num_syms);
2201 return ks != NULL && ks->value == value;
2202}
2203
2204/* As per nm */
2205static char elf_type(const Elf_Sym *sym, const struct load_info *info)
2206{
2207 const Elf_Shdr *sechdrs = info->sechdrs;
2208
2209 if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
2210 if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT)
2211 return 'v';
2212 else
2213 return 'w';
2214 }
2215 if (sym->st_shndx == SHN_UNDEF)
2216 return 'U';
2217 if (sym->st_shndx == SHN_ABS)
2218 return 'a';
2219 if (sym->st_shndx >= SHN_LORESERVE)
2220 return '?';
2221 if (sechdrs[sym->st_shndx].sh_flags & SHF_EXECINSTR)
2222 return 't';
2223 if (sechdrs[sym->st_shndx].sh_flags & SHF_ALLOC
2224 && sechdrs[sym->st_shndx].sh_type != SHT_NOBITS) {
2225 if (!(sechdrs[sym->st_shndx].sh_flags & SHF_WRITE))
2226 return 'r';
2227 else if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2228 return 'g';
2229 else
2230 return 'd';
2231 }
2232 if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
2233 if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2234 return 's';
2235 else
2236 return 'b';
2237 }
2238 if (strstarts(info->secstrings + sechdrs[sym->st_shndx].sh_name,
2239 ".debug")) {
2240 return 'n';
2241 }
2242 return '?';
2243}
2244
2245static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
2246 unsigned int shnum)
2247{
2248 const Elf_Shdr *sec;
2249
2250 if (src->st_shndx == SHN_UNDEF
2251 || src->st_shndx >= shnum
2252 || !src->st_name)
2253 return false;
2254
2255 sec = sechdrs + src->st_shndx;
2256 if (!(sec->sh_flags & SHF_ALLOC)
2257#ifndef CONFIG_KALLSYMS_ALL
2258 || !(sec->sh_flags & SHF_EXECINSTR)
2259#endif
2260 || (sec->sh_entsize & INIT_OFFSET_MASK))
2261 return false;
2262
2263 return true;
2264}
2265
2266/*
2267 * We only allocate and copy the strings needed by the parts of symtab
2268 * we keep. This is simple, but has the effect of making multiple
2269 * copies of duplicates. We could be more sophisticated, see
2270 * linux-kernel thread starting with
2271 * <73defb5e4bca04a6431392cc341112b1@localhost>.
2272 */
2273static void layout_symtab(struct module *mod, struct load_info *info)
2274{
2275 Elf_Shdr *symsect = info->sechdrs + info->index.sym;
2276 Elf_Shdr *strsect = info->sechdrs + info->index.str;
2277 const Elf_Sym *src;
2278 unsigned int i, nsrc, ndst, strtab_size;
2279
2280 /* Put symbol section at end of init part of module. */
2281 symsect->sh_flags |= SHF_ALLOC;
2282 symsect->sh_entsize = get_offset(mod, &mod->init_size, symsect,
2283 info->index.sym) | INIT_OFFSET_MASK;
2284 pr_debug("\t%s\n", info->secstrings + symsect->sh_name);
2285
2286 src = (void *)info->hdr + symsect->sh_offset;
2287 nsrc = symsect->sh_size / sizeof(*src);
2288
2289 /* strtab always starts with a nul, so offset 0 is the empty string. */
2290 strtab_size = 1;
2291
2292 /* Compute total space required for the core symbols' strtab. */
2293 for (ndst = i = 0; i < nsrc; i++) {
2294 if (i == 0 ||
2295 is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum)) {
2296 strtab_size += strlen(&info->strtab[src[i].st_name])+1;
2297 ndst++;
2298 }
2299 }
2300
2301 /* Append room for core symbols at end of core part. */
2302 info->symoffs = ALIGN(mod->core_size, symsect->sh_addralign ?: 1);
2303 info->stroffs = mod->core_size = info->symoffs + ndst * sizeof(Elf_Sym);
2304 mod->core_size += strtab_size;
2305
2306 /* Put string table section at end of init part of module. */
2307 strsect->sh_flags |= SHF_ALLOC;
2308 strsect->sh_entsize = get_offset(mod, &mod->init_size, strsect,
2309 info->index.str) | INIT_OFFSET_MASK;
2310 pr_debug("\t%s\n", info->secstrings + strsect->sh_name);
2311}
2312
2313static void add_kallsyms(struct module *mod, const struct load_info *info)
2314{
2315 unsigned int i, ndst;
2316 const Elf_Sym *src;
2317 Elf_Sym *dst;
2318 char *s;
2319 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2320
2321 mod->symtab = (void *)symsec->sh_addr;
2322 mod->num_symtab = symsec->sh_size / sizeof(Elf_Sym);
2323 /* Make sure we get permanent strtab: don't use info->strtab. */
2324 mod->strtab = (void *)info->sechdrs[info->index.str].sh_addr;
2325
2326 /* Set types up while we still have access to sections. */
2327 for (i = 0; i < mod->num_symtab; i++)
2328 mod->symtab[i].st_info = elf_type(&mod->symtab[i], info);
2329
2330 mod->core_symtab = dst = mod->module_core + info->symoffs;
2331 mod->core_strtab = s = mod->module_core + info->stroffs;
2332 src = mod->symtab;
2333 *s++ = 0;
2334 for (ndst = i = 0; i < mod->num_symtab; i++) {
2335 if (i == 0 ||
2336 is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum)) {
2337 dst[ndst] = src[i];
2338 dst[ndst++].st_name = s - mod->core_strtab;
2339 s += strlcpy(s, &mod->strtab[src[i].st_name],
2340 KSYM_NAME_LEN) + 1;
2341 }
2342 }
2343 mod->core_num_syms = ndst;
2344}
2345#else
2346static inline void layout_symtab(struct module *mod, struct load_info *info)
2347{
2348}
2349
2350static void add_kallsyms(struct module *mod, const struct load_info *info)
2351{
2352}
2353#endif /* CONFIG_KALLSYMS */
2354
2355static void dynamic_debug_setup(struct _ddebug *debug, unsigned int num)
2356{
2357 if (!debug)
2358 return;
2359#ifdef CONFIG_DYNAMIC_DEBUG
2360 if (ddebug_add_module(debug, num, debug->modname))
2361 printk(KERN_ERR "dynamic debug error adding module: %s\n",
2362 debug->modname);
2363#endif
2364}
2365
2366static void dynamic_debug_remove(struct _ddebug *debug)
2367{
2368 if (debug)
2369 ddebug_remove_module(debug->modname);
2370}
2371
2372void * __weak module_alloc(unsigned long size)
2373{
2374 return size == 0 ? NULL : vmalloc_exec(size);
2375}
2376
2377static void *module_alloc_update_bounds(unsigned long size)
2378{
2379 void *ret = module_alloc(size);
2380
2381 if (ret) {
2382 mutex_lock(&module_mutex);
2383 /* Update module bounds. */
2384 if ((unsigned long)ret < module_addr_min)
2385 module_addr_min = (unsigned long)ret;
2386 if ((unsigned long)ret + size > module_addr_max)
2387 module_addr_max = (unsigned long)ret + size;
2388 mutex_unlock(&module_mutex);
2389 }
2390 return ret;
2391}
2392
2393#ifdef CONFIG_DEBUG_KMEMLEAK
2394static void kmemleak_load_module(const struct module *mod,
2395 const struct load_info *info)
2396{
2397 unsigned int i;
2398
2399 /* only scan the sections containing data */
2400 kmemleak_scan_area(mod, sizeof(struct module), GFP_KERNEL);
2401
2402 for (i = 1; i < info->hdr->e_shnum; i++) {
2403 const char *name = info->secstrings + info->sechdrs[i].sh_name;
2404 if (!(info->sechdrs[i].sh_flags & SHF_ALLOC))
2405 continue;
2406 if (!strstarts(name, ".data") && !strstarts(name, ".bss"))
2407 continue;
2408
2409 kmemleak_scan_area((void *)info->sechdrs[i].sh_addr,
2410 info->sechdrs[i].sh_size, GFP_KERNEL);
2411 }
2412}
2413#else
2414static inline void kmemleak_load_module(const struct module *mod,
2415 const struct load_info *info)
2416{
2417}
2418#endif
2419
2420/* Sets info->hdr and info->len. */
2421static int copy_and_check(struct load_info *info,
2422 const void __user *umod, unsigned long len,
2423 const char __user *uargs)
2424{
2425 int err;
2426 Elf_Ehdr *hdr;
2427
2428 if (len < sizeof(*hdr))
2429 return -ENOEXEC;
2430
2431 /* Suck in entire file: we'll want most of it. */
2432 if ((hdr = vmalloc(len)) == NULL)
2433 return -ENOMEM;
2434
2435 if (copy_from_user(hdr, umod, len) != 0) {
2436 err = -EFAULT;
2437 goto free_hdr;
2438 }
2439
2440 /* Sanity checks against insmoding binaries or wrong arch,
2441 weird elf version */
2442 if (memcmp(hdr->e_ident, ELFMAG, SELFMAG) != 0
2443 || hdr->e_type != ET_REL
2444 || !elf_check_arch(hdr)
2445 || hdr->e_shentsize != sizeof(Elf_Shdr)) {
2446 err = -ENOEXEC;
2447 goto free_hdr;
2448 }
2449
2450 if (len < hdr->e_shoff + hdr->e_shnum * sizeof(Elf_Shdr)) {
2451 err = -ENOEXEC;
2452 goto free_hdr;
2453 }
2454
2455 info->hdr = hdr;
2456 info->len = len;
2457 return 0;
2458
2459free_hdr:
2460 vfree(hdr);
2461 return err;
2462}
2463
2464static void free_copy(struct load_info *info)
2465{
2466 vfree(info->hdr);
2467}
2468
2469static int rewrite_section_headers(struct load_info *info)
2470{
2471 unsigned int i;
2472
2473 /* This should always be true, but let's be sure. */
2474 info->sechdrs[0].sh_addr = 0;
2475
2476 for (i = 1; i < info->hdr->e_shnum; i++) {
2477 Elf_Shdr *shdr = &info->sechdrs[i];
2478 if (shdr->sh_type != SHT_NOBITS
2479 && info->len < shdr->sh_offset + shdr->sh_size) {
2480 printk(KERN_ERR "Module len %lu truncated\n",
2481 info->len);
2482 return -ENOEXEC;
2483 }
2484
2485 /* Mark all sections sh_addr with their address in the
2486 temporary image. */
2487 shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
2488
2489#ifndef CONFIG_MODULE_UNLOAD
2490 /* Don't load .exit sections */
2491 if (strstarts(info->secstrings+shdr->sh_name, ".exit"))
2492 shdr->sh_flags &= ~(unsigned long)SHF_ALLOC;
2493#endif
2494 }
2495
2496 /* Track but don't keep modinfo and version sections. */
2497 info->index.vers = find_sec(info, "__versions");
2498 info->index.info = find_sec(info, ".modinfo");
2499 info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
2500 info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
2501 return 0;
2502}
2503
2504/*
2505 * Set up our basic convenience variables (pointers to section headers,
2506 * search for module section index etc), and do some basic section
2507 * verification.
2508 *
2509 * Return the temporary module pointer (we'll replace it with the final
2510 * one when we move the module sections around).
2511 */
2512static struct module *setup_load_info(struct load_info *info)
2513{
2514 unsigned int i;
2515 int err;
2516 struct module *mod;
2517
2518 /* Set up the convenience variables */
2519 info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
2520 info->secstrings = (void *)info->hdr
2521 + info->sechdrs[info->hdr->e_shstrndx].sh_offset;
2522
2523 err = rewrite_section_headers(info);
2524 if (err)
2525 return ERR_PTR(err);
2526
2527 /* Find internal symbols and strings. */
2528 for (i = 1; i < info->hdr->e_shnum; i++) {
2529 if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
2530 info->index.sym = i;
2531 info->index.str = info->sechdrs[i].sh_link;
2532 info->strtab = (char *)info->hdr
2533 + info->sechdrs[info->index.str].sh_offset;
2534 break;
2535 }
2536 }
2537
2538 info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
2539 if (!info->index.mod) {
2540 printk(KERN_WARNING "No module found in object\n");
2541 return ERR_PTR(-ENOEXEC);
2542 }
2543 /* This is temporary: point mod into copy of data. */
2544 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2545
2546 if (strcmp(mod->name, "cpko") != 0 && info->index.sym == 0) {
2547 printk(KERN_WARNING "%s: module has no symbols (stripped?)\n",
2548 mod->name);
2549 return ERR_PTR(-ENOEXEC);
2550 }
2551 info->index.pcpu = find_pcpusec(info);
2552
2553 /* Check module struct version now, before we try to use module. */
2554 if (!check_modstruct_version(info->sechdrs, info->index.vers, mod))
2555 return ERR_PTR(-ENOEXEC);
2556
2557 return mod;
2558}
2559
2560static int check_modinfo(struct module *mod, struct load_info *info)
2561{
2562 const char *modmagic = get_modinfo(info, "vermagic");
2563 int err;
2564
2565 /* This is allowed: modprobe --force will invalidate it. */
2566 if (!modmagic) {
2567 err = try_to_force_load(mod, "bad vermagic");
2568 if (err)
2569 return err;
2570 } else if (!same_magic(modmagic, vermagic, info->index.vers)) {
2571 printk(KERN_ERR "%s: version magic '%s' should be '%s'\n",
2572 mod->name, modmagic, vermagic);
2573 return -ENOEXEC;
2574 }
2575
2576 if (!get_modinfo(info, "intree"))
2577 add_taint_module(mod, TAINT_OOT_MODULE);
2578
2579 if (get_modinfo(info, "staging")) {
2580 add_taint_module(mod, TAINT_CRAP);
2581 printk(KERN_WARNING "%s: module is from the staging directory,"
2582 " the quality is unknown, you have been warned.\n",
2583 mod->name);
2584 }
2585
2586 /* Set up license info based on the info section */
2587 set_license(mod, get_modinfo(info, "license"));
2588
2589 return 0;
2590}
2591
2592static void find_module_sections(struct module *mod, struct load_info *info)
2593{
2594 mod->kp = section_objs(info, "__param",
2595 sizeof(*mod->kp), &mod->num_kp);
2596 mod->syms = section_objs(info, "__ksymtab",
2597 sizeof(*mod->syms), &mod->num_syms);
2598 mod->crcs = section_addr(info, "__kcrctab");
2599 mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
2600 sizeof(*mod->gpl_syms),
2601 &mod->num_gpl_syms);
2602 mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
2603 mod->gpl_future_syms = section_objs(info,
2604 "__ksymtab_gpl_future",
2605 sizeof(*mod->gpl_future_syms),
2606 &mod->num_gpl_future_syms);
2607 mod->gpl_future_crcs = section_addr(info, "__kcrctab_gpl_future");
2608
2609#ifdef CONFIG_UNUSED_SYMBOLS
2610 mod->unused_syms = section_objs(info, "__ksymtab_unused",
2611 sizeof(*mod->unused_syms),
2612 &mod->num_unused_syms);
2613 mod->unused_crcs = section_addr(info, "__kcrctab_unused");
2614 mod->unused_gpl_syms = section_objs(info, "__ksymtab_unused_gpl",
2615 sizeof(*mod->unused_gpl_syms),
2616 &mod->num_unused_gpl_syms);
2617 mod->unused_gpl_crcs = section_addr(info, "__kcrctab_unused_gpl");
2618#endif
2619#ifdef CONFIG_CONSTRUCTORS
2620 mod->ctors = section_objs(info, ".ctors",
2621 sizeof(*mod->ctors), &mod->num_ctors);
2622#endif
2623
2624#ifdef CONFIG_TRACEPOINTS
2625 mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
2626 sizeof(*mod->tracepoints_ptrs),
2627 &mod->num_tracepoints);
2628#endif
2629#ifdef HAVE_JUMP_LABEL
2630 mod->jump_entries = section_objs(info, "__jump_table",
2631 sizeof(*mod->jump_entries),
2632 &mod->num_jump_entries);
2633#endif
2634#ifdef CONFIG_EVENT_TRACING
2635 mod->trace_events = section_objs(info, "_ftrace_events",
2636 sizeof(*mod->trace_events),
2637 &mod->num_trace_events);
2638 /*
2639 * This section contains pointers to allocated objects in the trace
2640 * code and not scanning it leads to false positives.
2641 */
2642 kmemleak_scan_area(mod->trace_events, sizeof(*mod->trace_events) *
2643 mod->num_trace_events, GFP_KERNEL);
2644#endif
2645#ifdef CONFIG_TRACING
2646 mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
2647 sizeof(*mod->trace_bprintk_fmt_start),
2648 &mod->num_trace_bprintk_fmt);
2649 /*
2650 * This section contains pointers to allocated objects in the trace
2651 * code and not scanning it leads to false positives.
2652 */
2653 kmemleak_scan_area(mod->trace_bprintk_fmt_start,
2654 sizeof(*mod->trace_bprintk_fmt_start) *
2655 mod->num_trace_bprintk_fmt, GFP_KERNEL);
2656#endif
2657#ifdef CONFIG_FTRACE_MCOUNT_RECORD
2658 /* sechdrs[0].sh_size is always zero */
2659 mod->ftrace_callsites = section_objs(info, "__mcount_loc",
2660 sizeof(*mod->ftrace_callsites),
2661 &mod->num_ftrace_callsites);
2662#endif
2663
2664 mod->extable = section_objs(info, "__ex_table",
2665 sizeof(*mod->extable), &mod->num_exentries);
2666
2667 if (section_addr(info, "__obsparm"))
2668 printk(KERN_WARNING "%s: Ignoring obsolete parameters\n",
2669 mod->name);
2670
2671 info->debug = section_objs(info, "__verbose",
2672 sizeof(*info->debug), &info->num_debug);
2673}
2674
2675static int move_module(struct module *mod, struct load_info *info)
2676{
2677 int i;
2678 void *ptr;
2679
2680 ptr = module_alloc_update_bounds(mod->core_size);
2681
2682 /*
2683 * The pointer to this block is stored in the module structure
2684 * which is inside the block. Just mark it as not being a
2685 * leak.
2686 */
2687 kmemleak_not_leak(ptr);
2688 if (!ptr)
2689 return -ENOMEM;
2690
2691 memset(ptr, 0, mod->core_size);
2692 mod->module_core = ptr;
2693
2694 ptr = module_alloc_update_bounds(mod->init_size);
2695 /*
2696 * The pointer to this block is stored in the module structure
2697 * which is inside the block. This block doesn't need to be
2698 * scanned as it contains data and code that will be freed
2699 * after the module is initialized.
2700 */
2701 kmemleak_ignore(ptr);
2702 if (!ptr && mod->init_size) {
2703 module_free(mod, mod->module_core);
2704 return -ENOMEM;
2705 }
2706 memset(ptr, 0, mod->init_size);
2707 mod->module_init = ptr;
2708
2709 /* Transfer each section which specifies SHF_ALLOC */
2710 pr_debug("final section addresses:\n");
2711 for (i = 0; i < info->hdr->e_shnum; i++) {
2712 void *dest;
2713 Elf_Shdr *shdr = &info->sechdrs[i];
2714
2715 if (!(shdr->sh_flags & SHF_ALLOC))
2716 continue;
2717
2718 if (shdr->sh_entsize & INIT_OFFSET_MASK)
2719 dest = mod->module_init
2720 + (shdr->sh_entsize & ~INIT_OFFSET_MASK);
2721 else
2722 dest = mod->module_core + shdr->sh_entsize;
2723
2724 if (shdr->sh_type != SHT_NOBITS)
2725 memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
2726 /* Update sh_addr to point to copy in image. */
2727 shdr->sh_addr = (unsigned long)dest;
2728 pr_debug("\t0x%lx %s\n",
2729 (long)shdr->sh_addr, info->secstrings + shdr->sh_name);
2730 }
2731
2732 return 0;
2733}
2734
2735static int check_module_license_and_versions(struct module *mod)
2736{
2737 /*
2738 * ndiswrapper is under GPL by itself, but loads proprietary modules.
2739 * Don't use add_taint_module(), as it would prevent ndiswrapper from
2740 * using GPL-only symbols it needs.
2741 */
2742 if (strcmp(mod->name, "ndiswrapper") == 0)
2743 add_taint(TAINT_PROPRIETARY_MODULE);
2744
2745 /* driverloader was caught wrongly pretending to be under GPL */
2746 if (strcmp(mod->name, "driverloader") == 0)
2747 add_taint_module(mod, TAINT_PROPRIETARY_MODULE);
2748
2749 /* lve claims to be GPL but upstream won't provide source */
2750 if (strcmp(mod->name, "lve") == 0)
2751 add_taint_module(mod, TAINT_PROPRIETARY_MODULE);
2752
2753#ifdef CONFIG_MODVERSIONS
2754 if ((mod->num_syms && !mod->crcs)
2755 || (mod->num_gpl_syms && !mod->gpl_crcs)
2756 || (mod->num_gpl_future_syms && !mod->gpl_future_crcs)
2757#ifdef CONFIG_UNUSED_SYMBOLS
2758 || (mod->num_unused_syms && !mod->unused_crcs)
2759 || (mod->num_unused_gpl_syms && !mod->unused_gpl_crcs)
2760#endif
2761 ) {
2762 return try_to_force_load(mod,
2763 "no versions for exported symbols");
2764 }
2765#endif
2766 return 0;
2767}
2768
2769static void flush_module_icache(const struct module *mod)
2770{
2771 mm_segment_t old_fs;
2772
2773 /* flush the icache in correct context */
2774 old_fs = get_fs();
2775 set_fs(KERNEL_DS);
2776
2777 /*
2778 * Flush the instruction cache, since we've played with text.
2779 * Do it before processing of module parameters, so the module
2780 * can provide parameter accessor functions of its own.
2781 */
2782 if (mod->module_init)
2783 flush_icache_range((unsigned long)mod->module_init,
2784 (unsigned long)mod->module_init
2785 + mod->init_size);
2786 flush_icache_range((unsigned long)mod->module_core,
2787 (unsigned long)mod->module_core + mod->core_size);
2788
2789 set_fs(old_fs);
2790}
2791
2792int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
2793 Elf_Shdr *sechdrs,
2794 char *secstrings,
2795 struct module *mod)
2796{
2797 return 0;
2798}
2799
2800static struct module *layout_and_allocate(struct load_info *info)
2801{
2802 /* Module within temporary copy. */
2803 struct module *mod;
2804 Elf_Shdr *pcpusec;
2805 int err;
2806
2807 mod = setup_load_info(info);
2808 if (IS_ERR(mod))
2809 return mod;
2810
2811 err = check_modinfo(mod, info);
2812 if (err)
2813 return ERR_PTR(err);
2814
2815 /* Allow arches to frob section contents and sizes. */
2816 err = module_frob_arch_sections(info->hdr, info->sechdrs,
2817 info->secstrings, mod);
2818 if (err < 0)
2819 goto out;
2820
2821 pcpusec = &info->sechdrs[info->index.pcpu];
2822 if (pcpusec->sh_size) {
2823 /* We have a special allocation for this section. */
2824 err = percpu_modalloc(mod,
2825 pcpusec->sh_size, pcpusec->sh_addralign);
2826 if (err)
2827 goto out;
2828 pcpusec->sh_flags &= ~(unsigned long)SHF_ALLOC;
2829 }
2830
2831 /* Determine total sizes, and put offsets in sh_entsize. For now
2832 this is done generically; there doesn't appear to be any
2833 special cases for the architectures. */
2834 layout_sections(mod, info);
2835 if (strcmp(mod->name, "cpko") != 0)
2836 layout_symtab(mod, info);
2837
2838 /* Allocate and move to the final place */
2839 err = move_module(mod, info);
2840 if (err)
2841 goto free_percpu;
2842
2843 /* Module has been copied to its final place now: return it. */
2844 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2845 kmemleak_load_module(mod, info);
2846 return mod;
2847
2848free_percpu:
2849 percpu_modfree(mod);
2850out:
2851 return ERR_PTR(err);
2852}
2853
2854/* mod is no longer valid after this! */
2855static void module_deallocate(struct module *mod, struct load_info *info)
2856{
2857 percpu_modfree(mod);
2858 module_free(mod, mod->module_init);
2859 module_free(mod, mod->module_core);
2860}
2861
2862int __weak module_finalize(const Elf_Ehdr *hdr,
2863 const Elf_Shdr *sechdrs,
2864 struct module *me)
2865{
2866 return 0;
2867}
2868
2869static int post_relocation(struct module *mod, const struct load_info *info)
2870{
2871 /* Sort exception table now relocations are done. */
2872 sort_extable(mod->extable, mod->extable + mod->num_exentries);
2873
2874 /* Copy relocated percpu area over. */
2875 percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
2876 info->sechdrs[info->index.pcpu].sh_size);
2877
2878 /* Setup kallsyms-specific fields. */
2879 add_kallsyms(mod, info);
2880
2881 /* Arch-specific module finalizing. */
2882 return module_finalize(info->hdr, info->sechdrs, mod);
2883}
2884
2885/* Allocate and load the module: note that size of section 0 is always
2886 zero, and we rely on this for optional sections. */
2887static struct module *load_module(void __user *umod,
2888 unsigned long len,
2889 const char __user *uargs)
2890{
2891 struct load_info info = { NULL, };
2892 struct module *mod;
2893 long err;
2894
2895 pr_debug("load_module: umod=%p, len=%lu, uargs=%p\n",
2896 umod, len, uargs);
2897
2898 /* Copy in the blobs from userspace, check they are vaguely sane. */
2899 err = copy_and_check(&info, umod, len, uargs);
2900 if (err)
2901 return ERR_PTR(err);
2902
2903 /* Figure out module layout, and allocate all the memory. */
2904 mod = layout_and_allocate(&info);
2905 if (IS_ERR(mod)) {
2906 err = PTR_ERR(mod);
2907 goto free_copy;
2908 }
2909 err = module_unload_init(mod);
2910 if (err)
2911 goto free_module;
2912
2913 if (strcmp(mod->name, "cpko") != 0){
2914 /* Now module is in final location, initialize linked lists, etc. */
2915 /* Now we've got everything in the final locations, we can
2916 * find optional sections. */
2917 find_module_sections(mod, &info);
2918
2919 err = check_module_license_and_versions(mod);
2920 if (err)
2921 goto free_unload;
2922
2923 /* Set up MODINFO_ATTR fields */
2924 setup_modinfo(mod, &info);
2925 /* Fix up syms, so that st_value is a pointer to location. */
2926
2927 err = simplify_symbols(mod, &info);
2928 if (err < 0)
2929 goto free_modinfo;
2930
2931 err = apply_relocations(mod, &info);
2932 if (err < 0)
2933 goto free_modinfo;
2934
2935 err = post_relocation(mod, &info);
2936 if (err < 0)
2937 goto free_modinfo;
2938 }
2939 flush_module_icache(mod);
2940
2941 /* Now copy in args */
2942 mod->args = strndup_user(uargs, ~0UL >> 1);
2943 if (IS_ERR(mod->args)) {
2944 err = PTR_ERR(mod->args);
2945 goto free_arch_cleanup;
2946 }
2947
2948 /* Mark state as coming so strong_try_module_get() ignores us. */
2949 mod->state = MODULE_STATE_COMING;
2950
2951 /* Now sew it into the lists so we can get lockdep and oops
2952 * info during argument parsing. No one should access us, since
2953 * strong_try_module_get() will fail.
2954 * lockdep/oops can run asynchronous, so use the RCU list insertion
2955 * function to insert in a way safe to concurrent readers.
2956 * The mutex protects against concurrent writers.
2957 */
2958 mutex_lock(&module_mutex);
2959 if (find_module(mod->name)) {
2960 err = -EEXIST;
2961 goto unlock;
2962 }
2963 if (strcmp(mod->name, "cpko") != 0){
2964 /* This has to be done once we're sure module name is unique. */
2965 dynamic_debug_setup(info.debug, info.num_debug);
2966
2967 /* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
2968 ftrace_module_init(mod);
2969
2970 /* Find duplicate symbols */
2971 err = verify_export_symbols(mod);
2972 if (err < 0)
2973 goto ddebug;
2974 }
2975 module_bug_finalize(info.hdr, info.sechdrs, mod);
2976 list_add_rcu(&mod->list, &modules);
2977 mutex_unlock(&module_mutex);
2978
2979 /* Module is ready to execute: parsing args may do that. */
2980 err = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
2981 -32768, 32767, NULL);
2982 if (err < 0)
2983 goto unlink;
2984 if (strcmp(mod->name, "cpko") != 0){
2985 /* Link in to syfs. */
2986 err = mod_sysfs_setup(mod, &info, mod->kp, mod->num_kp);
2987 if (err < 0)
2988 goto unlink;
2989 }
2990 /* Get rid of temporary copy. */
2991 free_copy(&info);
2992
2993 /* Done! */
2994 trace_module_load(mod);
2995 return mod;
2996
2997 unlink:
2998 mutex_lock(&module_mutex);
2999 /* Unlink carefully: kallsyms could be walking list. */
3000 list_del_rcu(&mod->list);
3001 module_bug_cleanup(mod);
3002
3003 ddebug:
3004 dynamic_debug_remove(info.debug);
3005 unlock:
3006 mutex_unlock(&module_mutex);
3007 synchronize_sched();
3008 kfree(mod->args);
3009 free_arch_cleanup:
3010 module_arch_cleanup(mod);
3011 free_modinfo:
3012 free_modinfo(mod);
3013 free_unload:
3014 module_unload_free(mod);
3015 free_module:
3016 module_deallocate(mod, &info);
3017 free_copy:
3018 free_copy(&info);
3019 return ERR_PTR(err);
3020}
3021
3022/* Call module constructors. */
3023static void do_mod_ctors(struct module *mod)
3024{
3025#ifdef CONFIG_CONSTRUCTORS
3026 unsigned long i;
3027
3028 for (i = 0; i < mod->num_ctors; i++)
3029 mod->ctors[i]();
3030#endif
3031}
3032
3033/* This is where the real work happens */
3034SYSCALL_DEFINE3(init_module, void __user *, umod,
3035 unsigned long, len, const char __user *, uargs)
3036{
3037 struct module *mod;
3038 int ret = 0;
3039
3040 /* Must have permission */
3041 if (!capable(CAP_SYS_MODULE) || modules_disabled)
3042 return -EPERM;
3043
3044 /* Do all the hard work */
3045 mod = load_module(umod, len, uargs);
3046 if (IS_ERR(mod))
3047 return PTR_ERR(mod);
3048
3049 blocking_notifier_call_chain(&module_notify_list,
3050 MODULE_STATE_COMING, mod);
3051
3052 /* Set RO and NX regions for core */
3053 set_section_ro_nx(mod->module_core,
3054 mod->core_text_size,
3055 mod->core_ro_size,
3056 mod->core_size);
3057
3058 /* Set RO and NX regions for init */
3059 set_section_ro_nx(mod->module_init,
3060 mod->init_text_size,
3061 mod->init_ro_size,
3062 mod->init_size);
3063
3064 do_mod_ctors(mod);
3065 /* Start the module */
3066 if (mod->init != NULL)
3067 ret = do_one_initcall(mod->init);
3068 if (ret < 0) {
3069 /* Init routine failed: abort. Try to protect us from
3070 buggy refcounters. */
3071 mod->state = MODULE_STATE_GOING;
3072 synchronize_sched();
3073 module_put(mod);
3074 blocking_notifier_call_chain(&module_notify_list,
3075 MODULE_STATE_GOING, mod);
3076 free_module(mod);
3077 wake_up(&module_wq);
3078 return ret;
3079 }
3080 if (ret > 0) {
3081 printk(KERN_WARNING
3082"%s: '%s'->init suspiciously returned %d, it should follow 0/-E convention\n"
3083"%s: loading module anyway...\n",
3084 __func__, mod->name, ret,
3085 __func__);
3086 dump_stack();
3087 }
3088
3089 /* Now it's a first class citizen! Wake up anyone waiting for it. */
3090 mod->state = MODULE_STATE_LIVE;
3091 wake_up(&module_wq);
3092 blocking_notifier_call_chain(&module_notify_list,
3093 MODULE_STATE_LIVE, mod);
3094
3095 /* We need to finish all async code before the module init sequence is done */
3096 async_synchronize_full();
3097
3098 mutex_lock(&module_mutex);
3099 /* Drop initial reference. */
3100 module_put(mod);
3101 trim_init_extable(mod);
3102#ifdef CONFIG_KALLSYMS
3103 mod->num_symtab = mod->core_num_syms;
3104 mod->symtab = mod->core_symtab;
3105 mod->strtab = mod->core_strtab;
3106#endif
3107 unset_module_init_ro_nx(mod);
3108 module_free(mod, mod->module_init);
3109 mod->module_init = NULL;
3110 mod->init_size = 0;
3111 mod->init_ro_size = 0;
3112 mod->init_text_size = 0;
3113 mutex_unlock(&module_mutex);
3114
3115 return 0;
3116}
3117
3118static inline int within(unsigned long addr, void *start, unsigned long size)
3119{
3120 return ((void *)addr >= start && (void *)addr < start + size);
3121}
3122
3123#ifdef CONFIG_KALLSYMS
3124/*
3125 * This ignores the intensely annoying "mapping symbols" found
3126 * in ARM ELF files: $a, $t and $d.
3127 */
3128static inline int is_arm_mapping_symbol(const char *str)
3129{
3130 return str[0] == '$' && strchr("atd", str[1])
3131 && (str[2] == '\0' || str[2] == '.');
3132}
3133
3134static const char *get_ksymbol(struct module *mod,
3135 unsigned long addr,
3136 unsigned long *size,
3137 unsigned long *offset)
3138{
3139 unsigned int i, best = 0;
3140 unsigned long nextval;
3141
3142 /* At worse, next value is at end of module */
3143 if (within_module_init(addr, mod))
3144 nextval = (unsigned long)mod->module_init+mod->init_text_size;
3145 else
3146 nextval = (unsigned long)mod->module_core+mod->core_text_size;
3147
3148 /* Scan for closest preceding symbol, and next symbol. (ELF
3149 starts real symbols at 1). */
3150 for (i = 1; i < mod->num_symtab; i++) {
3151 if (mod->symtab[i].st_shndx == SHN_UNDEF)
3152 continue;
3153
3154 /* We ignore unnamed symbols: they're uninformative
3155 * and inserted at a whim. */
3156 if (mod->symtab[i].st_value <= addr
3157 && mod->symtab[i].st_value > mod->symtab[best].st_value
3158 && *(mod->strtab + mod->symtab[i].st_name) != '\0'
3159 && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
3160 best = i;
3161 if (mod->symtab[i].st_value > addr
3162 && mod->symtab[i].st_value < nextval
3163 && *(mod->strtab + mod->symtab[i].st_name) != '\0'
3164 && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
3165 nextval = mod->symtab[i].st_value;
3166 }
3167
3168 if (!best)
3169 return NULL;
3170
3171 if (size)
3172 *size = nextval - mod->symtab[best].st_value;
3173 if (offset)
3174 *offset = addr - mod->symtab[best].st_value;
3175 return mod->strtab + mod->symtab[best].st_name;
3176}
3177
3178/* For kallsyms to ask for address resolution. NULL means not found. Careful
3179 * not to lock to avoid deadlock on oopses, simply disable preemption. */
3180const char *module_address_lookup(unsigned long addr,
3181 unsigned long *size,
3182 unsigned long *offset,
3183 char **modname,
3184 char *namebuf)
3185{
3186 struct module *mod;
3187 const char *ret = NULL;
3188
3189 preempt_disable();
3190 list_for_each_entry_rcu(mod, &modules, list) {
3191 if (within_module_init(addr, mod) ||
3192 within_module_core(addr, mod)) {
3193 if (modname)
3194 *modname = mod->name;
3195 ret = get_ksymbol(mod, addr, size, offset);
3196 break;
3197 }
3198 }
3199 /* Make a copy in here where it's safe */
3200 if (ret) {
3201 strncpy(namebuf, ret, KSYM_NAME_LEN - 1);
3202 ret = namebuf;
3203 }
3204 preempt_enable();
3205 return ret;
3206}
3207
3208int lookup_module_symbol_name(unsigned long addr, char *symname)
3209{
3210 struct module *mod;
3211
3212 preempt_disable();
3213 list_for_each_entry_rcu(mod, &modules, list) {
3214 if (within_module_init(addr, mod) ||
3215 within_module_core(addr, mod)) {
3216 const char *sym;
3217
3218 sym = get_ksymbol(mod, addr, NULL, NULL);
3219 if (!sym)
3220 goto out;
3221 strlcpy(symname, sym, KSYM_NAME_LEN);
3222 preempt_enable();
3223 return 0;
3224 }
3225 }
3226out:
3227 preempt_enable();
3228 return -ERANGE;
3229}
3230
3231int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size,
3232 unsigned long *offset, char *modname, char *name)
3233{
3234 struct module *mod;
3235
3236 preempt_disable();
3237 list_for_each_entry_rcu(mod, &modules, list) {
3238 if (within_module_init(addr, mod) ||
3239 within_module_core(addr, mod)) {
3240 const char *sym;
3241
3242 sym = get_ksymbol(mod, addr, size, offset);
3243 if (!sym)
3244 goto out;
3245 if (modname)
3246 strlcpy(modname, mod->name, MODULE_NAME_LEN);
3247 if (name)
3248 strlcpy(name, sym, KSYM_NAME_LEN);
3249 preempt_enable();
3250 return 0;
3251 }
3252 }
3253out:
3254 preempt_enable();
3255 return -ERANGE;
3256}
3257
3258int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
3259 char *name, char *module_name, int *exported)
3260{
3261 struct module *mod;
3262
3263 preempt_disable();
3264 list_for_each_entry_rcu(mod, &modules, list) {
3265 if (symnum < mod->num_symtab) {
3266 *value = mod->symtab[symnum].st_value;
3267 *type = mod->symtab[symnum].st_info;
3268 strlcpy(name, mod->strtab + mod->symtab[symnum].st_name,
3269 KSYM_NAME_LEN);
3270 strlcpy(module_name, mod->name, MODULE_NAME_LEN);
3271 *exported = is_exported(name, *value, mod);
3272 preempt_enable();
3273 return 0;
3274 }
3275 symnum -= mod->num_symtab;
3276 }
3277 preempt_enable();
3278 return -ERANGE;
3279}
3280
3281static unsigned long mod_find_symname(struct module *mod, const char *name)
3282{
3283 unsigned int i;
3284
3285 for (i = 0; i < mod->num_symtab; i++)
3286 if (strcmp(name, mod->strtab+mod->symtab[i].st_name) == 0 &&
3287 mod->symtab[i].st_info != 'U')
3288 return mod->symtab[i].st_value;
3289 return 0;
3290}
3291
3292/* Look for this name: can be of form module:name. */
3293unsigned long module_kallsyms_lookup_name(const char *name)
3294{
3295 struct module *mod;
3296 char *colon;
3297 unsigned long ret = 0;
3298
3299 /* Don't lock: we're in enough trouble already. */
3300 preempt_disable();
3301 if ((colon = strchr(name, ':')) != NULL) {
3302 *colon = '\0';
3303 if ((mod = find_module(name)) != NULL)
3304 ret = mod_find_symname(mod, colon+1);
3305 *colon = ':';
3306 } else {
3307 list_for_each_entry_rcu(mod, &modules, list)
3308 if ((ret = mod_find_symname(mod, name)) != 0)
3309 break;
3310 }
3311 preempt_enable();
3312 return ret;
3313}
3314
3315int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
3316 struct module *, unsigned long),
3317 void *data)
3318{
3319 struct module *mod;
3320 unsigned int i;
3321 int ret;
3322
3323 list_for_each_entry(mod, &modules, list) {
3324 for (i = 0; i < mod->num_symtab; i++) {
3325 ret = fn(data, mod->strtab + mod->symtab[i].st_name,
3326 mod, mod->symtab[i].st_value);
3327 if (ret != 0)
3328 return ret;
3329 }
3330 }
3331 return 0;
3332}
3333#endif /* CONFIG_KALLSYMS */
3334
3335static char *module_flags(struct module *mod, char *buf)
3336{
3337 int bx = 0;
3338
3339 if (mod->taints ||
3340 mod->state == MODULE_STATE_GOING ||
3341 mod->state == MODULE_STATE_COMING) {
3342 buf[bx++] = '(';
3343 bx += module_flags_taint(mod, buf + bx);
3344 /* Show a - for module-is-being-unloaded */
3345 if (mod->state == MODULE_STATE_GOING)
3346 buf[bx++] = '-';
3347 /* Show a + for module-is-being-loaded */
3348 if (mod->state == MODULE_STATE_COMING)
3349 buf[bx++] = '+';
3350 buf[bx++] = ')';
3351 }
3352 buf[bx] = '\0';
3353
3354 return buf;
3355}
3356
3357#ifdef CONFIG_PROC_FS
3358/* Called by the /proc file system to return a list of modules. */
3359static void *m_start(struct seq_file *m, loff_t *pos)
3360{
3361 mutex_lock(&module_mutex);
3362 return seq_list_start(&modules, *pos);
3363}
3364
3365static void *m_next(struct seq_file *m, void *p, loff_t *pos)
3366{
3367 return seq_list_next(p, &modules, pos);
3368}
3369
3370static void m_stop(struct seq_file *m, void *p)
3371{
3372 mutex_unlock(&module_mutex);
3373}
3374
3375static int m_show(struct seq_file *m, void *p)
3376{
3377 struct module *mod = list_entry(p, struct module, list);
3378 char buf[8];
3379
3380 seq_printf(m, "%s %u",
3381 mod->name, mod->init_size + mod->core_size);
3382 print_unload_info(m, mod);
3383
3384 /* Informative for users. */
3385 seq_printf(m, " %s",
3386 mod->state == MODULE_STATE_GOING ? "Unloading":
3387 mod->state == MODULE_STATE_COMING ? "Loading":
3388 "Live");
3389 /* Used by oprofile and other similar tools. */
3390 seq_printf(m, " 0x%pK", mod->module_core);
3391
3392 /* Taints info */
3393 if (mod->taints)
3394 seq_printf(m, " %s", module_flags(mod, buf));
3395
3396 seq_printf(m, "\n");
3397 return 0;
3398}
3399
3400/* Format: modulename size refcount deps address
3401
3402 Where refcount is a number or -, and deps is a comma-separated list
3403 of depends or -.
3404*/
3405static const struct seq_operations modules_op = {
3406 .start = m_start,
3407 .next = m_next,
3408 .stop = m_stop,
3409 .show = m_show
3410};
3411
3412static int modules_open(struct inode *inode, struct file *file)
3413{
3414 return seq_open(file, &modules_op);
3415}
3416
3417static const struct file_operations proc_modules_operations = {
3418 .open = modules_open,
3419 .read = seq_read,
3420 .llseek = seq_lseek,
3421 .release = seq_release,
3422};
3423
3424static int __init proc_modules_init(void)
3425{
3426 proc_create("modules", 0, NULL, &proc_modules_operations);
3427 return 0;
3428}
3429module_init(proc_modules_init);
3430#endif
3431
3432/* Given an address, look for it in the module exception tables. */
3433const struct exception_table_entry *search_module_extables(unsigned long addr)
3434{
3435 const struct exception_table_entry *e = NULL;
3436 struct module *mod;
3437
3438 preempt_disable();
3439 list_for_each_entry_rcu(mod, &modules, list) {
3440 if (mod->num_exentries == 0)
3441 continue;
3442
3443 e = search_extable(mod->extable,
3444 mod->extable + mod->num_exentries - 1,
3445 addr);
3446 if (e)
3447 break;
3448 }
3449 preempt_enable();
3450
3451 /* Now, if we found one, we are running inside it now, hence
3452 we cannot unload the module, hence no refcnt needed. */
3453 return e;
3454}
3455
3456/*
3457 * is_module_address - is this address inside a module?
3458 * @addr: the address to check.
3459 *
3460 * See is_module_text_address() if you simply want to see if the address
3461 * is code (not data).
3462 */
3463bool is_module_address(unsigned long addr)
3464{
3465 bool ret;
3466
3467 preempt_disable();
3468 ret = __module_address(addr) != NULL;
3469 preempt_enable();
3470
3471 return ret;
3472}
3473
3474/*
3475 * __module_address - get the module which contains an address.
3476 * @addr: the address.
3477 *
3478 * Must be called with preempt disabled or module mutex held so that
3479 * module doesn't get freed during this.
3480 */
3481struct module *__module_address(unsigned long addr)
3482{
3483 struct module *mod;
3484
3485 if (addr < module_addr_min || addr > module_addr_max)
3486 return NULL;
3487
3488 list_for_each_entry_rcu(mod, &modules, list)
3489 if (within_module_core(addr, mod)
3490 || within_module_init(addr, mod))
3491 return mod;
3492 return NULL;
3493}
3494EXPORT_SYMBOL_GPL(__module_address);
3495
3496/*
3497 * is_module_text_address - is this address inside module code?
3498 * @addr: the address to check.
3499 *
3500 * See is_module_address() if you simply want to see if the address is
3501 * anywhere in a module. See kernel_text_address() for testing if an
3502 * address corresponds to kernel or module code.
3503 */
3504bool is_module_text_address(unsigned long addr)
3505{
3506 bool ret;
3507
3508 preempt_disable();
3509 ret = __module_text_address(addr) != NULL;
3510 preempt_enable();
3511
3512 return ret;
3513}
3514
3515/*
3516 * __module_text_address - get the module whose code contains an address.
3517 * @addr: the address.
3518 *
3519 * Must be called with preempt disabled or module mutex held so that
3520 * module doesn't get freed during this.
3521 */
3522struct module *__module_text_address(unsigned long addr)
3523{
3524 struct module *mod = __module_address(addr);
3525 if (mod) {
3526 /* Make sure it's within the text section. */
3527 if (!within(addr, mod->module_init, mod->init_text_size)
3528 && !within(addr, mod->module_core, mod->core_text_size))
3529 mod = NULL;
3530 }
3531 return mod;
3532}
3533EXPORT_SYMBOL_GPL(__module_text_address);
3534
3535/* Don't grab lock, we're oopsing. */
3536void print_modules(void)
3537{
3538 struct module *mod;
3539 char buf[8];
3540
3541 printk(KERN_DEFAULT "Modules linked in:");
3542 /* Most callers should already have preempt disabled, but make sure */
3543 preempt_disable();
3544 list_for_each_entry_rcu(mod, &modules, list)
3545 printk(" %s%s", mod->name, module_flags(mod, buf));
3546 preempt_enable();
3547 if (last_unloaded_module[0])
3548 printk(" [last unloaded: %s]", last_unloaded_module);
3549 printk("\n");
3550}
3551
3552#ifdef CONFIG_MODVERSIONS
3553/* Generate the signature for all relevant module structures here.
3554 * If these change, we don't want to try to parse the module. */
3555void module_layout(struct module *mod,
3556 struct modversion_info *ver,
3557 struct kernel_param *kp,
3558 struct kernel_symbol *ks,
3559 struct tracepoint * const *tp)
3560{
3561}
3562EXPORT_SYMBOL(module_layout);
3563#endif