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