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