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