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