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