]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blob - kernel/module.c
Merge branches 'pm-qos' and 'pm-devfreq'
[mirror_ubuntu-artful-kernel.git] / kernel / module.c
1 /*
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/extable.h>
21 #include <linux/moduleloader.h>
22 #include <linux/trace_events.h>
23 #include <linux/init.h>
24 #include <linux/kallsyms.h>
25 #include <linux/file.h>
26 #include <linux/fs.h>
27 #include <linux/sysfs.h>
28 #include <linux/kernel.h>
29 #include <linux/slab.h>
30 #include <linux/vmalloc.h>
31 #include <linux/elf.h>
32 #include <linux/proc_fs.h>
33 #include <linux/security.h>
34 #include <linux/seq_file.h>
35 #include <linux/syscalls.h>
36 #include <linux/fcntl.h>
37 #include <linux/rcupdate.h>
38 #include <linux/capability.h>
39 #include <linux/cpu.h>
40 #include <linux/moduleparam.h>
41 #include <linux/errno.h>
42 #include <linux/err.h>
43 #include <linux/vermagic.h>
44 #include <linux/notifier.h>
45 #include <linux/sched.h>
46 #include <linux/device.h>
47 #include <linux/string.h>
48 #include <linux/mutex.h>
49 #include <linux/rculist.h>
50 #include <linux/uaccess.h>
51 #include <asm/cacheflush.h>
52 #include <linux/set_memory.h>
53 #include <asm/mmu_context.h>
54 #include <linux/license.h>
55 #include <asm/sections.h>
56 #include <linux/tracepoint.h>
57 #include <linux/ftrace.h>
58 #include <linux/livepatch.h>
59 #include <linux/async.h>
60 #include <linux/percpu.h>
61 #include <linux/kmemleak.h>
62 #include <linux/jump_label.h>
63 #include <linux/pfn.h>
64 #include <linux/bsearch.h>
65 #include <linux/dynamic_debug.h>
66 #include <linux/audit.h>
67 #include <uapi/linux/module.h>
68 #include "module-internal.h"
69
70 #define CREATE_TRACE_POINTS
71 #include <trace/events/module.h>
72
73 #ifndef ARCH_SHF_SMALL
74 #define ARCH_SHF_SMALL 0
75 #endif
76
77 /*
78 * Modules' sections will be aligned on page boundaries
79 * to ensure complete separation of code and data, but
80 * only when CONFIG_STRICT_MODULE_RWX=y
81 */
82 #ifdef CONFIG_STRICT_MODULE_RWX
83 # define debug_align(X) ALIGN(X, PAGE_SIZE)
84 #else
85 # define debug_align(X) (X)
86 #endif
87
88 /* If this is set, the section belongs in the init part of the module */
89 #define INIT_OFFSET_MASK (1UL << (BITS_PER_LONG-1))
90
91 /*
92 * Mutex protects:
93 * 1) List of modules (also safely readable with preempt_disable),
94 * 2) module_use links,
95 * 3) module_addr_min/module_addr_max.
96 * (delete and add uses RCU list operations). */
97 DEFINE_MUTEX(module_mutex);
98 EXPORT_SYMBOL_GPL(module_mutex);
99 static LIST_HEAD(modules);
100
101 #ifdef CONFIG_MODULES_TREE_LOOKUP
102
103 /*
104 * Use a latched RB-tree for __module_address(); this allows us to use
105 * RCU-sched lookups of the address from any context.
106 *
107 * This is conditional on PERF_EVENTS || TRACING because those can really hit
108 * __module_address() hard by doing a lot of stack unwinding; potentially from
109 * NMI context.
110 */
111
112 static __always_inline unsigned long __mod_tree_val(struct latch_tree_node *n)
113 {
114 struct module_layout *layout = container_of(n, struct module_layout, mtn.node);
115
116 return (unsigned long)layout->base;
117 }
118
119 static __always_inline unsigned long __mod_tree_size(struct latch_tree_node *n)
120 {
121 struct module_layout *layout = container_of(n, struct module_layout, mtn.node);
122
123 return (unsigned long)layout->size;
124 }
125
126 static __always_inline bool
127 mod_tree_less(struct latch_tree_node *a, struct latch_tree_node *b)
128 {
129 return __mod_tree_val(a) < __mod_tree_val(b);
130 }
131
132 static __always_inline int
133 mod_tree_comp(void *key, struct latch_tree_node *n)
134 {
135 unsigned long val = (unsigned long)key;
136 unsigned long start, end;
137
138 start = __mod_tree_val(n);
139 if (val < start)
140 return -1;
141
142 end = start + __mod_tree_size(n);
143 if (val >= end)
144 return 1;
145
146 return 0;
147 }
148
149 static const struct latch_tree_ops mod_tree_ops = {
150 .less = mod_tree_less,
151 .comp = mod_tree_comp,
152 };
153
154 static struct mod_tree_root {
155 struct latch_tree_root root;
156 unsigned long addr_min;
157 unsigned long addr_max;
158 } mod_tree __cacheline_aligned = {
159 .addr_min = -1UL,
160 };
161
162 #define module_addr_min mod_tree.addr_min
163 #define module_addr_max mod_tree.addr_max
164
165 static noinline void __mod_tree_insert(struct mod_tree_node *node)
166 {
167 latch_tree_insert(&node->node, &mod_tree.root, &mod_tree_ops);
168 }
169
170 static void __mod_tree_remove(struct mod_tree_node *node)
171 {
172 latch_tree_erase(&node->node, &mod_tree.root, &mod_tree_ops);
173 }
174
175 /*
176 * These modifications: insert, remove_init and remove; are serialized by the
177 * module_mutex.
178 */
179 static void mod_tree_insert(struct module *mod)
180 {
181 mod->core_layout.mtn.mod = mod;
182 mod->init_layout.mtn.mod = mod;
183
184 __mod_tree_insert(&mod->core_layout.mtn);
185 if (mod->init_layout.size)
186 __mod_tree_insert(&mod->init_layout.mtn);
187 }
188
189 static void mod_tree_remove_init(struct module *mod)
190 {
191 if (mod->init_layout.size)
192 __mod_tree_remove(&mod->init_layout.mtn);
193 }
194
195 static void mod_tree_remove(struct module *mod)
196 {
197 __mod_tree_remove(&mod->core_layout.mtn);
198 mod_tree_remove_init(mod);
199 }
200
201 static struct module *mod_find(unsigned long addr)
202 {
203 struct latch_tree_node *ltn;
204
205 ltn = latch_tree_find((void *)addr, &mod_tree.root, &mod_tree_ops);
206 if (!ltn)
207 return NULL;
208
209 return container_of(ltn, struct mod_tree_node, node)->mod;
210 }
211
212 #else /* MODULES_TREE_LOOKUP */
213
214 static unsigned long module_addr_min = -1UL, module_addr_max = 0;
215
216 static void mod_tree_insert(struct module *mod) { }
217 static void mod_tree_remove_init(struct module *mod) { }
218 static void mod_tree_remove(struct module *mod) { }
219
220 static struct module *mod_find(unsigned long addr)
221 {
222 struct module *mod;
223
224 list_for_each_entry_rcu(mod, &modules, list) {
225 if (within_module(addr, mod))
226 return mod;
227 }
228
229 return NULL;
230 }
231
232 #endif /* MODULES_TREE_LOOKUP */
233
234 /*
235 * Bounds of module text, for speeding up __module_address.
236 * Protected by module_mutex.
237 */
238 static void __mod_update_bounds(void *base, unsigned int size)
239 {
240 unsigned long min = (unsigned long)base;
241 unsigned long max = min + size;
242
243 if (min < module_addr_min)
244 module_addr_min = min;
245 if (max > module_addr_max)
246 module_addr_max = max;
247 }
248
249 static void mod_update_bounds(struct module *mod)
250 {
251 __mod_update_bounds(mod->core_layout.base, mod->core_layout.size);
252 if (mod->init_layout.size)
253 __mod_update_bounds(mod->init_layout.base, mod->init_layout.size);
254 }
255
256 #ifdef CONFIG_KGDB_KDB
257 struct list_head *kdb_modules = &modules; /* kdb needs the list of modules */
258 #endif /* CONFIG_KGDB_KDB */
259
260 static void module_assert_mutex(void)
261 {
262 lockdep_assert_held(&module_mutex);
263 }
264
265 static void module_assert_mutex_or_preempt(void)
266 {
267 #ifdef CONFIG_LOCKDEP
268 if (unlikely(!debug_locks))
269 return;
270
271 WARN_ON_ONCE(!rcu_read_lock_sched_held() &&
272 !lockdep_is_held(&module_mutex));
273 #endif
274 }
275
276 static bool sig_enforce = IS_ENABLED(CONFIG_MODULE_SIG_FORCE);
277 #ifndef CONFIG_MODULE_SIG_FORCE
278 module_param(sig_enforce, bool_enable_only, 0644);
279 #endif /* !CONFIG_MODULE_SIG_FORCE */
280
281 /* Block module loading/unloading? */
282 int modules_disabled = 0;
283 core_param(nomodule, modules_disabled, bint, 0);
284
285 /* Waiting for a module to finish initializing? */
286 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
287
288 static BLOCKING_NOTIFIER_HEAD(module_notify_list);
289
290 int register_module_notifier(struct notifier_block *nb)
291 {
292 return blocking_notifier_chain_register(&module_notify_list, nb);
293 }
294 EXPORT_SYMBOL(register_module_notifier);
295
296 int unregister_module_notifier(struct notifier_block *nb)
297 {
298 return blocking_notifier_chain_unregister(&module_notify_list, nb);
299 }
300 EXPORT_SYMBOL(unregister_module_notifier);
301
302 struct load_info {
303 Elf_Ehdr *hdr;
304 unsigned long len;
305 Elf_Shdr *sechdrs;
306 char *secstrings, *strtab;
307 unsigned long symoffs, stroffs;
308 struct _ddebug *debug;
309 unsigned int num_debug;
310 bool sig_ok;
311 #ifdef CONFIG_KALLSYMS
312 unsigned long mod_kallsyms_init_off;
313 #endif
314 struct {
315 unsigned int sym, str, mod, vers, info, pcpu;
316 } index;
317 };
318
319 /*
320 * We require a truly strong try_module_get(): 0 means success.
321 * Otherwise an error is returned due to ongoing or failed
322 * initialization etc.
323 */
324 static inline int strong_try_module_get(struct module *mod)
325 {
326 BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED);
327 if (mod && mod->state == MODULE_STATE_COMING)
328 return -EBUSY;
329 if (try_module_get(mod))
330 return 0;
331 else
332 return -ENOENT;
333 }
334
335 static inline void add_taint_module(struct module *mod, unsigned flag,
336 enum lockdep_ok lockdep_ok)
337 {
338 add_taint(flag, lockdep_ok);
339 set_bit(flag, &mod->taints);
340 }
341
342 /*
343 * A thread that wants to hold a reference to a module only while it
344 * is running can call this to safely exit. nfsd and lockd use this.
345 */
346 void __noreturn __module_put_and_exit(struct module *mod, long code)
347 {
348 module_put(mod);
349 do_exit(code);
350 }
351 EXPORT_SYMBOL(__module_put_and_exit);
352
353 /* Find a module section: 0 means not found. */
354 static unsigned int find_sec(const struct load_info *info, const char *name)
355 {
356 unsigned int i;
357
358 for (i = 1; i < info->hdr->e_shnum; i++) {
359 Elf_Shdr *shdr = &info->sechdrs[i];
360 /* Alloc bit cleared means "ignore it." */
361 if ((shdr->sh_flags & SHF_ALLOC)
362 && strcmp(info->secstrings + shdr->sh_name, name) == 0)
363 return i;
364 }
365 return 0;
366 }
367
368 /* Find a module section, or NULL. */
369 static void *section_addr(const struct load_info *info, const char *name)
370 {
371 /* Section 0 has sh_addr 0. */
372 return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
373 }
374
375 /* Find a module section, or NULL. Fill in number of "objects" in section. */
376 static void *section_objs(const struct load_info *info,
377 const char *name,
378 size_t object_size,
379 unsigned int *num)
380 {
381 unsigned int sec = find_sec(info, name);
382
383 /* Section 0 has sh_addr 0 and sh_size 0. */
384 *num = info->sechdrs[sec].sh_size / object_size;
385 return (void *)info->sechdrs[sec].sh_addr;
386 }
387
388 /* Provided by the linker */
389 extern const struct kernel_symbol __start___ksymtab[];
390 extern const struct kernel_symbol __stop___ksymtab[];
391 extern const struct kernel_symbol __start___ksymtab_gpl[];
392 extern const struct kernel_symbol __stop___ksymtab_gpl[];
393 extern const struct kernel_symbol __start___ksymtab_gpl_future[];
394 extern const struct kernel_symbol __stop___ksymtab_gpl_future[];
395 extern const s32 __start___kcrctab[];
396 extern const s32 __start___kcrctab_gpl[];
397 extern const s32 __start___kcrctab_gpl_future[];
398 #ifdef CONFIG_UNUSED_SYMBOLS
399 extern const struct kernel_symbol __start___ksymtab_unused[];
400 extern const struct kernel_symbol __stop___ksymtab_unused[];
401 extern const struct kernel_symbol __start___ksymtab_unused_gpl[];
402 extern const struct kernel_symbol __stop___ksymtab_unused_gpl[];
403 extern const s32 __start___kcrctab_unused[];
404 extern const s32 __start___kcrctab_unused_gpl[];
405 #endif
406
407 #ifndef CONFIG_MODVERSIONS
408 #define symversion(base, idx) NULL
409 #else
410 #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
411 #endif
412
413 static bool each_symbol_in_section(const struct symsearch *arr,
414 unsigned int arrsize,
415 struct module *owner,
416 bool (*fn)(const struct symsearch *syms,
417 struct module *owner,
418 void *data),
419 void *data)
420 {
421 unsigned int j;
422
423 for (j = 0; j < arrsize; j++) {
424 if (fn(&arr[j], owner, data))
425 return true;
426 }
427
428 return false;
429 }
430
431 /* Returns true as soon as fn returns true, otherwise false. */
432 bool each_symbol_section(bool (*fn)(const struct symsearch *arr,
433 struct module *owner,
434 void *data),
435 void *data)
436 {
437 struct module *mod;
438 static const struct symsearch arr[] = {
439 { __start___ksymtab, __stop___ksymtab, __start___kcrctab,
440 NOT_GPL_ONLY, false },
441 { __start___ksymtab_gpl, __stop___ksymtab_gpl,
442 __start___kcrctab_gpl,
443 GPL_ONLY, false },
444 { __start___ksymtab_gpl_future, __stop___ksymtab_gpl_future,
445 __start___kcrctab_gpl_future,
446 WILL_BE_GPL_ONLY, false },
447 #ifdef CONFIG_UNUSED_SYMBOLS
448 { __start___ksymtab_unused, __stop___ksymtab_unused,
449 __start___kcrctab_unused,
450 NOT_GPL_ONLY, true },
451 { __start___ksymtab_unused_gpl, __stop___ksymtab_unused_gpl,
452 __start___kcrctab_unused_gpl,
453 GPL_ONLY, true },
454 #endif
455 };
456
457 module_assert_mutex_or_preempt();
458
459 if (each_symbol_in_section(arr, ARRAY_SIZE(arr), NULL, fn, data))
460 return true;
461
462 list_for_each_entry_rcu(mod, &modules, list) {
463 struct symsearch arr[] = {
464 { mod->syms, mod->syms + mod->num_syms, mod->crcs,
465 NOT_GPL_ONLY, false },
466 { mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
467 mod->gpl_crcs,
468 GPL_ONLY, false },
469 { mod->gpl_future_syms,
470 mod->gpl_future_syms + mod->num_gpl_future_syms,
471 mod->gpl_future_crcs,
472 WILL_BE_GPL_ONLY, false },
473 #ifdef CONFIG_UNUSED_SYMBOLS
474 { mod->unused_syms,
475 mod->unused_syms + mod->num_unused_syms,
476 mod->unused_crcs,
477 NOT_GPL_ONLY, true },
478 { mod->unused_gpl_syms,
479 mod->unused_gpl_syms + mod->num_unused_gpl_syms,
480 mod->unused_gpl_crcs,
481 GPL_ONLY, true },
482 #endif
483 };
484
485 if (mod->state == MODULE_STATE_UNFORMED)
486 continue;
487
488 if (each_symbol_in_section(arr, ARRAY_SIZE(arr), mod, fn, data))
489 return true;
490 }
491 return false;
492 }
493 EXPORT_SYMBOL_GPL(each_symbol_section);
494
495 struct find_symbol_arg {
496 /* Input */
497 const char *name;
498 bool gplok;
499 bool warn;
500
501 /* Output */
502 struct module *owner;
503 const s32 *crc;
504 const struct kernel_symbol *sym;
505 };
506
507 static bool check_symbol(const struct symsearch *syms,
508 struct module *owner,
509 unsigned int symnum, void *data)
510 {
511 struct find_symbol_arg *fsa = data;
512
513 if (!fsa->gplok) {
514 if (syms->licence == GPL_ONLY)
515 return false;
516 if (syms->licence == WILL_BE_GPL_ONLY && fsa->warn) {
517 pr_warn("Symbol %s is being used by a non-GPL module, "
518 "which will not be allowed in the future\n",
519 fsa->name);
520 }
521 }
522
523 #ifdef CONFIG_UNUSED_SYMBOLS
524 if (syms->unused && fsa->warn) {
525 pr_warn("Symbol %s is marked as UNUSED, however this module is "
526 "using it.\n", fsa->name);
527 pr_warn("This symbol will go away in the future.\n");
528 pr_warn("Please evaluate if this is the right api to use and "
529 "if it really is, submit a report to the linux kernel "
530 "mailing list together with submitting your code for "
531 "inclusion.\n");
532 }
533 #endif
534
535 fsa->owner = owner;
536 fsa->crc = symversion(syms->crcs, symnum);
537 fsa->sym = &syms->start[symnum];
538 return true;
539 }
540
541 static int cmp_name(const void *va, const void *vb)
542 {
543 const char *a;
544 const struct kernel_symbol *b;
545 a = va; b = vb;
546 return strcmp(a, b->name);
547 }
548
549 static bool find_symbol_in_section(const struct symsearch *syms,
550 struct module *owner,
551 void *data)
552 {
553 struct find_symbol_arg *fsa = data;
554 struct kernel_symbol *sym;
555
556 sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
557 sizeof(struct kernel_symbol), cmp_name);
558
559 if (sym != NULL && check_symbol(syms, owner, sym - syms->start, data))
560 return true;
561
562 return false;
563 }
564
565 /* Find a symbol and return it, along with, (optional) crc and
566 * (optional) module which owns it. Needs preempt disabled or module_mutex. */
567 const struct kernel_symbol *find_symbol(const char *name,
568 struct module **owner,
569 const s32 **crc,
570 bool gplok,
571 bool warn)
572 {
573 struct find_symbol_arg fsa;
574
575 fsa.name = name;
576 fsa.gplok = gplok;
577 fsa.warn = warn;
578
579 if (each_symbol_section(find_symbol_in_section, &fsa)) {
580 if (owner)
581 *owner = fsa.owner;
582 if (crc)
583 *crc = fsa.crc;
584 return fsa.sym;
585 }
586
587 pr_debug("Failed to find symbol %s\n", name);
588 return NULL;
589 }
590 EXPORT_SYMBOL_GPL(find_symbol);
591
592 /*
593 * Search for module by name: must hold module_mutex (or preempt disabled
594 * for read-only access).
595 */
596 static struct module *find_module_all(const char *name, size_t len,
597 bool even_unformed)
598 {
599 struct module *mod;
600
601 module_assert_mutex_or_preempt();
602
603 list_for_each_entry(mod, &modules, list) {
604 if (!even_unformed && mod->state == MODULE_STATE_UNFORMED)
605 continue;
606 if (strlen(mod->name) == len && !memcmp(mod->name, name, len))
607 return mod;
608 }
609 return NULL;
610 }
611
612 struct module *find_module(const char *name)
613 {
614 module_assert_mutex();
615 return find_module_all(name, strlen(name), false);
616 }
617 EXPORT_SYMBOL_GPL(find_module);
618
619 #ifdef CONFIG_SMP
620
621 static inline void __percpu *mod_percpu(struct module *mod)
622 {
623 return mod->percpu;
624 }
625
626 static int percpu_modalloc(struct module *mod, struct load_info *info)
627 {
628 Elf_Shdr *pcpusec = &info->sechdrs[info->index.pcpu];
629 unsigned long align = pcpusec->sh_addralign;
630
631 if (!pcpusec->sh_size)
632 return 0;
633
634 if (align > PAGE_SIZE) {
635 pr_warn("%s: per-cpu alignment %li > %li\n",
636 mod->name, align, PAGE_SIZE);
637 align = PAGE_SIZE;
638 }
639
640 mod->percpu = __alloc_reserved_percpu(pcpusec->sh_size, align);
641 if (!mod->percpu) {
642 pr_warn("%s: Could not allocate %lu bytes percpu data\n",
643 mod->name, (unsigned long)pcpusec->sh_size);
644 return -ENOMEM;
645 }
646 mod->percpu_size = pcpusec->sh_size;
647 return 0;
648 }
649
650 static void percpu_modfree(struct module *mod)
651 {
652 free_percpu(mod->percpu);
653 }
654
655 static unsigned int find_pcpusec(struct load_info *info)
656 {
657 return find_sec(info, ".data..percpu");
658 }
659
660 static void percpu_modcopy(struct module *mod,
661 const void *from, unsigned long size)
662 {
663 int cpu;
664
665 for_each_possible_cpu(cpu)
666 memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
667 }
668
669 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
670 {
671 struct module *mod;
672 unsigned int cpu;
673
674 preempt_disable();
675
676 list_for_each_entry_rcu(mod, &modules, list) {
677 if (mod->state == MODULE_STATE_UNFORMED)
678 continue;
679 if (!mod->percpu_size)
680 continue;
681 for_each_possible_cpu(cpu) {
682 void *start = per_cpu_ptr(mod->percpu, cpu);
683 void *va = (void *)addr;
684
685 if (va >= start && va < start + mod->percpu_size) {
686 if (can_addr) {
687 *can_addr = (unsigned long) (va - start);
688 *can_addr += (unsigned long)
689 per_cpu_ptr(mod->percpu,
690 get_boot_cpu_id());
691 }
692 preempt_enable();
693 return true;
694 }
695 }
696 }
697
698 preempt_enable();
699 return false;
700 }
701
702 /**
703 * is_module_percpu_address - test whether address is from module static percpu
704 * @addr: address to test
705 *
706 * Test whether @addr belongs to module static percpu area.
707 *
708 * RETURNS:
709 * %true if @addr is from module static percpu area
710 */
711 bool is_module_percpu_address(unsigned long addr)
712 {
713 return __is_module_percpu_address(addr, NULL);
714 }
715
716 #else /* ... !CONFIG_SMP */
717
718 static inline void __percpu *mod_percpu(struct module *mod)
719 {
720 return NULL;
721 }
722 static int percpu_modalloc(struct module *mod, struct load_info *info)
723 {
724 /* UP modules shouldn't have this section: ENOMEM isn't quite right */
725 if (info->sechdrs[info->index.pcpu].sh_size != 0)
726 return -ENOMEM;
727 return 0;
728 }
729 static inline void percpu_modfree(struct module *mod)
730 {
731 }
732 static unsigned int find_pcpusec(struct load_info *info)
733 {
734 return 0;
735 }
736 static inline void percpu_modcopy(struct module *mod,
737 const void *from, unsigned long size)
738 {
739 /* pcpusec should be 0, and size of that section should be 0. */
740 BUG_ON(size != 0);
741 }
742 bool is_module_percpu_address(unsigned long addr)
743 {
744 return false;
745 }
746
747 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
748 {
749 return false;
750 }
751
752 #endif /* CONFIG_SMP */
753
754 #define MODINFO_ATTR(field) \
755 static void setup_modinfo_##field(struct module *mod, const char *s) \
756 { \
757 mod->field = kstrdup(s, GFP_KERNEL); \
758 } \
759 static ssize_t show_modinfo_##field(struct module_attribute *mattr, \
760 struct module_kobject *mk, char *buffer) \
761 { \
762 return scnprintf(buffer, PAGE_SIZE, "%s\n", mk->mod->field); \
763 } \
764 static int modinfo_##field##_exists(struct module *mod) \
765 { \
766 return mod->field != NULL; \
767 } \
768 static void free_modinfo_##field(struct module *mod) \
769 { \
770 kfree(mod->field); \
771 mod->field = NULL; \
772 } \
773 static struct module_attribute modinfo_##field = { \
774 .attr = { .name = __stringify(field), .mode = 0444 }, \
775 .show = show_modinfo_##field, \
776 .setup = setup_modinfo_##field, \
777 .test = modinfo_##field##_exists, \
778 .free = free_modinfo_##field, \
779 };
780
781 MODINFO_ATTR(version);
782 MODINFO_ATTR(srcversion);
783
784 static char last_unloaded_module[MODULE_NAME_LEN+1];
785
786 #ifdef CONFIG_MODULE_UNLOAD
787
788 EXPORT_TRACEPOINT_SYMBOL(module_get);
789
790 /* MODULE_REF_BASE is the base reference count by kmodule loader. */
791 #define MODULE_REF_BASE 1
792
793 /* Init the unload section of the module. */
794 static int module_unload_init(struct module *mod)
795 {
796 /*
797 * Initialize reference counter to MODULE_REF_BASE.
798 * refcnt == 0 means module is going.
799 */
800 atomic_set(&mod->refcnt, MODULE_REF_BASE);
801
802 INIT_LIST_HEAD(&mod->source_list);
803 INIT_LIST_HEAD(&mod->target_list);
804
805 /* Hold reference count during initialization. */
806 atomic_inc(&mod->refcnt);
807
808 return 0;
809 }
810
811 /* Does a already use b? */
812 static int already_uses(struct module *a, struct module *b)
813 {
814 struct module_use *use;
815
816 list_for_each_entry(use, &b->source_list, source_list) {
817 if (use->source == a) {
818 pr_debug("%s uses %s!\n", a->name, b->name);
819 return 1;
820 }
821 }
822 pr_debug("%s does not use %s!\n", a->name, b->name);
823 return 0;
824 }
825
826 /*
827 * Module a uses b
828 * - we add 'a' as a "source", 'b' as a "target" of module use
829 * - the module_use is added to the list of 'b' sources (so
830 * 'b' can walk the list to see who sourced them), and of 'a'
831 * targets (so 'a' can see what modules it targets).
832 */
833 static int add_module_usage(struct module *a, struct module *b)
834 {
835 struct module_use *use;
836
837 pr_debug("Allocating new usage for %s.\n", a->name);
838 use = kmalloc(sizeof(*use), GFP_ATOMIC);
839 if (!use) {
840 pr_warn("%s: out of memory loading\n", a->name);
841 return -ENOMEM;
842 }
843
844 use->source = a;
845 use->target = b;
846 list_add(&use->source_list, &b->source_list);
847 list_add(&use->target_list, &a->target_list);
848 return 0;
849 }
850
851 /* Module a uses b: caller needs module_mutex() */
852 int ref_module(struct module *a, struct module *b)
853 {
854 int err;
855
856 if (b == NULL || already_uses(a, b))
857 return 0;
858
859 /* If module isn't available, we fail. */
860 err = strong_try_module_get(b);
861 if (err)
862 return err;
863
864 err = add_module_usage(a, b);
865 if (err) {
866 module_put(b);
867 return err;
868 }
869 return 0;
870 }
871 EXPORT_SYMBOL_GPL(ref_module);
872
873 /* Clear the unload stuff of the module. */
874 static void module_unload_free(struct module *mod)
875 {
876 struct module_use *use, *tmp;
877
878 mutex_lock(&module_mutex);
879 list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
880 struct module *i = use->target;
881 pr_debug("%s unusing %s\n", mod->name, i->name);
882 module_put(i);
883 list_del(&use->source_list);
884 list_del(&use->target_list);
885 kfree(use);
886 }
887 mutex_unlock(&module_mutex);
888 }
889
890 #ifdef CONFIG_MODULE_FORCE_UNLOAD
891 static inline int try_force_unload(unsigned int flags)
892 {
893 int ret = (flags & O_TRUNC);
894 if (ret)
895 add_taint(TAINT_FORCED_RMMOD, LOCKDEP_NOW_UNRELIABLE);
896 return ret;
897 }
898 #else
899 static inline int try_force_unload(unsigned int flags)
900 {
901 return 0;
902 }
903 #endif /* CONFIG_MODULE_FORCE_UNLOAD */
904
905 /* Try to release refcount of module, 0 means success. */
906 static int try_release_module_ref(struct module *mod)
907 {
908 int ret;
909
910 /* Try to decrement refcnt which we set at loading */
911 ret = atomic_sub_return(MODULE_REF_BASE, &mod->refcnt);
912 BUG_ON(ret < 0);
913 if (ret)
914 /* Someone can put this right now, recover with checking */
915 ret = atomic_add_unless(&mod->refcnt, MODULE_REF_BASE, 0);
916
917 return ret;
918 }
919
920 static int try_stop_module(struct module *mod, int flags, int *forced)
921 {
922 /* If it's not unused, quit unless we're forcing. */
923 if (try_release_module_ref(mod) != 0) {
924 *forced = try_force_unload(flags);
925 if (!(*forced))
926 return -EWOULDBLOCK;
927 }
928
929 /* Mark it as dying. */
930 mod->state = MODULE_STATE_GOING;
931
932 return 0;
933 }
934
935 /**
936 * module_refcount - return the refcount or -1 if unloading
937 *
938 * @mod: the module we're checking
939 *
940 * Returns:
941 * -1 if the module is in the process of unloading
942 * otherwise the number of references in the kernel to the module
943 */
944 int module_refcount(struct module *mod)
945 {
946 return atomic_read(&mod->refcnt) - MODULE_REF_BASE;
947 }
948 EXPORT_SYMBOL(module_refcount);
949
950 /* This exists whether we can unload or not */
951 static void free_module(struct module *mod);
952
953 SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
954 unsigned int, flags)
955 {
956 struct module *mod;
957 char name[MODULE_NAME_LEN];
958 int ret, forced = 0;
959
960 if (!capable(CAP_SYS_MODULE) || modules_disabled)
961 return -EPERM;
962
963 if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
964 return -EFAULT;
965 name[MODULE_NAME_LEN-1] = '\0';
966
967 audit_log_kern_module(name);
968
969 if (mutex_lock_interruptible(&module_mutex) != 0)
970 return -EINTR;
971
972 mod = find_module(name);
973 if (!mod) {
974 ret = -ENOENT;
975 goto out;
976 }
977
978 if (!list_empty(&mod->source_list)) {
979 /* Other modules depend on us: get rid of them first. */
980 ret = -EWOULDBLOCK;
981 goto out;
982 }
983
984 /* Doing init or already dying? */
985 if (mod->state != MODULE_STATE_LIVE) {
986 /* FIXME: if (force), slam module count damn the torpedoes */
987 pr_debug("%s already dying\n", mod->name);
988 ret = -EBUSY;
989 goto out;
990 }
991
992 /* If it has an init func, it must have an exit func to unload */
993 if (mod->init && !mod->exit) {
994 forced = try_force_unload(flags);
995 if (!forced) {
996 /* This module can't be removed */
997 ret = -EBUSY;
998 goto out;
999 }
1000 }
1001
1002 /* Stop the machine so refcounts can't move and disable module. */
1003 ret = try_stop_module(mod, flags, &forced);
1004 if (ret != 0)
1005 goto out;
1006
1007 mutex_unlock(&module_mutex);
1008 /* Final destruction now no one is using it. */
1009 if (mod->exit != NULL)
1010 mod->exit();
1011 blocking_notifier_call_chain(&module_notify_list,
1012 MODULE_STATE_GOING, mod);
1013 klp_module_going(mod);
1014 ftrace_release_mod(mod);
1015
1016 async_synchronize_full();
1017
1018 /* Store the name of the last unloaded module for diagnostic purposes */
1019 strlcpy(last_unloaded_module, mod->name, sizeof(last_unloaded_module));
1020
1021 free_module(mod);
1022 return 0;
1023 out:
1024 mutex_unlock(&module_mutex);
1025 return ret;
1026 }
1027
1028 static inline void print_unload_info(struct seq_file *m, struct module *mod)
1029 {
1030 struct module_use *use;
1031 int printed_something = 0;
1032
1033 seq_printf(m, " %i ", module_refcount(mod));
1034
1035 /*
1036 * Always include a trailing , so userspace can differentiate
1037 * between this and the old multi-field proc format.
1038 */
1039 list_for_each_entry(use, &mod->source_list, source_list) {
1040 printed_something = 1;
1041 seq_printf(m, "%s,", use->source->name);
1042 }
1043
1044 if (mod->init != NULL && mod->exit == NULL) {
1045 printed_something = 1;
1046 seq_puts(m, "[permanent],");
1047 }
1048
1049 if (!printed_something)
1050 seq_puts(m, "-");
1051 }
1052
1053 void __symbol_put(const char *symbol)
1054 {
1055 struct module *owner;
1056
1057 preempt_disable();
1058 if (!find_symbol(symbol, &owner, NULL, true, false))
1059 BUG();
1060 module_put(owner);
1061 preempt_enable();
1062 }
1063 EXPORT_SYMBOL(__symbol_put);
1064
1065 /* Note this assumes addr is a function, which it currently always is. */
1066 void symbol_put_addr(void *addr)
1067 {
1068 struct module *modaddr;
1069 unsigned long a = (unsigned long)dereference_function_descriptor(addr);
1070
1071 if (core_kernel_text(a))
1072 return;
1073
1074 /*
1075 * Even though we hold a reference on the module; we still need to
1076 * disable preemption in order to safely traverse the data structure.
1077 */
1078 preempt_disable();
1079 modaddr = __module_text_address(a);
1080 BUG_ON(!modaddr);
1081 module_put(modaddr);
1082 preempt_enable();
1083 }
1084 EXPORT_SYMBOL_GPL(symbol_put_addr);
1085
1086 static ssize_t show_refcnt(struct module_attribute *mattr,
1087 struct module_kobject *mk, char *buffer)
1088 {
1089 return sprintf(buffer, "%i\n", module_refcount(mk->mod));
1090 }
1091
1092 static struct module_attribute modinfo_refcnt =
1093 __ATTR(refcnt, 0444, show_refcnt, NULL);
1094
1095 void __module_get(struct module *module)
1096 {
1097 if (module) {
1098 preempt_disable();
1099 atomic_inc(&module->refcnt);
1100 trace_module_get(module, _RET_IP_);
1101 preempt_enable();
1102 }
1103 }
1104 EXPORT_SYMBOL(__module_get);
1105
1106 bool try_module_get(struct module *module)
1107 {
1108 bool ret = true;
1109
1110 if (module) {
1111 preempt_disable();
1112 /* Note: here, we can fail to get a reference */
1113 if (likely(module_is_live(module) &&
1114 atomic_inc_not_zero(&module->refcnt) != 0))
1115 trace_module_get(module, _RET_IP_);
1116 else
1117 ret = false;
1118
1119 preempt_enable();
1120 }
1121 return ret;
1122 }
1123 EXPORT_SYMBOL(try_module_get);
1124
1125 void module_put(struct module *module)
1126 {
1127 int ret;
1128
1129 if (module) {
1130 preempt_disable();
1131 ret = atomic_dec_if_positive(&module->refcnt);
1132 WARN_ON(ret < 0); /* Failed to put refcount */
1133 trace_module_put(module, _RET_IP_);
1134 preempt_enable();
1135 }
1136 }
1137 EXPORT_SYMBOL(module_put);
1138
1139 #else /* !CONFIG_MODULE_UNLOAD */
1140 static inline void print_unload_info(struct seq_file *m, struct module *mod)
1141 {
1142 /* We don't know the usage count, or what modules are using. */
1143 seq_puts(m, " - -");
1144 }
1145
1146 static inline void module_unload_free(struct module *mod)
1147 {
1148 }
1149
1150 int ref_module(struct module *a, struct module *b)
1151 {
1152 return strong_try_module_get(b);
1153 }
1154 EXPORT_SYMBOL_GPL(ref_module);
1155
1156 static inline int module_unload_init(struct module *mod)
1157 {
1158 return 0;
1159 }
1160 #endif /* CONFIG_MODULE_UNLOAD */
1161
1162 static size_t module_flags_taint(struct module *mod, char *buf)
1163 {
1164 size_t l = 0;
1165 int i;
1166
1167 for (i = 0; i < TAINT_FLAGS_COUNT; i++) {
1168 if (taint_flags[i].module && test_bit(i, &mod->taints))
1169 buf[l++] = taint_flags[i].c_true;
1170 }
1171
1172 return l;
1173 }
1174
1175 static ssize_t show_initstate(struct module_attribute *mattr,
1176 struct module_kobject *mk, char *buffer)
1177 {
1178 const char *state = "unknown";
1179
1180 switch (mk->mod->state) {
1181 case MODULE_STATE_LIVE:
1182 state = "live";
1183 break;
1184 case MODULE_STATE_COMING:
1185 state = "coming";
1186 break;
1187 case MODULE_STATE_GOING:
1188 state = "going";
1189 break;
1190 default:
1191 BUG();
1192 }
1193 return sprintf(buffer, "%s\n", state);
1194 }
1195
1196 static struct module_attribute modinfo_initstate =
1197 __ATTR(initstate, 0444, show_initstate, NULL);
1198
1199 static ssize_t store_uevent(struct module_attribute *mattr,
1200 struct module_kobject *mk,
1201 const char *buffer, size_t count)
1202 {
1203 kobject_synth_uevent(&mk->kobj, buffer, count);
1204 return count;
1205 }
1206
1207 struct module_attribute module_uevent =
1208 __ATTR(uevent, 0200, NULL, store_uevent);
1209
1210 static ssize_t show_coresize(struct module_attribute *mattr,
1211 struct module_kobject *mk, char *buffer)
1212 {
1213 return sprintf(buffer, "%u\n", mk->mod->core_layout.size);
1214 }
1215
1216 static struct module_attribute modinfo_coresize =
1217 __ATTR(coresize, 0444, show_coresize, NULL);
1218
1219 static ssize_t show_initsize(struct module_attribute *mattr,
1220 struct module_kobject *mk, char *buffer)
1221 {
1222 return sprintf(buffer, "%u\n", mk->mod->init_layout.size);
1223 }
1224
1225 static struct module_attribute modinfo_initsize =
1226 __ATTR(initsize, 0444, show_initsize, NULL);
1227
1228 static ssize_t show_taint(struct module_attribute *mattr,
1229 struct module_kobject *mk, char *buffer)
1230 {
1231 size_t l;
1232
1233 l = module_flags_taint(mk->mod, buffer);
1234 buffer[l++] = '\n';
1235 return l;
1236 }
1237
1238 static struct module_attribute modinfo_taint =
1239 __ATTR(taint, 0444, show_taint, NULL);
1240
1241 static struct module_attribute *modinfo_attrs[] = {
1242 &module_uevent,
1243 &modinfo_version,
1244 &modinfo_srcversion,
1245 &modinfo_initstate,
1246 &modinfo_coresize,
1247 &modinfo_initsize,
1248 &modinfo_taint,
1249 #ifdef CONFIG_MODULE_UNLOAD
1250 &modinfo_refcnt,
1251 #endif
1252 NULL,
1253 };
1254
1255 static const char vermagic[] = VERMAGIC_STRING;
1256
1257 static int try_to_force_load(struct module *mod, const char *reason)
1258 {
1259 #ifdef CONFIG_MODULE_FORCE_LOAD
1260 if (!test_taint(TAINT_FORCED_MODULE))
1261 pr_warn("%s: %s: kernel tainted.\n", mod->name, reason);
1262 add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE);
1263 return 0;
1264 #else
1265 return -ENOEXEC;
1266 #endif
1267 }
1268
1269 #ifdef CONFIG_MODVERSIONS
1270
1271 static u32 resolve_rel_crc(const s32 *crc)
1272 {
1273 return *(u32 *)((void *)crc + *crc);
1274 }
1275
1276 static int check_version(Elf_Shdr *sechdrs,
1277 unsigned int versindex,
1278 const char *symname,
1279 struct module *mod,
1280 const s32 *crc)
1281 {
1282 unsigned int i, num_versions;
1283 struct modversion_info *versions;
1284
1285 /* Exporting module didn't supply crcs? OK, we're already tainted. */
1286 if (!crc)
1287 return 1;
1288
1289 /* No versions at all? modprobe --force does this. */
1290 if (versindex == 0)
1291 return try_to_force_load(mod, symname) == 0;
1292
1293 versions = (void *) sechdrs[versindex].sh_addr;
1294 num_versions = sechdrs[versindex].sh_size
1295 / sizeof(struct modversion_info);
1296
1297 for (i = 0; i < num_versions; i++) {
1298 u32 crcval;
1299
1300 if (strcmp(versions[i].name, symname) != 0)
1301 continue;
1302
1303 if (IS_ENABLED(CONFIG_MODULE_REL_CRCS))
1304 crcval = resolve_rel_crc(crc);
1305 else
1306 crcval = *crc;
1307 if (versions[i].crc == crcval)
1308 return 1;
1309 pr_debug("Found checksum %X vs module %lX\n",
1310 crcval, versions[i].crc);
1311 goto bad_version;
1312 }
1313
1314 /* Broken toolchain. Warn once, then let it go.. */
1315 pr_warn_once("%s: no symbol version for %s\n", mod->name, symname);
1316 return 1;
1317
1318 bad_version:
1319 pr_warn("%s: disagrees about version of symbol %s\n",
1320 mod->name, symname);
1321 return 0;
1322 }
1323
1324 static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1325 unsigned int versindex,
1326 struct module *mod)
1327 {
1328 const s32 *crc;
1329
1330 /*
1331 * Since this should be found in kernel (which can't be removed), no
1332 * locking is necessary -- use preempt_disable() to placate lockdep.
1333 */
1334 preempt_disable();
1335 if (!find_symbol(VMLINUX_SYMBOL_STR(module_layout), NULL,
1336 &crc, true, false)) {
1337 preempt_enable();
1338 BUG();
1339 }
1340 preempt_enable();
1341 return check_version(sechdrs, versindex,
1342 VMLINUX_SYMBOL_STR(module_layout), mod, crc);
1343 }
1344
1345 /* First part is kernel version, which we ignore if module has crcs. */
1346 static inline int same_magic(const char *amagic, const char *bmagic,
1347 bool has_crcs)
1348 {
1349 if (has_crcs) {
1350 amagic += strcspn(amagic, " ");
1351 bmagic += strcspn(bmagic, " ");
1352 }
1353 return strcmp(amagic, bmagic) == 0;
1354 }
1355 #else
1356 static inline int check_version(Elf_Shdr *sechdrs,
1357 unsigned int versindex,
1358 const char *symname,
1359 struct module *mod,
1360 const s32 *crc)
1361 {
1362 return 1;
1363 }
1364
1365 static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1366 unsigned int versindex,
1367 struct module *mod)
1368 {
1369 return 1;
1370 }
1371
1372 static inline int same_magic(const char *amagic, const char *bmagic,
1373 bool has_crcs)
1374 {
1375 return strcmp(amagic, bmagic) == 0;
1376 }
1377 #endif /* CONFIG_MODVERSIONS */
1378
1379 /* Resolve a symbol for this module. I.e. if we find one, record usage. */
1380 static const struct kernel_symbol *resolve_symbol(struct module *mod,
1381 const struct load_info *info,
1382 const char *name,
1383 char ownername[])
1384 {
1385 struct module *owner;
1386 const struct kernel_symbol *sym;
1387 const s32 *crc;
1388 int err;
1389
1390 /*
1391 * The module_mutex should not be a heavily contended lock;
1392 * if we get the occasional sleep here, we'll go an extra iteration
1393 * in the wait_event_interruptible(), which is harmless.
1394 */
1395 sched_annotate_sleep();
1396 mutex_lock(&module_mutex);
1397 sym = find_symbol(name, &owner, &crc,
1398 !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)), true);
1399 if (!sym)
1400 goto unlock;
1401
1402 if (!check_version(info->sechdrs, info->index.vers, name, mod, crc)) {
1403 sym = ERR_PTR(-EINVAL);
1404 goto getname;
1405 }
1406
1407 err = ref_module(mod, owner);
1408 if (err) {
1409 sym = ERR_PTR(err);
1410 goto getname;
1411 }
1412
1413 getname:
1414 /* We must make copy under the lock if we failed to get ref. */
1415 strncpy(ownername, module_name(owner), MODULE_NAME_LEN);
1416 unlock:
1417 mutex_unlock(&module_mutex);
1418 return sym;
1419 }
1420
1421 static const struct kernel_symbol *
1422 resolve_symbol_wait(struct module *mod,
1423 const struct load_info *info,
1424 const char *name)
1425 {
1426 const struct kernel_symbol *ksym;
1427 char owner[MODULE_NAME_LEN];
1428
1429 if (wait_event_interruptible_timeout(module_wq,
1430 !IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1431 || PTR_ERR(ksym) != -EBUSY,
1432 30 * HZ) <= 0) {
1433 pr_warn("%s: gave up waiting for init of module %s.\n",
1434 mod->name, owner);
1435 }
1436 return ksym;
1437 }
1438
1439 /*
1440 * /sys/module/foo/sections stuff
1441 * J. Corbet <corbet@lwn.net>
1442 */
1443 #ifdef CONFIG_SYSFS
1444
1445 #ifdef CONFIG_KALLSYMS
1446 static inline bool sect_empty(const Elf_Shdr *sect)
1447 {
1448 return !(sect->sh_flags & SHF_ALLOC) || sect->sh_size == 0;
1449 }
1450
1451 struct module_sect_attr {
1452 struct module_attribute mattr;
1453 char *name;
1454 unsigned long address;
1455 };
1456
1457 struct module_sect_attrs {
1458 struct attribute_group grp;
1459 unsigned int nsections;
1460 struct module_sect_attr attrs[0];
1461 };
1462
1463 static ssize_t module_sect_show(struct module_attribute *mattr,
1464 struct module_kobject *mk, char *buf)
1465 {
1466 struct module_sect_attr *sattr =
1467 container_of(mattr, struct module_sect_attr, mattr);
1468 return sprintf(buf, "0x%pK\n", (void *)sattr->address);
1469 }
1470
1471 static void free_sect_attrs(struct module_sect_attrs *sect_attrs)
1472 {
1473 unsigned int section;
1474
1475 for (section = 0; section < sect_attrs->nsections; section++)
1476 kfree(sect_attrs->attrs[section].name);
1477 kfree(sect_attrs);
1478 }
1479
1480 static void add_sect_attrs(struct module *mod, const struct load_info *info)
1481 {
1482 unsigned int nloaded = 0, i, size[2];
1483 struct module_sect_attrs *sect_attrs;
1484 struct module_sect_attr *sattr;
1485 struct attribute **gattr;
1486
1487 /* Count loaded sections and allocate structures */
1488 for (i = 0; i < info->hdr->e_shnum; i++)
1489 if (!sect_empty(&info->sechdrs[i]))
1490 nloaded++;
1491 size[0] = ALIGN(sizeof(*sect_attrs)
1492 + nloaded * sizeof(sect_attrs->attrs[0]),
1493 sizeof(sect_attrs->grp.attrs[0]));
1494 size[1] = (nloaded + 1) * sizeof(sect_attrs->grp.attrs[0]);
1495 sect_attrs = kzalloc(size[0] + size[1], GFP_KERNEL);
1496 if (sect_attrs == NULL)
1497 return;
1498
1499 /* Setup section attributes. */
1500 sect_attrs->grp.name = "sections";
1501 sect_attrs->grp.attrs = (void *)sect_attrs + size[0];
1502
1503 sect_attrs->nsections = 0;
1504 sattr = &sect_attrs->attrs[0];
1505 gattr = &sect_attrs->grp.attrs[0];
1506 for (i = 0; i < info->hdr->e_shnum; i++) {
1507 Elf_Shdr *sec = &info->sechdrs[i];
1508 if (sect_empty(sec))
1509 continue;
1510 sattr->address = sec->sh_addr;
1511 sattr->name = kstrdup(info->secstrings + sec->sh_name,
1512 GFP_KERNEL);
1513 if (sattr->name == NULL)
1514 goto out;
1515 sect_attrs->nsections++;
1516 sysfs_attr_init(&sattr->mattr.attr);
1517 sattr->mattr.show = module_sect_show;
1518 sattr->mattr.store = NULL;
1519 sattr->mattr.attr.name = sattr->name;
1520 sattr->mattr.attr.mode = S_IRUGO;
1521 *(gattr++) = &(sattr++)->mattr.attr;
1522 }
1523 *gattr = NULL;
1524
1525 if (sysfs_create_group(&mod->mkobj.kobj, &sect_attrs->grp))
1526 goto out;
1527
1528 mod->sect_attrs = sect_attrs;
1529 return;
1530 out:
1531 free_sect_attrs(sect_attrs);
1532 }
1533
1534 static void remove_sect_attrs(struct module *mod)
1535 {
1536 if (mod->sect_attrs) {
1537 sysfs_remove_group(&mod->mkobj.kobj,
1538 &mod->sect_attrs->grp);
1539 /* We are positive that no one is using any sect attrs
1540 * at this point. Deallocate immediately. */
1541 free_sect_attrs(mod->sect_attrs);
1542 mod->sect_attrs = NULL;
1543 }
1544 }
1545
1546 /*
1547 * /sys/module/foo/notes/.section.name gives contents of SHT_NOTE sections.
1548 */
1549
1550 struct module_notes_attrs {
1551 struct kobject *dir;
1552 unsigned int notes;
1553 struct bin_attribute attrs[0];
1554 };
1555
1556 static ssize_t module_notes_read(struct file *filp, struct kobject *kobj,
1557 struct bin_attribute *bin_attr,
1558 char *buf, loff_t pos, size_t count)
1559 {
1560 /*
1561 * The caller checked the pos and count against our size.
1562 */
1563 memcpy(buf, bin_attr->private + pos, count);
1564 return count;
1565 }
1566
1567 static void free_notes_attrs(struct module_notes_attrs *notes_attrs,
1568 unsigned int i)
1569 {
1570 if (notes_attrs->dir) {
1571 while (i-- > 0)
1572 sysfs_remove_bin_file(notes_attrs->dir,
1573 &notes_attrs->attrs[i]);
1574 kobject_put(notes_attrs->dir);
1575 }
1576 kfree(notes_attrs);
1577 }
1578
1579 static void add_notes_attrs(struct module *mod, const struct load_info *info)
1580 {
1581 unsigned int notes, loaded, i;
1582 struct module_notes_attrs *notes_attrs;
1583 struct bin_attribute *nattr;
1584
1585 /* failed to create section attributes, so can't create notes */
1586 if (!mod->sect_attrs)
1587 return;
1588
1589 /* Count notes sections and allocate structures. */
1590 notes = 0;
1591 for (i = 0; i < info->hdr->e_shnum; i++)
1592 if (!sect_empty(&info->sechdrs[i]) &&
1593 (info->sechdrs[i].sh_type == SHT_NOTE))
1594 ++notes;
1595
1596 if (notes == 0)
1597 return;
1598
1599 notes_attrs = kzalloc(sizeof(*notes_attrs)
1600 + notes * sizeof(notes_attrs->attrs[0]),
1601 GFP_KERNEL);
1602 if (notes_attrs == NULL)
1603 return;
1604
1605 notes_attrs->notes = notes;
1606 nattr = &notes_attrs->attrs[0];
1607 for (loaded = i = 0; i < info->hdr->e_shnum; ++i) {
1608 if (sect_empty(&info->sechdrs[i]))
1609 continue;
1610 if (info->sechdrs[i].sh_type == SHT_NOTE) {
1611 sysfs_bin_attr_init(nattr);
1612 nattr->attr.name = mod->sect_attrs->attrs[loaded].name;
1613 nattr->attr.mode = S_IRUGO;
1614 nattr->size = info->sechdrs[i].sh_size;
1615 nattr->private = (void *) info->sechdrs[i].sh_addr;
1616 nattr->read = module_notes_read;
1617 ++nattr;
1618 }
1619 ++loaded;
1620 }
1621
1622 notes_attrs->dir = kobject_create_and_add("notes", &mod->mkobj.kobj);
1623 if (!notes_attrs->dir)
1624 goto out;
1625
1626 for (i = 0; i < notes; ++i)
1627 if (sysfs_create_bin_file(notes_attrs->dir,
1628 &notes_attrs->attrs[i]))
1629 goto out;
1630
1631 mod->notes_attrs = notes_attrs;
1632 return;
1633
1634 out:
1635 free_notes_attrs(notes_attrs, i);
1636 }
1637
1638 static void remove_notes_attrs(struct module *mod)
1639 {
1640 if (mod->notes_attrs)
1641 free_notes_attrs(mod->notes_attrs, mod->notes_attrs->notes);
1642 }
1643
1644 #else
1645
1646 static inline void add_sect_attrs(struct module *mod,
1647 const struct load_info *info)
1648 {
1649 }
1650
1651 static inline void remove_sect_attrs(struct module *mod)
1652 {
1653 }
1654
1655 static inline void add_notes_attrs(struct module *mod,
1656 const struct load_info *info)
1657 {
1658 }
1659
1660 static inline void remove_notes_attrs(struct module *mod)
1661 {
1662 }
1663 #endif /* CONFIG_KALLSYMS */
1664
1665 static void add_usage_links(struct module *mod)
1666 {
1667 #ifdef CONFIG_MODULE_UNLOAD
1668 struct module_use *use;
1669 int nowarn;
1670
1671 mutex_lock(&module_mutex);
1672 list_for_each_entry(use, &mod->target_list, target_list) {
1673 nowarn = sysfs_create_link(use->target->holders_dir,
1674 &mod->mkobj.kobj, mod->name);
1675 }
1676 mutex_unlock(&module_mutex);
1677 #endif
1678 }
1679
1680 static void del_usage_links(struct module *mod)
1681 {
1682 #ifdef CONFIG_MODULE_UNLOAD
1683 struct module_use *use;
1684
1685 mutex_lock(&module_mutex);
1686 list_for_each_entry(use, &mod->target_list, target_list)
1687 sysfs_remove_link(use->target->holders_dir, mod->name);
1688 mutex_unlock(&module_mutex);
1689 #endif
1690 }
1691
1692 static int module_add_modinfo_attrs(struct module *mod)
1693 {
1694 struct module_attribute *attr;
1695 struct module_attribute *temp_attr;
1696 int error = 0;
1697 int i;
1698
1699 mod->modinfo_attrs = kzalloc((sizeof(struct module_attribute) *
1700 (ARRAY_SIZE(modinfo_attrs) + 1)),
1701 GFP_KERNEL);
1702 if (!mod->modinfo_attrs)
1703 return -ENOMEM;
1704
1705 temp_attr = mod->modinfo_attrs;
1706 for (i = 0; (attr = modinfo_attrs[i]) && !error; i++) {
1707 if (!attr->test || attr->test(mod)) {
1708 memcpy(temp_attr, attr, sizeof(*temp_attr));
1709 sysfs_attr_init(&temp_attr->attr);
1710 error = sysfs_create_file(&mod->mkobj.kobj,
1711 &temp_attr->attr);
1712 ++temp_attr;
1713 }
1714 }
1715 return error;
1716 }
1717
1718 static void module_remove_modinfo_attrs(struct module *mod)
1719 {
1720 struct module_attribute *attr;
1721 int i;
1722
1723 for (i = 0; (attr = &mod->modinfo_attrs[i]); i++) {
1724 /* pick a field to test for end of list */
1725 if (!attr->attr.name)
1726 break;
1727 sysfs_remove_file(&mod->mkobj.kobj, &attr->attr);
1728 if (attr->free)
1729 attr->free(mod);
1730 }
1731 kfree(mod->modinfo_attrs);
1732 }
1733
1734 static void mod_kobject_put(struct module *mod)
1735 {
1736 DECLARE_COMPLETION_ONSTACK(c);
1737 mod->mkobj.kobj_completion = &c;
1738 kobject_put(&mod->mkobj.kobj);
1739 wait_for_completion(&c);
1740 }
1741
1742 static int mod_sysfs_init(struct module *mod)
1743 {
1744 int err;
1745 struct kobject *kobj;
1746
1747 if (!module_sysfs_initialized) {
1748 pr_err("%s: module sysfs not initialized\n", mod->name);
1749 err = -EINVAL;
1750 goto out;
1751 }
1752
1753 kobj = kset_find_obj(module_kset, mod->name);
1754 if (kobj) {
1755 pr_err("%s: module is already loaded\n", mod->name);
1756 kobject_put(kobj);
1757 err = -EINVAL;
1758 goto out;
1759 }
1760
1761 mod->mkobj.mod = mod;
1762
1763 memset(&mod->mkobj.kobj, 0, sizeof(mod->mkobj.kobj));
1764 mod->mkobj.kobj.kset = module_kset;
1765 err = kobject_init_and_add(&mod->mkobj.kobj, &module_ktype, NULL,
1766 "%s", mod->name);
1767 if (err)
1768 mod_kobject_put(mod);
1769
1770 /* delay uevent until full sysfs population */
1771 out:
1772 return err;
1773 }
1774
1775 static int mod_sysfs_setup(struct module *mod,
1776 const struct load_info *info,
1777 struct kernel_param *kparam,
1778 unsigned int num_params)
1779 {
1780 int err;
1781
1782 err = mod_sysfs_init(mod);
1783 if (err)
1784 goto out;
1785
1786 mod->holders_dir = kobject_create_and_add("holders", &mod->mkobj.kobj);
1787 if (!mod->holders_dir) {
1788 err = -ENOMEM;
1789 goto out_unreg;
1790 }
1791
1792 err = module_param_sysfs_setup(mod, kparam, num_params);
1793 if (err)
1794 goto out_unreg_holders;
1795
1796 err = module_add_modinfo_attrs(mod);
1797 if (err)
1798 goto out_unreg_param;
1799
1800 add_usage_links(mod);
1801 add_sect_attrs(mod, info);
1802 add_notes_attrs(mod, info);
1803
1804 kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
1805 return 0;
1806
1807 out_unreg_param:
1808 module_param_sysfs_remove(mod);
1809 out_unreg_holders:
1810 kobject_put(mod->holders_dir);
1811 out_unreg:
1812 mod_kobject_put(mod);
1813 out:
1814 return err;
1815 }
1816
1817 static void mod_sysfs_fini(struct module *mod)
1818 {
1819 remove_notes_attrs(mod);
1820 remove_sect_attrs(mod);
1821 mod_kobject_put(mod);
1822 }
1823
1824 static void init_param_lock(struct module *mod)
1825 {
1826 mutex_init(&mod->param_lock);
1827 }
1828 #else /* !CONFIG_SYSFS */
1829
1830 static int mod_sysfs_setup(struct module *mod,
1831 const struct load_info *info,
1832 struct kernel_param *kparam,
1833 unsigned int num_params)
1834 {
1835 return 0;
1836 }
1837
1838 static void mod_sysfs_fini(struct module *mod)
1839 {
1840 }
1841
1842 static void module_remove_modinfo_attrs(struct module *mod)
1843 {
1844 }
1845
1846 static void del_usage_links(struct module *mod)
1847 {
1848 }
1849
1850 static void init_param_lock(struct module *mod)
1851 {
1852 }
1853 #endif /* CONFIG_SYSFS */
1854
1855 static void mod_sysfs_teardown(struct module *mod)
1856 {
1857 del_usage_links(mod);
1858 module_remove_modinfo_attrs(mod);
1859 module_param_sysfs_remove(mod);
1860 kobject_put(mod->mkobj.drivers_dir);
1861 kobject_put(mod->holders_dir);
1862 mod_sysfs_fini(mod);
1863 }
1864
1865 #ifdef CONFIG_STRICT_MODULE_RWX
1866 /*
1867 * LKM RO/NX protection: protect module's text/ro-data
1868 * from modification and any data from execution.
1869 *
1870 * General layout of module is:
1871 * [text] [read-only-data] [ro-after-init] [writable data]
1872 * text_size -----^ ^ ^ ^
1873 * ro_size ------------------------| | |
1874 * ro_after_init_size -----------------------------| |
1875 * size -----------------------------------------------------------|
1876 *
1877 * These values are always page-aligned (as is base)
1878 */
1879 static void frob_text(const struct module_layout *layout,
1880 int (*set_memory)(unsigned long start, int num_pages))
1881 {
1882 BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
1883 BUG_ON((unsigned long)layout->text_size & (PAGE_SIZE-1));
1884 set_memory((unsigned long)layout->base,
1885 layout->text_size >> PAGE_SHIFT);
1886 }
1887
1888 static void frob_rodata(const struct module_layout *layout,
1889 int (*set_memory)(unsigned long start, int num_pages))
1890 {
1891 BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
1892 BUG_ON((unsigned long)layout->text_size & (PAGE_SIZE-1));
1893 BUG_ON((unsigned long)layout->ro_size & (PAGE_SIZE-1));
1894 set_memory((unsigned long)layout->base + layout->text_size,
1895 (layout->ro_size - layout->text_size) >> PAGE_SHIFT);
1896 }
1897
1898 static void frob_ro_after_init(const struct module_layout *layout,
1899 int (*set_memory)(unsigned long start, int num_pages))
1900 {
1901 BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
1902 BUG_ON((unsigned long)layout->ro_size & (PAGE_SIZE-1));
1903 BUG_ON((unsigned long)layout->ro_after_init_size & (PAGE_SIZE-1));
1904 set_memory((unsigned long)layout->base + layout->ro_size,
1905 (layout->ro_after_init_size - layout->ro_size) >> PAGE_SHIFT);
1906 }
1907
1908 static void frob_writable_data(const struct module_layout *layout,
1909 int (*set_memory)(unsigned long start, int num_pages))
1910 {
1911 BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
1912 BUG_ON((unsigned long)layout->ro_after_init_size & (PAGE_SIZE-1));
1913 BUG_ON((unsigned long)layout->size & (PAGE_SIZE-1));
1914 set_memory((unsigned long)layout->base + layout->ro_after_init_size,
1915 (layout->size - layout->ro_after_init_size) >> PAGE_SHIFT);
1916 }
1917
1918 /* livepatching wants to disable read-only so it can frob module. */
1919 void module_disable_ro(const struct module *mod)
1920 {
1921 if (!rodata_enabled)
1922 return;
1923
1924 frob_text(&mod->core_layout, set_memory_rw);
1925 frob_rodata(&mod->core_layout, set_memory_rw);
1926 frob_ro_after_init(&mod->core_layout, set_memory_rw);
1927 frob_text(&mod->init_layout, set_memory_rw);
1928 frob_rodata(&mod->init_layout, set_memory_rw);
1929 }
1930
1931 void module_enable_ro(const struct module *mod, bool after_init)
1932 {
1933 if (!rodata_enabled)
1934 return;
1935
1936 frob_text(&mod->core_layout, set_memory_ro);
1937 frob_rodata(&mod->core_layout, set_memory_ro);
1938 frob_text(&mod->init_layout, set_memory_ro);
1939 frob_rodata(&mod->init_layout, set_memory_ro);
1940
1941 if (after_init)
1942 frob_ro_after_init(&mod->core_layout, set_memory_ro);
1943 }
1944
1945 static void module_enable_nx(const struct module *mod)
1946 {
1947 frob_rodata(&mod->core_layout, set_memory_nx);
1948 frob_ro_after_init(&mod->core_layout, set_memory_nx);
1949 frob_writable_data(&mod->core_layout, set_memory_nx);
1950 frob_rodata(&mod->init_layout, set_memory_nx);
1951 frob_writable_data(&mod->init_layout, set_memory_nx);
1952 }
1953
1954 static void module_disable_nx(const struct module *mod)
1955 {
1956 frob_rodata(&mod->core_layout, set_memory_x);
1957 frob_ro_after_init(&mod->core_layout, set_memory_x);
1958 frob_writable_data(&mod->core_layout, set_memory_x);
1959 frob_rodata(&mod->init_layout, set_memory_x);
1960 frob_writable_data(&mod->init_layout, set_memory_x);
1961 }
1962
1963 /* Iterate through all modules and set each module's text as RW */
1964 void set_all_modules_text_rw(void)
1965 {
1966 struct module *mod;
1967
1968 if (!rodata_enabled)
1969 return;
1970
1971 mutex_lock(&module_mutex);
1972 list_for_each_entry_rcu(mod, &modules, list) {
1973 if (mod->state == MODULE_STATE_UNFORMED)
1974 continue;
1975
1976 frob_text(&mod->core_layout, set_memory_rw);
1977 frob_text(&mod->init_layout, set_memory_rw);
1978 }
1979 mutex_unlock(&module_mutex);
1980 }
1981
1982 /* Iterate through all modules and set each module's text as RO */
1983 void set_all_modules_text_ro(void)
1984 {
1985 struct module *mod;
1986
1987 if (!rodata_enabled)
1988 return;
1989
1990 mutex_lock(&module_mutex);
1991 list_for_each_entry_rcu(mod, &modules, list) {
1992 /*
1993 * Ignore going modules since it's possible that ro
1994 * protection has already been disabled, otherwise we'll
1995 * run into protection faults at module deallocation.
1996 */
1997 if (mod->state == MODULE_STATE_UNFORMED ||
1998 mod->state == MODULE_STATE_GOING)
1999 continue;
2000
2001 frob_text(&mod->core_layout, set_memory_ro);
2002 frob_text(&mod->init_layout, set_memory_ro);
2003 }
2004 mutex_unlock(&module_mutex);
2005 }
2006
2007 static void disable_ro_nx(const struct module_layout *layout)
2008 {
2009 if (rodata_enabled) {
2010 frob_text(layout, set_memory_rw);
2011 frob_rodata(layout, set_memory_rw);
2012 frob_ro_after_init(layout, set_memory_rw);
2013 }
2014 frob_rodata(layout, set_memory_x);
2015 frob_ro_after_init(layout, set_memory_x);
2016 frob_writable_data(layout, set_memory_x);
2017 }
2018
2019 #else
2020 static void disable_ro_nx(const struct module_layout *layout) { }
2021 static void module_enable_nx(const struct module *mod) { }
2022 static void module_disable_nx(const struct module *mod) { }
2023 #endif
2024
2025 #ifdef CONFIG_LIVEPATCH
2026 /*
2027 * Persist Elf information about a module. Copy the Elf header,
2028 * section header table, section string table, and symtab section
2029 * index from info to mod->klp_info.
2030 */
2031 static int copy_module_elf(struct module *mod, struct load_info *info)
2032 {
2033 unsigned int size, symndx;
2034 int ret;
2035
2036 size = sizeof(*mod->klp_info);
2037 mod->klp_info = kmalloc(size, GFP_KERNEL);
2038 if (mod->klp_info == NULL)
2039 return -ENOMEM;
2040
2041 /* Elf header */
2042 size = sizeof(mod->klp_info->hdr);
2043 memcpy(&mod->klp_info->hdr, info->hdr, size);
2044
2045 /* Elf section header table */
2046 size = sizeof(*info->sechdrs) * info->hdr->e_shnum;
2047 mod->klp_info->sechdrs = kmalloc(size, GFP_KERNEL);
2048 if (mod->klp_info->sechdrs == NULL) {
2049 ret = -ENOMEM;
2050 goto free_info;
2051 }
2052 memcpy(mod->klp_info->sechdrs, info->sechdrs, size);
2053
2054 /* Elf section name string table */
2055 size = info->sechdrs[info->hdr->e_shstrndx].sh_size;
2056 mod->klp_info->secstrings = kmalloc(size, GFP_KERNEL);
2057 if (mod->klp_info->secstrings == NULL) {
2058 ret = -ENOMEM;
2059 goto free_sechdrs;
2060 }
2061 memcpy(mod->klp_info->secstrings, info->secstrings, size);
2062
2063 /* Elf symbol section index */
2064 symndx = info->index.sym;
2065 mod->klp_info->symndx = symndx;
2066
2067 /*
2068 * For livepatch modules, core_kallsyms.symtab is a complete
2069 * copy of the original symbol table. Adjust sh_addr to point
2070 * to core_kallsyms.symtab since the copy of the symtab in module
2071 * init memory is freed at the end of do_init_module().
2072 */
2073 mod->klp_info->sechdrs[symndx].sh_addr = \
2074 (unsigned long) mod->core_kallsyms.symtab;
2075
2076 return 0;
2077
2078 free_sechdrs:
2079 kfree(mod->klp_info->sechdrs);
2080 free_info:
2081 kfree(mod->klp_info);
2082 return ret;
2083 }
2084
2085 static void free_module_elf(struct module *mod)
2086 {
2087 kfree(mod->klp_info->sechdrs);
2088 kfree(mod->klp_info->secstrings);
2089 kfree(mod->klp_info);
2090 }
2091 #else /* !CONFIG_LIVEPATCH */
2092 static int copy_module_elf(struct module *mod, struct load_info *info)
2093 {
2094 return 0;
2095 }
2096
2097 static void free_module_elf(struct module *mod)
2098 {
2099 }
2100 #endif /* CONFIG_LIVEPATCH */
2101
2102 void __weak module_memfree(void *module_region)
2103 {
2104 vfree(module_region);
2105 }
2106
2107 void __weak module_arch_cleanup(struct module *mod)
2108 {
2109 }
2110
2111 void __weak module_arch_freeing_init(struct module *mod)
2112 {
2113 }
2114
2115 /* Free a module, remove from lists, etc. */
2116 static void free_module(struct module *mod)
2117 {
2118 trace_module_free(mod);
2119
2120 mod_sysfs_teardown(mod);
2121
2122 /* We leave it in list to prevent duplicate loads, but make sure
2123 * that noone uses it while it's being deconstructed. */
2124 mutex_lock(&module_mutex);
2125 mod->state = MODULE_STATE_UNFORMED;
2126 mutex_unlock(&module_mutex);
2127
2128 /* Remove dynamic debug info */
2129 ddebug_remove_module(mod->name);
2130
2131 /* Arch-specific cleanup. */
2132 module_arch_cleanup(mod);
2133
2134 /* Module unload stuff */
2135 module_unload_free(mod);
2136
2137 /* Free any allocated parameters. */
2138 destroy_params(mod->kp, mod->num_kp);
2139
2140 if (is_livepatch_module(mod))
2141 free_module_elf(mod);
2142
2143 /* Now we can delete it from the lists */
2144 mutex_lock(&module_mutex);
2145 /* Unlink carefully: kallsyms could be walking list. */
2146 list_del_rcu(&mod->list);
2147 mod_tree_remove(mod);
2148 /* Remove this module from bug list, this uses list_del_rcu */
2149 module_bug_cleanup(mod);
2150 /* Wait for RCU-sched synchronizing before releasing mod->list and buglist. */
2151 synchronize_sched();
2152 mutex_unlock(&module_mutex);
2153
2154 /* This may be empty, but that's OK */
2155 disable_ro_nx(&mod->init_layout);
2156 module_arch_freeing_init(mod);
2157 module_memfree(mod->init_layout.base);
2158 kfree(mod->args);
2159 percpu_modfree(mod);
2160
2161 /* Free lock-classes; relies on the preceding sync_rcu(). */
2162 lockdep_free_key_range(mod->core_layout.base, mod->core_layout.size);
2163
2164 /* Finally, free the core (containing the module structure) */
2165 disable_ro_nx(&mod->core_layout);
2166 module_memfree(mod->core_layout.base);
2167
2168 #ifdef CONFIG_MPU
2169 update_protections(current->mm);
2170 #endif
2171 }
2172
2173 void *__symbol_get(const char *symbol)
2174 {
2175 struct module *owner;
2176 const struct kernel_symbol *sym;
2177
2178 preempt_disable();
2179 sym = find_symbol(symbol, &owner, NULL, true, true);
2180 if (sym && strong_try_module_get(owner))
2181 sym = NULL;
2182 preempt_enable();
2183
2184 return sym ? (void *)sym->value : NULL;
2185 }
2186 EXPORT_SYMBOL_GPL(__symbol_get);
2187
2188 /*
2189 * Ensure that an exported symbol [global namespace] does not already exist
2190 * in the kernel or in some other module's exported symbol table.
2191 *
2192 * You must hold the module_mutex.
2193 */
2194 static int verify_export_symbols(struct module *mod)
2195 {
2196 unsigned int i;
2197 struct module *owner;
2198 const struct kernel_symbol *s;
2199 struct {
2200 const struct kernel_symbol *sym;
2201 unsigned int num;
2202 } arr[] = {
2203 { mod->syms, mod->num_syms },
2204 { mod->gpl_syms, mod->num_gpl_syms },
2205 { mod->gpl_future_syms, mod->num_gpl_future_syms },
2206 #ifdef CONFIG_UNUSED_SYMBOLS
2207 { mod->unused_syms, mod->num_unused_syms },
2208 { mod->unused_gpl_syms, mod->num_unused_gpl_syms },
2209 #endif
2210 };
2211
2212 for (i = 0; i < ARRAY_SIZE(arr); i++) {
2213 for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
2214 if (find_symbol(s->name, &owner, NULL, true, false)) {
2215 pr_err("%s: exports duplicate symbol %s"
2216 " (owned by %s)\n",
2217 mod->name, s->name, module_name(owner));
2218 return -ENOEXEC;
2219 }
2220 }
2221 }
2222 return 0;
2223 }
2224
2225 /* Change all symbols so that st_value encodes the pointer directly. */
2226 static int simplify_symbols(struct module *mod, const struct load_info *info)
2227 {
2228 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2229 Elf_Sym *sym = (void *)symsec->sh_addr;
2230 unsigned long secbase;
2231 unsigned int i;
2232 int ret = 0;
2233 const struct kernel_symbol *ksym;
2234
2235 for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
2236 const char *name = info->strtab + sym[i].st_name;
2237
2238 switch (sym[i].st_shndx) {
2239 case SHN_COMMON:
2240 /* Ignore common symbols */
2241 if (!strncmp(name, "__gnu_lto", 9))
2242 break;
2243
2244 /* We compiled with -fno-common. These are not
2245 supposed to happen. */
2246 pr_debug("Common symbol: %s\n", name);
2247 pr_warn("%s: please compile with -fno-common\n",
2248 mod->name);
2249 ret = -ENOEXEC;
2250 break;
2251
2252 case SHN_ABS:
2253 /* Don't need to do anything */
2254 pr_debug("Absolute symbol: 0x%08lx\n",
2255 (long)sym[i].st_value);
2256 break;
2257
2258 case SHN_LIVEPATCH:
2259 /* Livepatch symbols are resolved by livepatch */
2260 break;
2261
2262 case SHN_UNDEF:
2263 ksym = resolve_symbol_wait(mod, info, name);
2264 /* Ok if resolved. */
2265 if (ksym && !IS_ERR(ksym)) {
2266 sym[i].st_value = ksym->value;
2267 break;
2268 }
2269
2270 /* Ok if weak. */
2271 if (!ksym && ELF_ST_BIND(sym[i].st_info) == STB_WEAK)
2272 break;
2273
2274 pr_warn("%s: Unknown symbol %s (err %li)\n",
2275 mod->name, name, PTR_ERR(ksym));
2276 ret = PTR_ERR(ksym) ?: -ENOENT;
2277 break;
2278
2279 default:
2280 /* Divert to percpu allocation if a percpu var. */
2281 if (sym[i].st_shndx == info->index.pcpu)
2282 secbase = (unsigned long)mod_percpu(mod);
2283 else
2284 secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
2285 sym[i].st_value += secbase;
2286 break;
2287 }
2288 }
2289
2290 return ret;
2291 }
2292
2293 static int apply_relocations(struct module *mod, const struct load_info *info)
2294 {
2295 unsigned int i;
2296 int err = 0;
2297
2298 /* Now do relocations. */
2299 for (i = 1; i < info->hdr->e_shnum; i++) {
2300 unsigned int infosec = info->sechdrs[i].sh_info;
2301
2302 /* Not a valid relocation section? */
2303 if (infosec >= info->hdr->e_shnum)
2304 continue;
2305
2306 /* Don't bother with non-allocated sections */
2307 if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
2308 continue;
2309
2310 /* Livepatch relocation sections are applied by livepatch */
2311 if (info->sechdrs[i].sh_flags & SHF_RELA_LIVEPATCH)
2312 continue;
2313
2314 if (info->sechdrs[i].sh_type == SHT_REL)
2315 err = apply_relocate(info->sechdrs, info->strtab,
2316 info->index.sym, i, mod);
2317 else if (info->sechdrs[i].sh_type == SHT_RELA)
2318 err = apply_relocate_add(info->sechdrs, info->strtab,
2319 info->index.sym, i, mod);
2320 if (err < 0)
2321 break;
2322 }
2323 return err;
2324 }
2325
2326 /* Additional bytes needed by arch in front of individual sections */
2327 unsigned int __weak arch_mod_section_prepend(struct module *mod,
2328 unsigned int section)
2329 {
2330 /* default implementation just returns zero */
2331 return 0;
2332 }
2333
2334 /* Update size with this section: return offset. */
2335 static long get_offset(struct module *mod, unsigned int *size,
2336 Elf_Shdr *sechdr, unsigned int section)
2337 {
2338 long ret;
2339
2340 *size += arch_mod_section_prepend(mod, section);
2341 ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
2342 *size = ret + sechdr->sh_size;
2343 return ret;
2344 }
2345
2346 /* Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
2347 might -- code, read-only data, read-write data, small data. Tally
2348 sizes, and place the offsets into sh_entsize fields: high bit means it
2349 belongs in init. */
2350 static void layout_sections(struct module *mod, struct load_info *info)
2351 {
2352 static unsigned long const masks[][2] = {
2353 /* NOTE: all executable code must be the first section
2354 * in this array; otherwise modify the text_size
2355 * finder in the two loops below */
2356 { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
2357 { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
2358 { SHF_RO_AFTER_INIT | SHF_ALLOC, ARCH_SHF_SMALL },
2359 { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
2360 { ARCH_SHF_SMALL | SHF_ALLOC, 0 }
2361 };
2362 unsigned int m, i;
2363
2364 for (i = 0; i < info->hdr->e_shnum; i++)
2365 info->sechdrs[i].sh_entsize = ~0UL;
2366
2367 pr_debug("Core section allocation order:\n");
2368 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2369 for (i = 0; i < info->hdr->e_shnum; ++i) {
2370 Elf_Shdr *s = &info->sechdrs[i];
2371 const char *sname = info->secstrings + s->sh_name;
2372
2373 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2374 || (s->sh_flags & masks[m][1])
2375 || s->sh_entsize != ~0UL
2376 || strstarts(sname, ".init"))
2377 continue;
2378 s->sh_entsize = get_offset(mod, &mod->core_layout.size, s, i);
2379 pr_debug("\t%s\n", sname);
2380 }
2381 switch (m) {
2382 case 0: /* executable */
2383 mod->core_layout.size = debug_align(mod->core_layout.size);
2384 mod->core_layout.text_size = mod->core_layout.size;
2385 break;
2386 case 1: /* RO: text and ro-data */
2387 mod->core_layout.size = debug_align(mod->core_layout.size);
2388 mod->core_layout.ro_size = mod->core_layout.size;
2389 break;
2390 case 2: /* RO after init */
2391 mod->core_layout.size = debug_align(mod->core_layout.size);
2392 mod->core_layout.ro_after_init_size = mod->core_layout.size;
2393 break;
2394 case 4: /* whole core */
2395 mod->core_layout.size = debug_align(mod->core_layout.size);
2396 break;
2397 }
2398 }
2399
2400 pr_debug("Init section allocation order:\n");
2401 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2402 for (i = 0; i < info->hdr->e_shnum; ++i) {
2403 Elf_Shdr *s = &info->sechdrs[i];
2404 const char *sname = info->secstrings + s->sh_name;
2405
2406 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2407 || (s->sh_flags & masks[m][1])
2408 || s->sh_entsize != ~0UL
2409 || !strstarts(sname, ".init"))
2410 continue;
2411 s->sh_entsize = (get_offset(mod, &mod->init_layout.size, s, i)
2412 | INIT_OFFSET_MASK);
2413 pr_debug("\t%s\n", sname);
2414 }
2415 switch (m) {
2416 case 0: /* executable */
2417 mod->init_layout.size = debug_align(mod->init_layout.size);
2418 mod->init_layout.text_size = mod->init_layout.size;
2419 break;
2420 case 1: /* RO: text and ro-data */
2421 mod->init_layout.size = debug_align(mod->init_layout.size);
2422 mod->init_layout.ro_size = mod->init_layout.size;
2423 break;
2424 case 2:
2425 /*
2426 * RO after init doesn't apply to init_layout (only
2427 * core_layout), so it just takes the value of ro_size.
2428 */
2429 mod->init_layout.ro_after_init_size = mod->init_layout.ro_size;
2430 break;
2431 case 4: /* whole init */
2432 mod->init_layout.size = debug_align(mod->init_layout.size);
2433 break;
2434 }
2435 }
2436 }
2437
2438 static void set_license(struct module *mod, const char *license)
2439 {
2440 if (!license)
2441 license = "unspecified";
2442
2443 if (!license_is_gpl_compatible(license)) {
2444 if (!test_taint(TAINT_PROPRIETARY_MODULE))
2445 pr_warn("%s: module license '%s' taints kernel.\n",
2446 mod->name, license);
2447 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2448 LOCKDEP_NOW_UNRELIABLE);
2449 }
2450 }
2451
2452 /* Parse tag=value strings from .modinfo section */
2453 static char *next_string(char *string, unsigned long *secsize)
2454 {
2455 /* Skip non-zero chars */
2456 while (string[0]) {
2457 string++;
2458 if ((*secsize)-- <= 1)
2459 return NULL;
2460 }
2461
2462 /* Skip any zero padding. */
2463 while (!string[0]) {
2464 string++;
2465 if ((*secsize)-- <= 1)
2466 return NULL;
2467 }
2468 return string;
2469 }
2470
2471 static char *get_modinfo(struct load_info *info, const char *tag)
2472 {
2473 char *p;
2474 unsigned int taglen = strlen(tag);
2475 Elf_Shdr *infosec = &info->sechdrs[info->index.info];
2476 unsigned long size = infosec->sh_size;
2477
2478 for (p = (char *)infosec->sh_addr; p; p = next_string(p, &size)) {
2479 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
2480 return p + taglen + 1;
2481 }
2482 return NULL;
2483 }
2484
2485 static void setup_modinfo(struct module *mod, struct load_info *info)
2486 {
2487 struct module_attribute *attr;
2488 int i;
2489
2490 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2491 if (attr->setup)
2492 attr->setup(mod, get_modinfo(info, attr->attr.name));
2493 }
2494 }
2495
2496 static void free_modinfo(struct module *mod)
2497 {
2498 struct module_attribute *attr;
2499 int i;
2500
2501 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2502 if (attr->free)
2503 attr->free(mod);
2504 }
2505 }
2506
2507 #ifdef CONFIG_KALLSYMS
2508
2509 /* lookup symbol in given range of kernel_symbols */
2510 static const struct kernel_symbol *lookup_symbol(const char *name,
2511 const struct kernel_symbol *start,
2512 const struct kernel_symbol *stop)
2513 {
2514 return bsearch(name, start, stop - start,
2515 sizeof(struct kernel_symbol), cmp_name);
2516 }
2517
2518 static int is_exported(const char *name, unsigned long value,
2519 const struct module *mod)
2520 {
2521 const struct kernel_symbol *ks;
2522 if (!mod)
2523 ks = lookup_symbol(name, __start___ksymtab, __stop___ksymtab);
2524 else
2525 ks = lookup_symbol(name, mod->syms, mod->syms + mod->num_syms);
2526 return ks != NULL && ks->value == value;
2527 }
2528
2529 /* As per nm */
2530 static char elf_type(const Elf_Sym *sym, const struct load_info *info)
2531 {
2532 const Elf_Shdr *sechdrs = info->sechdrs;
2533
2534 if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
2535 if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT)
2536 return 'v';
2537 else
2538 return 'w';
2539 }
2540 if (sym->st_shndx == SHN_UNDEF)
2541 return 'U';
2542 if (sym->st_shndx == SHN_ABS || sym->st_shndx == info->index.pcpu)
2543 return 'a';
2544 if (sym->st_shndx >= SHN_LORESERVE)
2545 return '?';
2546 if (sechdrs[sym->st_shndx].sh_flags & SHF_EXECINSTR)
2547 return 't';
2548 if (sechdrs[sym->st_shndx].sh_flags & SHF_ALLOC
2549 && sechdrs[sym->st_shndx].sh_type != SHT_NOBITS) {
2550 if (!(sechdrs[sym->st_shndx].sh_flags & SHF_WRITE))
2551 return 'r';
2552 else if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2553 return 'g';
2554 else
2555 return 'd';
2556 }
2557 if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
2558 if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2559 return 's';
2560 else
2561 return 'b';
2562 }
2563 if (strstarts(info->secstrings + sechdrs[sym->st_shndx].sh_name,
2564 ".debug")) {
2565 return 'n';
2566 }
2567 return '?';
2568 }
2569
2570 static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
2571 unsigned int shnum, unsigned int pcpundx)
2572 {
2573 const Elf_Shdr *sec;
2574
2575 if (src->st_shndx == SHN_UNDEF
2576 || src->st_shndx >= shnum
2577 || !src->st_name)
2578 return false;
2579
2580 #ifdef CONFIG_KALLSYMS_ALL
2581 if (src->st_shndx == pcpundx)
2582 return true;
2583 #endif
2584
2585 sec = sechdrs + src->st_shndx;
2586 if (!(sec->sh_flags & SHF_ALLOC)
2587 #ifndef CONFIG_KALLSYMS_ALL
2588 || !(sec->sh_flags & SHF_EXECINSTR)
2589 #endif
2590 || (sec->sh_entsize & INIT_OFFSET_MASK))
2591 return false;
2592
2593 return true;
2594 }
2595
2596 /*
2597 * We only allocate and copy the strings needed by the parts of symtab
2598 * we keep. This is simple, but has the effect of making multiple
2599 * copies of duplicates. We could be more sophisticated, see
2600 * linux-kernel thread starting with
2601 * <73defb5e4bca04a6431392cc341112b1@localhost>.
2602 */
2603 static void layout_symtab(struct module *mod, struct load_info *info)
2604 {
2605 Elf_Shdr *symsect = info->sechdrs + info->index.sym;
2606 Elf_Shdr *strsect = info->sechdrs + info->index.str;
2607 const Elf_Sym *src;
2608 unsigned int i, nsrc, ndst, strtab_size = 0;
2609
2610 /* Put symbol section at end of init part of module. */
2611 symsect->sh_flags |= SHF_ALLOC;
2612 symsect->sh_entsize = get_offset(mod, &mod->init_layout.size, symsect,
2613 info->index.sym) | INIT_OFFSET_MASK;
2614 pr_debug("\t%s\n", info->secstrings + symsect->sh_name);
2615
2616 src = (void *)info->hdr + symsect->sh_offset;
2617 nsrc = symsect->sh_size / sizeof(*src);
2618
2619 /* Compute total space required for the core symbols' strtab. */
2620 for (ndst = i = 0; i < nsrc; i++) {
2621 if (i == 0 || is_livepatch_module(mod) ||
2622 is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum,
2623 info->index.pcpu)) {
2624 strtab_size += strlen(&info->strtab[src[i].st_name])+1;
2625 ndst++;
2626 }
2627 }
2628
2629 /* Append room for core symbols at end of core part. */
2630 info->symoffs = ALIGN(mod->core_layout.size, symsect->sh_addralign ?: 1);
2631 info->stroffs = mod->core_layout.size = info->symoffs + ndst * sizeof(Elf_Sym);
2632 mod->core_layout.size += strtab_size;
2633 mod->core_layout.size = debug_align(mod->core_layout.size);
2634
2635 /* Put string table section at end of init part of module. */
2636 strsect->sh_flags |= SHF_ALLOC;
2637 strsect->sh_entsize = get_offset(mod, &mod->init_layout.size, strsect,
2638 info->index.str) | INIT_OFFSET_MASK;
2639 pr_debug("\t%s\n", info->secstrings + strsect->sh_name);
2640
2641 /* We'll tack temporary mod_kallsyms on the end. */
2642 mod->init_layout.size = ALIGN(mod->init_layout.size,
2643 __alignof__(struct mod_kallsyms));
2644 info->mod_kallsyms_init_off = mod->init_layout.size;
2645 mod->init_layout.size += sizeof(struct mod_kallsyms);
2646 mod->init_layout.size = debug_align(mod->init_layout.size);
2647 }
2648
2649 /*
2650 * We use the full symtab and strtab which layout_symtab arranged to
2651 * be appended to the init section. Later we switch to the cut-down
2652 * core-only ones.
2653 */
2654 static void add_kallsyms(struct module *mod, const struct load_info *info)
2655 {
2656 unsigned int i, ndst;
2657 const Elf_Sym *src;
2658 Elf_Sym *dst;
2659 char *s;
2660 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2661
2662 /* Set up to point into init section. */
2663 mod->kallsyms = mod->init_layout.base + info->mod_kallsyms_init_off;
2664
2665 mod->kallsyms->symtab = (void *)symsec->sh_addr;
2666 mod->kallsyms->num_symtab = symsec->sh_size / sizeof(Elf_Sym);
2667 /* Make sure we get permanent strtab: don't use info->strtab. */
2668 mod->kallsyms->strtab = (void *)info->sechdrs[info->index.str].sh_addr;
2669
2670 /* Set types up while we still have access to sections. */
2671 for (i = 0; i < mod->kallsyms->num_symtab; i++)
2672 mod->kallsyms->symtab[i].st_info
2673 = elf_type(&mod->kallsyms->symtab[i], info);
2674
2675 /* Now populate the cut down core kallsyms for after init. */
2676 mod->core_kallsyms.symtab = dst = mod->core_layout.base + info->symoffs;
2677 mod->core_kallsyms.strtab = s = mod->core_layout.base + info->stroffs;
2678 src = mod->kallsyms->symtab;
2679 for (ndst = i = 0; i < mod->kallsyms->num_symtab; i++) {
2680 if (i == 0 || is_livepatch_module(mod) ||
2681 is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum,
2682 info->index.pcpu)) {
2683 dst[ndst] = src[i];
2684 dst[ndst++].st_name = s - mod->core_kallsyms.strtab;
2685 s += strlcpy(s, &mod->kallsyms->strtab[src[i].st_name],
2686 KSYM_NAME_LEN) + 1;
2687 }
2688 }
2689 mod->core_kallsyms.num_symtab = ndst;
2690 }
2691 #else
2692 static inline void layout_symtab(struct module *mod, struct load_info *info)
2693 {
2694 }
2695
2696 static void add_kallsyms(struct module *mod, const struct load_info *info)
2697 {
2698 }
2699 #endif /* CONFIG_KALLSYMS */
2700
2701 static void dynamic_debug_setup(struct _ddebug *debug, unsigned int num)
2702 {
2703 if (!debug)
2704 return;
2705 #ifdef CONFIG_DYNAMIC_DEBUG
2706 if (ddebug_add_module(debug, num, debug->modname))
2707 pr_err("dynamic debug error adding module: %s\n",
2708 debug->modname);
2709 #endif
2710 }
2711
2712 static void dynamic_debug_remove(struct _ddebug *debug)
2713 {
2714 if (debug)
2715 ddebug_remove_module(debug->modname);
2716 }
2717
2718 void * __weak module_alloc(unsigned long size)
2719 {
2720 return vmalloc_exec(size);
2721 }
2722
2723 #ifdef CONFIG_DEBUG_KMEMLEAK
2724 static void kmemleak_load_module(const struct module *mod,
2725 const struct load_info *info)
2726 {
2727 unsigned int i;
2728
2729 /* only scan the sections containing data */
2730 kmemleak_scan_area(mod, sizeof(struct module), GFP_KERNEL);
2731
2732 for (i = 1; i < info->hdr->e_shnum; i++) {
2733 /* Scan all writable sections that's not executable */
2734 if (!(info->sechdrs[i].sh_flags & SHF_ALLOC) ||
2735 !(info->sechdrs[i].sh_flags & SHF_WRITE) ||
2736 (info->sechdrs[i].sh_flags & SHF_EXECINSTR))
2737 continue;
2738
2739 kmemleak_scan_area((void *)info->sechdrs[i].sh_addr,
2740 info->sechdrs[i].sh_size, GFP_KERNEL);
2741 }
2742 }
2743 #else
2744 static inline void kmemleak_load_module(const struct module *mod,
2745 const struct load_info *info)
2746 {
2747 }
2748 #endif
2749
2750 #ifdef CONFIG_MODULE_SIG
2751 static int module_sig_check(struct load_info *info, int flags)
2752 {
2753 int err = -ENOKEY;
2754 const unsigned long markerlen = sizeof(MODULE_SIG_STRING) - 1;
2755 const void *mod = info->hdr;
2756
2757 /*
2758 * Require flags == 0, as a module with version information
2759 * removed is no longer the module that was signed
2760 */
2761 if (flags == 0 &&
2762 info->len > markerlen &&
2763 memcmp(mod + info->len - markerlen, MODULE_SIG_STRING, markerlen) == 0) {
2764 /* We truncate the module to discard the signature */
2765 info->len -= markerlen;
2766 err = mod_verify_sig(mod, &info->len);
2767 }
2768
2769 if (!err) {
2770 info->sig_ok = true;
2771 return 0;
2772 }
2773
2774 /* Not having a signature is only an error if we're strict. */
2775 if (err == -ENOKEY && !sig_enforce)
2776 err = 0;
2777
2778 return err;
2779 }
2780 #else /* !CONFIG_MODULE_SIG */
2781 static int module_sig_check(struct load_info *info, int flags)
2782 {
2783 return 0;
2784 }
2785 #endif /* !CONFIG_MODULE_SIG */
2786
2787 /* Sanity checks against invalid binaries, wrong arch, weird elf version. */
2788 static int elf_header_check(struct load_info *info)
2789 {
2790 if (info->len < sizeof(*(info->hdr)))
2791 return -ENOEXEC;
2792
2793 if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0
2794 || info->hdr->e_type != ET_REL
2795 || !elf_check_arch(info->hdr)
2796 || info->hdr->e_shentsize != sizeof(Elf_Shdr))
2797 return -ENOEXEC;
2798
2799 if (info->hdr->e_shoff >= info->len
2800 || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
2801 info->len - info->hdr->e_shoff))
2802 return -ENOEXEC;
2803
2804 return 0;
2805 }
2806
2807 #define COPY_CHUNK_SIZE (16*PAGE_SIZE)
2808
2809 static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len)
2810 {
2811 do {
2812 unsigned long n = min(len, COPY_CHUNK_SIZE);
2813
2814 if (copy_from_user(dst, usrc, n) != 0)
2815 return -EFAULT;
2816 cond_resched();
2817 dst += n;
2818 usrc += n;
2819 len -= n;
2820 } while (len);
2821 return 0;
2822 }
2823
2824 #ifdef CONFIG_LIVEPATCH
2825 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
2826 {
2827 if (get_modinfo(info, "livepatch")) {
2828 mod->klp = true;
2829 add_taint_module(mod, TAINT_LIVEPATCH, LOCKDEP_STILL_OK);
2830 pr_notice_once("%s: tainting kernel with TAINT_LIVEPATCH\n",
2831 mod->name);
2832 }
2833
2834 return 0;
2835 }
2836 #else /* !CONFIG_LIVEPATCH */
2837 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
2838 {
2839 if (get_modinfo(info, "livepatch")) {
2840 pr_err("%s: module is marked as livepatch module, but livepatch support is disabled",
2841 mod->name);
2842 return -ENOEXEC;
2843 }
2844
2845 return 0;
2846 }
2847 #endif /* CONFIG_LIVEPATCH */
2848
2849 /* Sets info->hdr and info->len. */
2850 static int copy_module_from_user(const void __user *umod, unsigned long len,
2851 struct load_info *info)
2852 {
2853 int err;
2854
2855 info->len = len;
2856 if (info->len < sizeof(*(info->hdr)))
2857 return -ENOEXEC;
2858
2859 err = security_kernel_read_file(NULL, READING_MODULE);
2860 if (err)
2861 return err;
2862
2863 /* Suck in entire file: we'll want most of it. */
2864 info->hdr = __vmalloc(info->len,
2865 GFP_KERNEL | __GFP_NOWARN, PAGE_KERNEL);
2866 if (!info->hdr)
2867 return -ENOMEM;
2868
2869 if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) {
2870 vfree(info->hdr);
2871 return -EFAULT;
2872 }
2873
2874 return 0;
2875 }
2876
2877 static void free_copy(struct load_info *info)
2878 {
2879 vfree(info->hdr);
2880 }
2881
2882 static int rewrite_section_headers(struct load_info *info, int flags)
2883 {
2884 unsigned int i;
2885
2886 /* This should always be true, but let's be sure. */
2887 info->sechdrs[0].sh_addr = 0;
2888
2889 for (i = 1; i < info->hdr->e_shnum; i++) {
2890 Elf_Shdr *shdr = &info->sechdrs[i];
2891 if (shdr->sh_type != SHT_NOBITS
2892 && info->len < shdr->sh_offset + shdr->sh_size) {
2893 pr_err("Module len %lu truncated\n", info->len);
2894 return -ENOEXEC;
2895 }
2896
2897 /* Mark all sections sh_addr with their address in the
2898 temporary image. */
2899 shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
2900
2901 #ifndef CONFIG_MODULE_UNLOAD
2902 /* Don't load .exit sections */
2903 if (strstarts(info->secstrings+shdr->sh_name, ".exit"))
2904 shdr->sh_flags &= ~(unsigned long)SHF_ALLOC;
2905 #endif
2906 }
2907
2908 /* Track but don't keep modinfo and version sections. */
2909 if (flags & MODULE_INIT_IGNORE_MODVERSIONS)
2910 info->index.vers = 0; /* Pretend no __versions section! */
2911 else
2912 info->index.vers = find_sec(info, "__versions");
2913 info->index.info = find_sec(info, ".modinfo");
2914 info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
2915 info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
2916 return 0;
2917 }
2918
2919 /*
2920 * Set up our basic convenience variables (pointers to section headers,
2921 * search for module section index etc), and do some basic section
2922 * verification.
2923 *
2924 * Return the temporary module pointer (we'll replace it with the final
2925 * one when we move the module sections around).
2926 */
2927 static struct module *setup_load_info(struct load_info *info, int flags)
2928 {
2929 unsigned int i;
2930 int err;
2931 struct module *mod;
2932
2933 /* Set up the convenience variables */
2934 info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
2935 info->secstrings = (void *)info->hdr
2936 + info->sechdrs[info->hdr->e_shstrndx].sh_offset;
2937
2938 err = rewrite_section_headers(info, flags);
2939 if (err)
2940 return ERR_PTR(err);
2941
2942 /* Find internal symbols and strings. */
2943 for (i = 1; i < info->hdr->e_shnum; i++) {
2944 if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
2945 info->index.sym = i;
2946 info->index.str = info->sechdrs[i].sh_link;
2947 info->strtab = (char *)info->hdr
2948 + info->sechdrs[info->index.str].sh_offset;
2949 break;
2950 }
2951 }
2952
2953 info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
2954 if (!info->index.mod) {
2955 pr_warn("No module found in object\n");
2956 return ERR_PTR(-ENOEXEC);
2957 }
2958 /* This is temporary: point mod into copy of data. */
2959 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2960
2961 if (info->index.sym == 0) {
2962 pr_warn("%s: module has no symbols (stripped?)\n", mod->name);
2963 return ERR_PTR(-ENOEXEC);
2964 }
2965
2966 info->index.pcpu = find_pcpusec(info);
2967
2968 /* Check module struct version now, before we try to use module. */
2969 if (!check_modstruct_version(info->sechdrs, info->index.vers, mod))
2970 return ERR_PTR(-ENOEXEC);
2971
2972 return mod;
2973 }
2974
2975 static int check_modinfo(struct module *mod, struct load_info *info, int flags)
2976 {
2977 const char *modmagic = get_modinfo(info, "vermagic");
2978 int err;
2979
2980 if (flags & MODULE_INIT_IGNORE_VERMAGIC)
2981 modmagic = NULL;
2982
2983 /* This is allowed: modprobe --force will invalidate it. */
2984 if (!modmagic) {
2985 err = try_to_force_load(mod, "bad vermagic");
2986 if (err)
2987 return err;
2988 } else if (!same_magic(modmagic, vermagic, info->index.vers)) {
2989 pr_err("%s: version magic '%s' should be '%s'\n",
2990 mod->name, modmagic, vermagic);
2991 return -ENOEXEC;
2992 }
2993
2994 if (!get_modinfo(info, "intree")) {
2995 if (!test_taint(TAINT_OOT_MODULE))
2996 pr_warn("%s: loading out-of-tree module taints kernel.\n",
2997 mod->name);
2998 add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
2999 }
3000
3001 if (get_modinfo(info, "staging")) {
3002 add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
3003 pr_warn("%s: module is from the staging directory, the quality "
3004 "is unknown, you have been warned.\n", mod->name);
3005 }
3006
3007 err = check_modinfo_livepatch(mod, info);
3008 if (err)
3009 return err;
3010
3011 /* Set up license info based on the info section */
3012 set_license(mod, get_modinfo(info, "license"));
3013
3014 return 0;
3015 }
3016
3017 static int find_module_sections(struct module *mod, struct load_info *info)
3018 {
3019 mod->kp = section_objs(info, "__param",
3020 sizeof(*mod->kp), &mod->num_kp);
3021 mod->syms = section_objs(info, "__ksymtab",
3022 sizeof(*mod->syms), &mod->num_syms);
3023 mod->crcs = section_addr(info, "__kcrctab");
3024 mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
3025 sizeof(*mod->gpl_syms),
3026 &mod->num_gpl_syms);
3027 mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
3028 mod->gpl_future_syms = section_objs(info,
3029 "__ksymtab_gpl_future",
3030 sizeof(*mod->gpl_future_syms),
3031 &mod->num_gpl_future_syms);
3032 mod->gpl_future_crcs = section_addr(info, "__kcrctab_gpl_future");
3033
3034 #ifdef CONFIG_UNUSED_SYMBOLS
3035 mod->unused_syms = section_objs(info, "__ksymtab_unused",
3036 sizeof(*mod->unused_syms),
3037 &mod->num_unused_syms);
3038 mod->unused_crcs = section_addr(info, "__kcrctab_unused");
3039 mod->unused_gpl_syms = section_objs(info, "__ksymtab_unused_gpl",
3040 sizeof(*mod->unused_gpl_syms),
3041 &mod->num_unused_gpl_syms);
3042 mod->unused_gpl_crcs = section_addr(info, "__kcrctab_unused_gpl");
3043 #endif
3044 #ifdef CONFIG_CONSTRUCTORS
3045 mod->ctors = section_objs(info, ".ctors",
3046 sizeof(*mod->ctors), &mod->num_ctors);
3047 if (!mod->ctors)
3048 mod->ctors = section_objs(info, ".init_array",
3049 sizeof(*mod->ctors), &mod->num_ctors);
3050 else if (find_sec(info, ".init_array")) {
3051 /*
3052 * This shouldn't happen with same compiler and binutils
3053 * building all parts of the module.
3054 */
3055 pr_warn("%s: has both .ctors and .init_array.\n",
3056 mod->name);
3057 return -EINVAL;
3058 }
3059 #endif
3060
3061 #ifdef CONFIG_TRACEPOINTS
3062 mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
3063 sizeof(*mod->tracepoints_ptrs),
3064 &mod->num_tracepoints);
3065 #endif
3066 #ifdef HAVE_JUMP_LABEL
3067 mod->jump_entries = section_objs(info, "__jump_table",
3068 sizeof(*mod->jump_entries),
3069 &mod->num_jump_entries);
3070 #endif
3071 #ifdef CONFIG_EVENT_TRACING
3072 mod->trace_events = section_objs(info, "_ftrace_events",
3073 sizeof(*mod->trace_events),
3074 &mod->num_trace_events);
3075 mod->trace_evals = section_objs(info, "_ftrace_eval_map",
3076 sizeof(*mod->trace_evals),
3077 &mod->num_trace_evals);
3078 #endif
3079 #ifdef CONFIG_TRACING
3080 mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
3081 sizeof(*mod->trace_bprintk_fmt_start),
3082 &mod->num_trace_bprintk_fmt);
3083 #endif
3084 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
3085 /* sechdrs[0].sh_size is always zero */
3086 mod->ftrace_callsites = section_objs(info, "__mcount_loc",
3087 sizeof(*mod->ftrace_callsites),
3088 &mod->num_ftrace_callsites);
3089 #endif
3090
3091 mod->extable = section_objs(info, "__ex_table",
3092 sizeof(*mod->extable), &mod->num_exentries);
3093
3094 if (section_addr(info, "__obsparm"))
3095 pr_warn("%s: Ignoring obsolete parameters\n", mod->name);
3096
3097 info->debug = section_objs(info, "__verbose",
3098 sizeof(*info->debug), &info->num_debug);
3099
3100 return 0;
3101 }
3102
3103 static int move_module(struct module *mod, struct load_info *info)
3104 {
3105 int i;
3106 void *ptr;
3107
3108 /* Do the allocs. */
3109 ptr = module_alloc(mod->core_layout.size);
3110 /*
3111 * The pointer to this block is stored in the module structure
3112 * which is inside the block. Just mark it as not being a
3113 * leak.
3114 */
3115 kmemleak_not_leak(ptr);
3116 if (!ptr)
3117 return -ENOMEM;
3118
3119 memset(ptr, 0, mod->core_layout.size);
3120 mod->core_layout.base = ptr;
3121
3122 if (mod->init_layout.size) {
3123 ptr = module_alloc(mod->init_layout.size);
3124 /*
3125 * The pointer to this block is stored in the module structure
3126 * which is inside the block. This block doesn't need to be
3127 * scanned as it contains data and code that will be freed
3128 * after the module is initialized.
3129 */
3130 kmemleak_ignore(ptr);
3131 if (!ptr) {
3132 module_memfree(mod->core_layout.base);
3133 return -ENOMEM;
3134 }
3135 memset(ptr, 0, mod->init_layout.size);
3136 mod->init_layout.base = ptr;
3137 } else
3138 mod->init_layout.base = NULL;
3139
3140 /* Transfer each section which specifies SHF_ALLOC */
3141 pr_debug("final section addresses:\n");
3142 for (i = 0; i < info->hdr->e_shnum; i++) {
3143 void *dest;
3144 Elf_Shdr *shdr = &info->sechdrs[i];
3145
3146 if (!(shdr->sh_flags & SHF_ALLOC))
3147 continue;
3148
3149 if (shdr->sh_entsize & INIT_OFFSET_MASK)
3150 dest = mod->init_layout.base
3151 + (shdr->sh_entsize & ~INIT_OFFSET_MASK);
3152 else
3153 dest = mod->core_layout.base + shdr->sh_entsize;
3154
3155 if (shdr->sh_type != SHT_NOBITS)
3156 memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
3157 /* Update sh_addr to point to copy in image. */
3158 shdr->sh_addr = (unsigned long)dest;
3159 pr_debug("\t0x%lx %s\n",
3160 (long)shdr->sh_addr, info->secstrings + shdr->sh_name);
3161 }
3162
3163 return 0;
3164 }
3165
3166 static int check_module_license_and_versions(struct module *mod)
3167 {
3168 int prev_taint = test_taint(TAINT_PROPRIETARY_MODULE);
3169
3170 /*
3171 * ndiswrapper is under GPL by itself, but loads proprietary modules.
3172 * Don't use add_taint_module(), as it would prevent ndiswrapper from
3173 * using GPL-only symbols it needs.
3174 */
3175 if (strcmp(mod->name, "ndiswrapper") == 0)
3176 add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
3177
3178 /* driverloader was caught wrongly pretending to be under GPL */
3179 if (strcmp(mod->name, "driverloader") == 0)
3180 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
3181 LOCKDEP_NOW_UNRELIABLE);
3182
3183 /* lve claims to be GPL but upstream won't provide source */
3184 if (strcmp(mod->name, "lve") == 0)
3185 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
3186 LOCKDEP_NOW_UNRELIABLE);
3187
3188 if (!prev_taint && test_taint(TAINT_PROPRIETARY_MODULE))
3189 pr_warn("%s: module license taints kernel.\n", mod->name);
3190
3191 #ifdef CONFIG_MODVERSIONS
3192 if ((mod->num_syms && !mod->crcs)
3193 || (mod->num_gpl_syms && !mod->gpl_crcs)
3194 || (mod->num_gpl_future_syms && !mod->gpl_future_crcs)
3195 #ifdef CONFIG_UNUSED_SYMBOLS
3196 || (mod->num_unused_syms && !mod->unused_crcs)
3197 || (mod->num_unused_gpl_syms && !mod->unused_gpl_crcs)
3198 #endif
3199 ) {
3200 return try_to_force_load(mod,
3201 "no versions for exported symbols");
3202 }
3203 #endif
3204 return 0;
3205 }
3206
3207 static void flush_module_icache(const struct module *mod)
3208 {
3209 mm_segment_t old_fs;
3210
3211 /* flush the icache in correct context */
3212 old_fs = get_fs();
3213 set_fs(KERNEL_DS);
3214
3215 /*
3216 * Flush the instruction cache, since we've played with text.
3217 * Do it before processing of module parameters, so the module
3218 * can provide parameter accessor functions of its own.
3219 */
3220 if (mod->init_layout.base)
3221 flush_icache_range((unsigned long)mod->init_layout.base,
3222 (unsigned long)mod->init_layout.base
3223 + mod->init_layout.size);
3224 flush_icache_range((unsigned long)mod->core_layout.base,
3225 (unsigned long)mod->core_layout.base + mod->core_layout.size);
3226
3227 set_fs(old_fs);
3228 }
3229
3230 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
3231 Elf_Shdr *sechdrs,
3232 char *secstrings,
3233 struct module *mod)
3234 {
3235 return 0;
3236 }
3237
3238 /* module_blacklist is a comma-separated list of module names */
3239 static char *module_blacklist;
3240 static bool blacklisted(char *module_name)
3241 {
3242 const char *p;
3243 size_t len;
3244
3245 if (!module_blacklist)
3246 return false;
3247
3248 for (p = module_blacklist; *p; p += len) {
3249 len = strcspn(p, ",");
3250 if (strlen(module_name) == len && !memcmp(module_name, p, len))
3251 return true;
3252 if (p[len] == ',')
3253 len++;
3254 }
3255 return false;
3256 }
3257 core_param(module_blacklist, module_blacklist, charp, 0400);
3258
3259 static struct module *layout_and_allocate(struct load_info *info, int flags)
3260 {
3261 /* Module within temporary copy. */
3262 struct module *mod;
3263 unsigned int ndx;
3264 int err;
3265
3266 mod = setup_load_info(info, flags);
3267 if (IS_ERR(mod))
3268 return mod;
3269
3270 if (blacklisted(mod->name))
3271 return ERR_PTR(-EPERM);
3272
3273 err = check_modinfo(mod, info, flags);
3274 if (err)
3275 return ERR_PTR(err);
3276
3277 /* Allow arches to frob section contents and sizes. */
3278 err = module_frob_arch_sections(info->hdr, info->sechdrs,
3279 info->secstrings, mod);
3280 if (err < 0)
3281 return ERR_PTR(err);
3282
3283 /* We will do a special allocation for per-cpu sections later. */
3284 info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
3285
3286 /*
3287 * Mark ro_after_init section with SHF_RO_AFTER_INIT so that
3288 * layout_sections() can put it in the right place.
3289 * Note: ro_after_init sections also have SHF_{WRITE,ALLOC} set.
3290 */
3291 ndx = find_sec(info, ".data..ro_after_init");
3292 if (ndx)
3293 info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
3294
3295 /* Determine total sizes, and put offsets in sh_entsize. For now
3296 this is done generically; there doesn't appear to be any
3297 special cases for the architectures. */
3298 layout_sections(mod, info);
3299 layout_symtab(mod, info);
3300
3301 /* Allocate and move to the final place */
3302 err = move_module(mod, info);
3303 if (err)
3304 return ERR_PTR(err);
3305
3306 /* Module has been copied to its final place now: return it. */
3307 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
3308 kmemleak_load_module(mod, info);
3309 return mod;
3310 }
3311
3312 /* mod is no longer valid after this! */
3313 static void module_deallocate(struct module *mod, struct load_info *info)
3314 {
3315 percpu_modfree(mod);
3316 module_arch_freeing_init(mod);
3317 module_memfree(mod->init_layout.base);
3318 module_memfree(mod->core_layout.base);
3319 }
3320
3321 int __weak module_finalize(const Elf_Ehdr *hdr,
3322 const Elf_Shdr *sechdrs,
3323 struct module *me)
3324 {
3325 return 0;
3326 }
3327
3328 static int post_relocation(struct module *mod, const struct load_info *info)
3329 {
3330 /* Sort exception table now relocations are done. */
3331 sort_extable(mod->extable, mod->extable + mod->num_exentries);
3332
3333 /* Copy relocated percpu area over. */
3334 percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
3335 info->sechdrs[info->index.pcpu].sh_size);
3336
3337 /* Setup kallsyms-specific fields. */
3338 add_kallsyms(mod, info);
3339
3340 /* Arch-specific module finalizing. */
3341 return module_finalize(info->hdr, info->sechdrs, mod);
3342 }
3343
3344 /* Is this module of this name done loading? No locks held. */
3345 static bool finished_loading(const char *name)
3346 {
3347 struct module *mod;
3348 bool ret;
3349
3350 /*
3351 * The module_mutex should not be a heavily contended lock;
3352 * if we get the occasional sleep here, we'll go an extra iteration
3353 * in the wait_event_interruptible(), which is harmless.
3354 */
3355 sched_annotate_sleep();
3356 mutex_lock(&module_mutex);
3357 mod = find_module_all(name, strlen(name), true);
3358 ret = !mod || mod->state == MODULE_STATE_LIVE
3359 || mod->state == MODULE_STATE_GOING;
3360 mutex_unlock(&module_mutex);
3361
3362 return ret;
3363 }
3364
3365 /* Call module constructors. */
3366 static void do_mod_ctors(struct module *mod)
3367 {
3368 #ifdef CONFIG_CONSTRUCTORS
3369 unsigned long i;
3370
3371 for (i = 0; i < mod->num_ctors; i++)
3372 mod->ctors[i]();
3373 #endif
3374 }
3375
3376 /* For freeing module_init on success, in case kallsyms traversing */
3377 struct mod_initfree {
3378 struct rcu_head rcu;
3379 void *module_init;
3380 };
3381
3382 static void do_free_init(struct rcu_head *head)
3383 {
3384 struct mod_initfree *m = container_of(head, struct mod_initfree, rcu);
3385 module_memfree(m->module_init);
3386 kfree(m);
3387 }
3388
3389 /*
3390 * This is where the real work happens.
3391 *
3392 * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb
3393 * helper command 'lx-symbols'.
3394 */
3395 static noinline int do_init_module(struct module *mod)
3396 {
3397 int ret = 0;
3398 struct mod_initfree *freeinit;
3399
3400 freeinit = kmalloc(sizeof(*freeinit), GFP_KERNEL);
3401 if (!freeinit) {
3402 ret = -ENOMEM;
3403 goto fail;
3404 }
3405 freeinit->module_init = mod->init_layout.base;
3406
3407 /*
3408 * We want to find out whether @mod uses async during init. Clear
3409 * PF_USED_ASYNC. async_schedule*() will set it.
3410 */
3411 current->flags &= ~PF_USED_ASYNC;
3412
3413 do_mod_ctors(mod);
3414 /* Start the module */
3415 if (mod->init != NULL)
3416 ret = do_one_initcall(mod->init);
3417 if (ret < 0) {
3418 goto fail_free_freeinit;
3419 }
3420 if (ret > 0) {
3421 pr_warn("%s: '%s'->init suspiciously returned %d, it should "
3422 "follow 0/-E convention\n"
3423 "%s: loading module anyway...\n",
3424 __func__, mod->name, ret, __func__);
3425 dump_stack();
3426 }
3427
3428 /* Now it's a first class citizen! */
3429 mod->state = MODULE_STATE_LIVE;
3430 blocking_notifier_call_chain(&module_notify_list,
3431 MODULE_STATE_LIVE, mod);
3432
3433 /*
3434 * We need to finish all async code before the module init sequence
3435 * is done. This has potential to deadlock. For example, a newly
3436 * detected block device can trigger request_module() of the
3437 * default iosched from async probing task. Once userland helper
3438 * reaches here, async_synchronize_full() will wait on the async
3439 * task waiting on request_module() and deadlock.
3440 *
3441 * This deadlock is avoided by perfomring async_synchronize_full()
3442 * iff module init queued any async jobs. This isn't a full
3443 * solution as it will deadlock the same if module loading from
3444 * async jobs nests more than once; however, due to the various
3445 * constraints, this hack seems to be the best option for now.
3446 * Please refer to the following thread for details.
3447 *
3448 * http://thread.gmane.org/gmane.linux.kernel/1420814
3449 */
3450 if (!mod->async_probe_requested && (current->flags & PF_USED_ASYNC))
3451 async_synchronize_full();
3452
3453 mutex_lock(&module_mutex);
3454 /* Drop initial reference. */
3455 module_put(mod);
3456 trim_init_extable(mod);
3457 #ifdef CONFIG_KALLSYMS
3458 /* Switch to core kallsyms now init is done: kallsyms may be walking! */
3459 rcu_assign_pointer(mod->kallsyms, &mod->core_kallsyms);
3460 #endif
3461 module_enable_ro(mod, true);
3462 mod_tree_remove_init(mod);
3463 disable_ro_nx(&mod->init_layout);
3464 module_arch_freeing_init(mod);
3465 mod->init_layout.base = NULL;
3466 mod->init_layout.size = 0;
3467 mod->init_layout.ro_size = 0;
3468 mod->init_layout.ro_after_init_size = 0;
3469 mod->init_layout.text_size = 0;
3470 /*
3471 * We want to free module_init, but be aware that kallsyms may be
3472 * walking this with preempt disabled. In all the failure paths, we
3473 * call synchronize_sched(), but we don't want to slow down the success
3474 * path, so use actual RCU here.
3475 */
3476 call_rcu_sched(&freeinit->rcu, do_free_init);
3477 mutex_unlock(&module_mutex);
3478 wake_up_all(&module_wq);
3479
3480 return 0;
3481
3482 fail_free_freeinit:
3483 kfree(freeinit);
3484 fail:
3485 /* Try to protect us from buggy refcounters. */
3486 mod->state = MODULE_STATE_GOING;
3487 synchronize_sched();
3488 module_put(mod);
3489 blocking_notifier_call_chain(&module_notify_list,
3490 MODULE_STATE_GOING, mod);
3491 klp_module_going(mod);
3492 ftrace_release_mod(mod);
3493 free_module(mod);
3494 wake_up_all(&module_wq);
3495 return ret;
3496 }
3497
3498 static int may_init_module(void)
3499 {
3500 if (!capable(CAP_SYS_MODULE) || modules_disabled)
3501 return -EPERM;
3502
3503 return 0;
3504 }
3505
3506 /*
3507 * We try to place it in the list now to make sure it's unique before
3508 * we dedicate too many resources. In particular, temporary percpu
3509 * memory exhaustion.
3510 */
3511 static int add_unformed_module(struct module *mod)
3512 {
3513 int err;
3514 struct module *old;
3515
3516 mod->state = MODULE_STATE_UNFORMED;
3517
3518 again:
3519 mutex_lock(&module_mutex);
3520 old = find_module_all(mod->name, strlen(mod->name), true);
3521 if (old != NULL) {
3522 if (old->state == MODULE_STATE_COMING
3523 || old->state == MODULE_STATE_UNFORMED) {
3524 /* Wait in case it fails to load. */
3525 mutex_unlock(&module_mutex);
3526 err = wait_event_interruptible(module_wq,
3527 finished_loading(mod->name));
3528 if (err)
3529 goto out_unlocked;
3530 goto again;
3531 }
3532 err = -EEXIST;
3533 goto out;
3534 }
3535 mod_update_bounds(mod);
3536 list_add_rcu(&mod->list, &modules);
3537 mod_tree_insert(mod);
3538 err = 0;
3539
3540 out:
3541 mutex_unlock(&module_mutex);
3542 out_unlocked:
3543 return err;
3544 }
3545
3546 static int complete_formation(struct module *mod, struct load_info *info)
3547 {
3548 int err;
3549
3550 mutex_lock(&module_mutex);
3551
3552 /* Find duplicate symbols (must be called under lock). */
3553 err = verify_export_symbols(mod);
3554 if (err < 0)
3555 goto out;
3556
3557 /* This relies on module_mutex for list integrity. */
3558 module_bug_finalize(info->hdr, info->sechdrs, mod);
3559
3560 module_enable_ro(mod, false);
3561 module_enable_nx(mod);
3562
3563 /* Mark state as coming so strong_try_module_get() ignores us,
3564 * but kallsyms etc. can see us. */
3565 mod->state = MODULE_STATE_COMING;
3566 mutex_unlock(&module_mutex);
3567
3568 return 0;
3569
3570 out:
3571 mutex_unlock(&module_mutex);
3572 return err;
3573 }
3574
3575 static int prepare_coming_module(struct module *mod)
3576 {
3577 int err;
3578
3579 ftrace_module_enable(mod);
3580 err = klp_module_coming(mod);
3581 if (err)
3582 return err;
3583
3584 blocking_notifier_call_chain(&module_notify_list,
3585 MODULE_STATE_COMING, mod);
3586 return 0;
3587 }
3588
3589 static int unknown_module_param_cb(char *param, char *val, const char *modname,
3590 void *arg)
3591 {
3592 struct module *mod = arg;
3593 int ret;
3594
3595 if (strcmp(param, "async_probe") == 0) {
3596 mod->async_probe_requested = true;
3597 return 0;
3598 }
3599
3600 /* Check for magic 'dyndbg' arg */
3601 ret = ddebug_dyndbg_module_param_cb(param, val, modname);
3602 if (ret != 0)
3603 pr_warn("%s: unknown parameter '%s' ignored\n", modname, param);
3604 return 0;
3605 }
3606
3607 /* Allocate and load the module: note that size of section 0 is always
3608 zero, and we rely on this for optional sections. */
3609 static int load_module(struct load_info *info, const char __user *uargs,
3610 int flags)
3611 {
3612 struct module *mod;
3613 long err;
3614 char *after_dashes;
3615
3616 err = module_sig_check(info, flags);
3617 if (err)
3618 goto free_copy;
3619
3620 err = elf_header_check(info);
3621 if (err)
3622 goto free_copy;
3623
3624 /* Figure out module layout, and allocate all the memory. */
3625 mod = layout_and_allocate(info, flags);
3626 if (IS_ERR(mod)) {
3627 err = PTR_ERR(mod);
3628 goto free_copy;
3629 }
3630
3631 audit_log_kern_module(mod->name);
3632
3633 /* Reserve our place in the list. */
3634 err = add_unformed_module(mod);
3635 if (err)
3636 goto free_module;
3637
3638 #ifdef CONFIG_MODULE_SIG
3639 mod->sig_ok = info->sig_ok;
3640 if (!mod->sig_ok) {
3641 pr_notice_once("%s: module verification failed: signature "
3642 "and/or required key missing - tainting "
3643 "kernel\n", mod->name);
3644 add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
3645 }
3646 #endif
3647
3648 /* To avoid stressing percpu allocator, do this once we're unique. */
3649 err = percpu_modalloc(mod, info);
3650 if (err)
3651 goto unlink_mod;
3652
3653 /* Now module is in final location, initialize linked lists, etc. */
3654 err = module_unload_init(mod);
3655 if (err)
3656 goto unlink_mod;
3657
3658 init_param_lock(mod);
3659
3660 /* Now we've got everything in the final locations, we can
3661 * find optional sections. */
3662 err = find_module_sections(mod, info);
3663 if (err)
3664 goto free_unload;
3665
3666 err = check_module_license_and_versions(mod);
3667 if (err)
3668 goto free_unload;
3669
3670 /* Set up MODINFO_ATTR fields */
3671 setup_modinfo(mod, info);
3672
3673 /* Fix up syms, so that st_value is a pointer to location. */
3674 err = simplify_symbols(mod, info);
3675 if (err < 0)
3676 goto free_modinfo;
3677
3678 err = apply_relocations(mod, info);
3679 if (err < 0)
3680 goto free_modinfo;
3681
3682 err = post_relocation(mod, info);
3683 if (err < 0)
3684 goto free_modinfo;
3685
3686 flush_module_icache(mod);
3687
3688 /* Now copy in args */
3689 mod->args = strndup_user(uargs, ~0UL >> 1);
3690 if (IS_ERR(mod->args)) {
3691 err = PTR_ERR(mod->args);
3692 goto free_arch_cleanup;
3693 }
3694
3695 dynamic_debug_setup(info->debug, info->num_debug);
3696
3697 /* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
3698 ftrace_module_init(mod);
3699
3700 /* Finally it's fully formed, ready to start executing. */
3701 err = complete_formation(mod, info);
3702 if (err)
3703 goto ddebug_cleanup;
3704
3705 err = prepare_coming_module(mod);
3706 if (err)
3707 goto bug_cleanup;
3708
3709 /* Module is ready to execute: parsing args may do that. */
3710 after_dashes = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
3711 -32768, 32767, mod,
3712 unknown_module_param_cb);
3713 if (IS_ERR(after_dashes)) {
3714 err = PTR_ERR(after_dashes);
3715 goto coming_cleanup;
3716 } else if (after_dashes) {
3717 pr_warn("%s: parameters '%s' after `--' ignored\n",
3718 mod->name, after_dashes);
3719 }
3720
3721 /* Link in to sysfs. */
3722 err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
3723 if (err < 0)
3724 goto coming_cleanup;
3725
3726 if (is_livepatch_module(mod)) {
3727 err = copy_module_elf(mod, info);
3728 if (err < 0)
3729 goto sysfs_cleanup;
3730 }
3731
3732 /* Get rid of temporary copy. */
3733 free_copy(info);
3734
3735 /* Done! */
3736 trace_module_load(mod);
3737
3738 return do_init_module(mod);
3739
3740 sysfs_cleanup:
3741 mod_sysfs_teardown(mod);
3742 coming_cleanup:
3743 mod->state = MODULE_STATE_GOING;
3744 destroy_params(mod->kp, mod->num_kp);
3745 blocking_notifier_call_chain(&module_notify_list,
3746 MODULE_STATE_GOING, mod);
3747 klp_module_going(mod);
3748 bug_cleanup:
3749 /* module_bug_cleanup needs module_mutex protection */
3750 mutex_lock(&module_mutex);
3751 module_bug_cleanup(mod);
3752 mutex_unlock(&module_mutex);
3753
3754 /* we can't deallocate the module until we clear memory protection */
3755 module_disable_ro(mod);
3756 module_disable_nx(mod);
3757
3758 ddebug_cleanup:
3759 dynamic_debug_remove(info->debug);
3760 synchronize_sched();
3761 kfree(mod->args);
3762 free_arch_cleanup:
3763 module_arch_cleanup(mod);
3764 free_modinfo:
3765 free_modinfo(mod);
3766 free_unload:
3767 module_unload_free(mod);
3768 unlink_mod:
3769 mutex_lock(&module_mutex);
3770 /* Unlink carefully: kallsyms could be walking list. */
3771 list_del_rcu(&mod->list);
3772 mod_tree_remove(mod);
3773 wake_up_all(&module_wq);
3774 /* Wait for RCU-sched synchronizing before releasing mod->list. */
3775 synchronize_sched();
3776 mutex_unlock(&module_mutex);
3777 free_module:
3778 /*
3779 * Ftrace needs to clean up what it initialized.
3780 * This does nothing if ftrace_module_init() wasn't called,
3781 * but it must be called outside of module_mutex.
3782 */
3783 ftrace_release_mod(mod);
3784 /* Free lock-classes; relies on the preceding sync_rcu() */
3785 lockdep_free_key_range(mod->core_layout.base, mod->core_layout.size);
3786
3787 module_deallocate(mod, info);
3788 free_copy:
3789 free_copy(info);
3790 return err;
3791 }
3792
3793 SYSCALL_DEFINE3(init_module, void __user *, umod,
3794 unsigned long, len, const char __user *, uargs)
3795 {
3796 int err;
3797 struct load_info info = { };
3798
3799 err = may_init_module();
3800 if (err)
3801 return err;
3802
3803 pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
3804 umod, len, uargs);
3805
3806 err = copy_module_from_user(umod, len, &info);
3807 if (err)
3808 return err;
3809
3810 return load_module(&info, uargs, 0);
3811 }
3812
3813 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
3814 {
3815 struct load_info info = { };
3816 loff_t size;
3817 void *hdr;
3818 int err;
3819
3820 err = may_init_module();
3821 if (err)
3822 return err;
3823
3824 pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
3825
3826 if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
3827 |MODULE_INIT_IGNORE_VERMAGIC))
3828 return -EINVAL;
3829
3830 err = kernel_read_file_from_fd(fd, &hdr, &size, INT_MAX,
3831 READING_MODULE);
3832 if (err)
3833 return err;
3834 info.hdr = hdr;
3835 info.len = size;
3836
3837 return load_module(&info, uargs, flags);
3838 }
3839
3840 static inline int within(unsigned long addr, void *start, unsigned long size)
3841 {
3842 return ((void *)addr >= start && (void *)addr < start + size);
3843 }
3844
3845 #ifdef CONFIG_KALLSYMS
3846 /*
3847 * This ignores the intensely annoying "mapping symbols" found
3848 * in ARM ELF files: $a, $t and $d.
3849 */
3850 static inline int is_arm_mapping_symbol(const char *str)
3851 {
3852 if (str[0] == '.' && str[1] == 'L')
3853 return true;
3854 return str[0] == '$' && strchr("axtd", str[1])
3855 && (str[2] == '\0' || str[2] == '.');
3856 }
3857
3858 static const char *symname(struct mod_kallsyms *kallsyms, unsigned int symnum)
3859 {
3860 return kallsyms->strtab + kallsyms->symtab[symnum].st_name;
3861 }
3862
3863 static const char *get_ksymbol(struct module *mod,
3864 unsigned long addr,
3865 unsigned long *size,
3866 unsigned long *offset)
3867 {
3868 unsigned int i, best = 0;
3869 unsigned long nextval;
3870 struct mod_kallsyms *kallsyms = rcu_dereference_sched(mod->kallsyms);
3871
3872 /* At worse, next value is at end of module */
3873 if (within_module_init(addr, mod))
3874 nextval = (unsigned long)mod->init_layout.base+mod->init_layout.text_size;
3875 else
3876 nextval = (unsigned long)mod->core_layout.base+mod->core_layout.text_size;
3877
3878 /* Scan for closest preceding symbol, and next symbol. (ELF
3879 starts real symbols at 1). */
3880 for (i = 1; i < kallsyms->num_symtab; i++) {
3881 if (kallsyms->symtab[i].st_shndx == SHN_UNDEF)
3882 continue;
3883
3884 /* We ignore unnamed symbols: they're uninformative
3885 * and inserted at a whim. */
3886 if (*symname(kallsyms, i) == '\0'
3887 || is_arm_mapping_symbol(symname(kallsyms, i)))
3888 continue;
3889
3890 if (kallsyms->symtab[i].st_value <= addr
3891 && kallsyms->symtab[i].st_value > kallsyms->symtab[best].st_value)
3892 best = i;
3893 if (kallsyms->symtab[i].st_value > addr
3894 && kallsyms->symtab[i].st_value < nextval)
3895 nextval = kallsyms->symtab[i].st_value;
3896 }
3897
3898 if (!best)
3899 return NULL;
3900
3901 if (size)
3902 *size = nextval - kallsyms->symtab[best].st_value;
3903 if (offset)
3904 *offset = addr - kallsyms->symtab[best].st_value;
3905 return symname(kallsyms, best);
3906 }
3907
3908 /* For kallsyms to ask for address resolution. NULL means not found. Careful
3909 * not to lock to avoid deadlock on oopses, simply disable preemption. */
3910 const char *module_address_lookup(unsigned long addr,
3911 unsigned long *size,
3912 unsigned long *offset,
3913 char **modname,
3914 char *namebuf)
3915 {
3916 const char *ret = NULL;
3917 struct module *mod;
3918
3919 preempt_disable();
3920 mod = __module_address(addr);
3921 if (mod) {
3922 if (modname)
3923 *modname = mod->name;
3924 ret = get_ksymbol(mod, addr, size, offset);
3925 }
3926 /* Make a copy in here where it's safe */
3927 if (ret) {
3928 strncpy(namebuf, ret, KSYM_NAME_LEN - 1);
3929 ret = namebuf;
3930 }
3931 preempt_enable();
3932
3933 return ret;
3934 }
3935
3936 int lookup_module_symbol_name(unsigned long addr, char *symname)
3937 {
3938 struct module *mod;
3939
3940 preempt_disable();
3941 list_for_each_entry_rcu(mod, &modules, list) {
3942 if (mod->state == MODULE_STATE_UNFORMED)
3943 continue;
3944 if (within_module(addr, mod)) {
3945 const char *sym;
3946
3947 sym = get_ksymbol(mod, addr, NULL, NULL);
3948 if (!sym)
3949 goto out;
3950 strlcpy(symname, sym, KSYM_NAME_LEN);
3951 preempt_enable();
3952 return 0;
3953 }
3954 }
3955 out:
3956 preempt_enable();
3957 return -ERANGE;
3958 }
3959
3960 int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size,
3961 unsigned long *offset, char *modname, char *name)
3962 {
3963 struct module *mod;
3964
3965 preempt_disable();
3966 list_for_each_entry_rcu(mod, &modules, list) {
3967 if (mod->state == MODULE_STATE_UNFORMED)
3968 continue;
3969 if (within_module(addr, mod)) {
3970 const char *sym;
3971
3972 sym = get_ksymbol(mod, addr, size, offset);
3973 if (!sym)
3974 goto out;
3975 if (modname)
3976 strlcpy(modname, mod->name, MODULE_NAME_LEN);
3977 if (name)
3978 strlcpy(name, sym, KSYM_NAME_LEN);
3979 preempt_enable();
3980 return 0;
3981 }
3982 }
3983 out:
3984 preempt_enable();
3985 return -ERANGE;
3986 }
3987
3988 int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
3989 char *name, char *module_name, int *exported)
3990 {
3991 struct module *mod;
3992
3993 preempt_disable();
3994 list_for_each_entry_rcu(mod, &modules, list) {
3995 struct mod_kallsyms *kallsyms;
3996
3997 if (mod->state == MODULE_STATE_UNFORMED)
3998 continue;
3999 kallsyms = rcu_dereference_sched(mod->kallsyms);
4000 if (symnum < kallsyms->num_symtab) {
4001 *value = kallsyms->symtab[symnum].st_value;
4002 *type = kallsyms->symtab[symnum].st_info;
4003 strlcpy(name, symname(kallsyms, symnum), KSYM_NAME_LEN);
4004 strlcpy(module_name, mod->name, MODULE_NAME_LEN);
4005 *exported = is_exported(name, *value, mod);
4006 preempt_enable();
4007 return 0;
4008 }
4009 symnum -= kallsyms->num_symtab;
4010 }
4011 preempt_enable();
4012 return -ERANGE;
4013 }
4014
4015 static unsigned long mod_find_symname(struct module *mod, const char *name)
4016 {
4017 unsigned int i;
4018 struct mod_kallsyms *kallsyms = rcu_dereference_sched(mod->kallsyms);
4019
4020 for (i = 0; i < kallsyms->num_symtab; i++)
4021 if (strcmp(name, symname(kallsyms, i)) == 0 &&
4022 kallsyms->symtab[i].st_info != 'U')
4023 return kallsyms->symtab[i].st_value;
4024 return 0;
4025 }
4026
4027 /* Look for this name: can be of form module:name. */
4028 unsigned long module_kallsyms_lookup_name(const char *name)
4029 {
4030 struct module *mod;
4031 char *colon;
4032 unsigned long ret = 0;
4033
4034 /* Don't lock: we're in enough trouble already. */
4035 preempt_disable();
4036 if ((colon = strnchr(name, MODULE_NAME_LEN, ':')) != NULL) {
4037 if ((mod = find_module_all(name, colon - name, false)) != NULL)
4038 ret = mod_find_symname(mod, colon+1);
4039 } else {
4040 list_for_each_entry_rcu(mod, &modules, list) {
4041 if (mod->state == MODULE_STATE_UNFORMED)
4042 continue;
4043 if ((ret = mod_find_symname(mod, name)) != 0)
4044 break;
4045 }
4046 }
4047 preempt_enable();
4048 return ret;
4049 }
4050
4051 int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
4052 struct module *, unsigned long),
4053 void *data)
4054 {
4055 struct module *mod;
4056 unsigned int i;
4057 int ret;
4058
4059 module_assert_mutex();
4060
4061 list_for_each_entry(mod, &modules, list) {
4062 /* We hold module_mutex: no need for rcu_dereference_sched */
4063 struct mod_kallsyms *kallsyms = mod->kallsyms;
4064
4065 if (mod->state == MODULE_STATE_UNFORMED)
4066 continue;
4067 for (i = 0; i < kallsyms->num_symtab; i++) {
4068 ret = fn(data, symname(kallsyms, i),
4069 mod, kallsyms->symtab[i].st_value);
4070 if (ret != 0)
4071 return ret;
4072 }
4073 }
4074 return 0;
4075 }
4076 #endif /* CONFIG_KALLSYMS */
4077
4078 /* Maximum number of characters written by module_flags() */
4079 #define MODULE_FLAGS_BUF_SIZE (TAINT_FLAGS_COUNT + 4)
4080
4081 /* Keep in sync with MODULE_FLAGS_BUF_SIZE !!! */
4082 static char *module_flags(struct module *mod, char *buf)
4083 {
4084 int bx = 0;
4085
4086 BUG_ON(mod->state == MODULE_STATE_UNFORMED);
4087 if (mod->taints ||
4088 mod->state == MODULE_STATE_GOING ||
4089 mod->state == MODULE_STATE_COMING) {
4090 buf[bx++] = '(';
4091 bx += module_flags_taint(mod, buf + bx);
4092 /* Show a - for module-is-being-unloaded */
4093 if (mod->state == MODULE_STATE_GOING)
4094 buf[bx++] = '-';
4095 /* Show a + for module-is-being-loaded */
4096 if (mod->state == MODULE_STATE_COMING)
4097 buf[bx++] = '+';
4098 buf[bx++] = ')';
4099 }
4100 buf[bx] = '\0';
4101
4102 return buf;
4103 }
4104
4105 #ifdef CONFIG_PROC_FS
4106 /* Called by the /proc file system to return a list of modules. */
4107 static void *m_start(struct seq_file *m, loff_t *pos)
4108 {
4109 mutex_lock(&module_mutex);
4110 return seq_list_start(&modules, *pos);
4111 }
4112
4113 static void *m_next(struct seq_file *m, void *p, loff_t *pos)
4114 {
4115 return seq_list_next(p, &modules, pos);
4116 }
4117
4118 static void m_stop(struct seq_file *m, void *p)
4119 {
4120 mutex_unlock(&module_mutex);
4121 }
4122
4123 static int m_show(struct seq_file *m, void *p)
4124 {
4125 struct module *mod = list_entry(p, struct module, list);
4126 char buf[MODULE_FLAGS_BUF_SIZE];
4127
4128 /* We always ignore unformed modules. */
4129 if (mod->state == MODULE_STATE_UNFORMED)
4130 return 0;
4131
4132 seq_printf(m, "%s %u",
4133 mod->name, mod->init_layout.size + mod->core_layout.size);
4134 print_unload_info(m, mod);
4135
4136 /* Informative for users. */
4137 seq_printf(m, " %s",
4138 mod->state == MODULE_STATE_GOING ? "Unloading" :
4139 mod->state == MODULE_STATE_COMING ? "Loading" :
4140 "Live");
4141 /* Used by oprofile and other similar tools. */
4142 seq_printf(m, " 0x%pK", mod->core_layout.base);
4143
4144 /* Taints info */
4145 if (mod->taints)
4146 seq_printf(m, " %s", module_flags(mod, buf));
4147
4148 seq_puts(m, "\n");
4149 return 0;
4150 }
4151
4152 /* Format: modulename size refcount deps address
4153
4154 Where refcount is a number or -, and deps is a comma-separated list
4155 of depends or -.
4156 */
4157 static const struct seq_operations modules_op = {
4158 .start = m_start,
4159 .next = m_next,
4160 .stop = m_stop,
4161 .show = m_show
4162 };
4163
4164 static int modules_open(struct inode *inode, struct file *file)
4165 {
4166 return seq_open(file, &modules_op);
4167 }
4168
4169 static const struct file_operations proc_modules_operations = {
4170 .open = modules_open,
4171 .read = seq_read,
4172 .llseek = seq_lseek,
4173 .release = seq_release,
4174 };
4175
4176 static int __init proc_modules_init(void)
4177 {
4178 proc_create("modules", 0, NULL, &proc_modules_operations);
4179 return 0;
4180 }
4181 module_init(proc_modules_init);
4182 #endif
4183
4184 /* Given an address, look for it in the module exception tables. */
4185 const struct exception_table_entry *search_module_extables(unsigned long addr)
4186 {
4187 const struct exception_table_entry *e = NULL;
4188 struct module *mod;
4189
4190 preempt_disable();
4191 mod = __module_address(addr);
4192 if (!mod)
4193 goto out;
4194
4195 if (!mod->num_exentries)
4196 goto out;
4197
4198 e = search_extable(mod->extable,
4199 mod->extable + mod->num_exentries - 1,
4200 addr);
4201 out:
4202 preempt_enable();
4203
4204 /*
4205 * Now, if we found one, we are running inside it now, hence
4206 * we cannot unload the module, hence no refcnt needed.
4207 */
4208 return e;
4209 }
4210
4211 /*
4212 * is_module_address - is this address inside a module?
4213 * @addr: the address to check.
4214 *
4215 * See is_module_text_address() if you simply want to see if the address
4216 * is code (not data).
4217 */
4218 bool is_module_address(unsigned long addr)
4219 {
4220 bool ret;
4221
4222 preempt_disable();
4223 ret = __module_address(addr) != NULL;
4224 preempt_enable();
4225
4226 return ret;
4227 }
4228
4229 /*
4230 * __module_address - get the module which contains an address.
4231 * @addr: the address.
4232 *
4233 * Must be called with preempt disabled or module mutex held so that
4234 * module doesn't get freed during this.
4235 */
4236 struct module *__module_address(unsigned long addr)
4237 {
4238 struct module *mod;
4239
4240 if (addr < module_addr_min || addr > module_addr_max)
4241 return NULL;
4242
4243 module_assert_mutex_or_preempt();
4244
4245 mod = mod_find(addr);
4246 if (mod) {
4247 BUG_ON(!within_module(addr, mod));
4248 if (mod->state == MODULE_STATE_UNFORMED)
4249 mod = NULL;
4250 }
4251 return mod;
4252 }
4253 EXPORT_SYMBOL_GPL(__module_address);
4254
4255 /*
4256 * is_module_text_address - is this address inside module code?
4257 * @addr: the address to check.
4258 *
4259 * See is_module_address() if you simply want to see if the address is
4260 * anywhere in a module. See kernel_text_address() for testing if an
4261 * address corresponds to kernel or module code.
4262 */
4263 bool is_module_text_address(unsigned long addr)
4264 {
4265 bool ret;
4266
4267 preempt_disable();
4268 ret = __module_text_address(addr) != NULL;
4269 preempt_enable();
4270
4271 return ret;
4272 }
4273
4274 /*
4275 * __module_text_address - get the module whose code contains an address.
4276 * @addr: the address.
4277 *
4278 * Must be called with preempt disabled or module mutex held so that
4279 * module doesn't get freed during this.
4280 */
4281 struct module *__module_text_address(unsigned long addr)
4282 {
4283 struct module *mod = __module_address(addr);
4284 if (mod) {
4285 /* Make sure it's within the text section. */
4286 if (!within(addr, mod->init_layout.base, mod->init_layout.text_size)
4287 && !within(addr, mod->core_layout.base, mod->core_layout.text_size))
4288 mod = NULL;
4289 }
4290 return mod;
4291 }
4292 EXPORT_SYMBOL_GPL(__module_text_address);
4293
4294 /* Don't grab lock, we're oopsing. */
4295 void print_modules(void)
4296 {
4297 struct module *mod;
4298 char buf[MODULE_FLAGS_BUF_SIZE];
4299
4300 printk(KERN_DEFAULT "Modules linked in:");
4301 /* Most callers should already have preempt disabled, but make sure */
4302 preempt_disable();
4303 list_for_each_entry_rcu(mod, &modules, list) {
4304 if (mod->state == MODULE_STATE_UNFORMED)
4305 continue;
4306 pr_cont(" %s%s", mod->name, module_flags(mod, buf));
4307 }
4308 preempt_enable();
4309 if (last_unloaded_module[0])
4310 pr_cont(" [last unloaded: %s]", last_unloaded_module);
4311 pr_cont("\n");
4312 }
4313
4314 #ifdef CONFIG_MODVERSIONS
4315 /* Generate the signature for all relevant module structures here.
4316 * If these change, we don't want to try to parse the module. */
4317 void module_layout(struct module *mod,
4318 struct modversion_info *ver,
4319 struct kernel_param *kp,
4320 struct kernel_symbol *ks,
4321 struct tracepoint * const *tp)
4322 {
4323 }
4324 EXPORT_SYMBOL(module_layout);
4325 #endif