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