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