• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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,const char * name)1382 static bool inherit_taint(struct module *mod, struct module *owner, const char *name)
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 %s from proprietary module %s.\n",
1389 			mod->name, name, owner->name);
1390 		return false;
1391 	}
1392 
1393 	if (!test_bit(TAINT_PROPRIETARY_MODULE, &mod->taints)) {
1394 		pr_warn("%s: module uses symbols %s from proprietary module %s, inheriting taint.\n",
1395 			mod->name, 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, name)) {
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 	err = ref_module(mod, fsa.owner);
1444 	if (err) {
1445 		fsa.sym = ERR_PTR(err);
1446 		goto getname;
1447 	}
1448 
1449 getname:
1450 	/* We must make copy under the lock if we failed to get ref. */
1451 	strncpy(ownername, module_name(fsa.owner), MODULE_NAME_LEN);
1452 unlock:
1453 	mutex_unlock(&module_mutex);
1454 	return fsa.sym;
1455 }
1456 
1457 static const struct kernel_symbol *
resolve_symbol_wait(struct module * mod,const struct load_info * info,const char * name)1458 resolve_symbol_wait(struct module *mod,
1459 		    const struct load_info *info,
1460 		    const char *name)
1461 {
1462 	const struct kernel_symbol *ksym;
1463 	char owner[MODULE_NAME_LEN];
1464 
1465 	if (wait_event_interruptible_timeout(module_wq,
1466 			!IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1467 			|| PTR_ERR(ksym) != -EBUSY,
1468 					     30 * HZ) <= 0) {
1469 		pr_warn("%s: gave up waiting for init of module %s.\n",
1470 			mod->name, owner);
1471 	}
1472 	return ksym;
1473 }
1474 
1475 #ifdef CONFIG_KALLSYMS
sect_empty(const Elf_Shdr * sect)1476 static inline bool sect_empty(const Elf_Shdr *sect)
1477 {
1478 	return !(sect->sh_flags & SHF_ALLOC) || sect->sh_size == 0;
1479 }
1480 #endif
1481 
1482 /*
1483  * /sys/module/foo/sections stuff
1484  * J. Corbet <corbet@lwn.net>
1485  */
1486 #ifdef CONFIG_SYSFS
1487 
1488 #ifdef CONFIG_KALLSYMS
1489 struct module_sect_attr {
1490 	struct bin_attribute battr;
1491 	unsigned long address;
1492 };
1493 
1494 struct module_sect_attrs {
1495 	struct attribute_group grp;
1496 	unsigned int nsections;
1497 	struct module_sect_attr attrs[];
1498 };
1499 
1500 #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)1501 static ssize_t module_sect_read(struct file *file, struct kobject *kobj,
1502 				struct bin_attribute *battr,
1503 				char *buf, loff_t pos, size_t count)
1504 {
1505 	struct module_sect_attr *sattr =
1506 		container_of(battr, struct module_sect_attr, battr);
1507 	char bounce[MODULE_SECT_READ_SIZE + 1];
1508 	size_t wrote;
1509 
1510 	if (pos != 0)
1511 		return -EINVAL;
1512 
1513 	/*
1514 	 * Since we're a binary read handler, we must account for the
1515 	 * trailing NUL byte that sprintf will write: if "buf" is
1516 	 * too small to hold the NUL, or the NUL is exactly the last
1517 	 * byte, the read will look like it got truncated by one byte.
1518 	 * Since there is no way to ask sprintf nicely to not write
1519 	 * the NUL, we have to use a bounce buffer.
1520 	 */
1521 	wrote = scnprintf(bounce, sizeof(bounce), "0x%px\n",
1522 			 kallsyms_show_value(file->f_cred)
1523 				? (void *)sattr->address : NULL);
1524 	count = min(count, wrote);
1525 	memcpy(buf, bounce, count);
1526 
1527 	return count;
1528 }
1529 
free_sect_attrs(struct module_sect_attrs * sect_attrs)1530 static void free_sect_attrs(struct module_sect_attrs *sect_attrs)
1531 {
1532 	unsigned int section;
1533 
1534 	for (section = 0; section < sect_attrs->nsections; section++)
1535 		kfree(sect_attrs->attrs[section].battr.attr.name);
1536 	kfree(sect_attrs);
1537 }
1538 
add_sect_attrs(struct module * mod,const struct load_info * info)1539 static void add_sect_attrs(struct module *mod, const struct load_info *info)
1540 {
1541 	unsigned int nloaded = 0, i, size[2];
1542 	struct module_sect_attrs *sect_attrs;
1543 	struct module_sect_attr *sattr;
1544 	struct bin_attribute **gattr;
1545 
1546 	/* Count loaded sections and allocate structures */
1547 	for (i = 0; i < info->hdr->e_shnum; i++)
1548 		if (!sect_empty(&info->sechdrs[i]))
1549 			nloaded++;
1550 	size[0] = ALIGN(struct_size(sect_attrs, attrs, nloaded),
1551 			sizeof(sect_attrs->grp.bin_attrs[0]));
1552 	size[1] = (nloaded + 1) * sizeof(sect_attrs->grp.bin_attrs[0]);
1553 	sect_attrs = kzalloc(size[0] + size[1], GFP_KERNEL);
1554 	if (sect_attrs == NULL)
1555 		return;
1556 
1557 	/* Setup section attributes. */
1558 	sect_attrs->grp.name = "sections";
1559 	sect_attrs->grp.bin_attrs = (void *)sect_attrs + size[0];
1560 
1561 	sect_attrs->nsections = 0;
1562 	sattr = &sect_attrs->attrs[0];
1563 	gattr = &sect_attrs->grp.bin_attrs[0];
1564 	for (i = 0; i < info->hdr->e_shnum; i++) {
1565 		Elf_Shdr *sec = &info->sechdrs[i];
1566 		if (sect_empty(sec))
1567 			continue;
1568 		sysfs_bin_attr_init(&sattr->battr);
1569 		sattr->address = sec->sh_addr;
1570 		sattr->battr.attr.name =
1571 			kstrdup(info->secstrings + sec->sh_name, GFP_KERNEL);
1572 		if (sattr->battr.attr.name == NULL)
1573 			goto out;
1574 		sect_attrs->nsections++;
1575 		sattr->battr.read = module_sect_read;
1576 		sattr->battr.size = MODULE_SECT_READ_SIZE;
1577 		sattr->battr.attr.mode = 0400;
1578 		*(gattr++) = &(sattr++)->battr;
1579 	}
1580 	*gattr = NULL;
1581 
1582 	if (sysfs_create_group(&mod->mkobj.kobj, &sect_attrs->grp))
1583 		goto out;
1584 
1585 	mod->sect_attrs = sect_attrs;
1586 	return;
1587   out:
1588 	free_sect_attrs(sect_attrs);
1589 }
1590 
remove_sect_attrs(struct module * mod)1591 static void remove_sect_attrs(struct module *mod)
1592 {
1593 	if (mod->sect_attrs) {
1594 		sysfs_remove_group(&mod->mkobj.kobj,
1595 				   &mod->sect_attrs->grp);
1596 		/*
1597 		 * We are positive that no one is using any sect attrs
1598 		 * at this point.  Deallocate immediately.
1599 		 */
1600 		free_sect_attrs(mod->sect_attrs);
1601 		mod->sect_attrs = NULL;
1602 	}
1603 }
1604 
1605 /*
1606  * /sys/module/foo/notes/.section.name gives contents of SHT_NOTE sections.
1607  */
1608 
1609 struct module_notes_attrs {
1610 	struct kobject *dir;
1611 	unsigned int notes;
1612 	struct bin_attribute attrs[];
1613 };
1614 
module_notes_read(struct file * filp,struct kobject * kobj,struct bin_attribute * bin_attr,char * buf,loff_t pos,size_t count)1615 static ssize_t module_notes_read(struct file *filp, struct kobject *kobj,
1616 				 struct bin_attribute *bin_attr,
1617 				 char *buf, loff_t pos, size_t count)
1618 {
1619 	/*
1620 	 * The caller checked the pos and count against our size.
1621 	 */
1622 	memcpy(buf, bin_attr->private + pos, count);
1623 	return count;
1624 }
1625 
free_notes_attrs(struct module_notes_attrs * notes_attrs,unsigned int i)1626 static void free_notes_attrs(struct module_notes_attrs *notes_attrs,
1627 			     unsigned int i)
1628 {
1629 	if (notes_attrs->dir) {
1630 		while (i-- > 0)
1631 			sysfs_remove_bin_file(notes_attrs->dir,
1632 					      &notes_attrs->attrs[i]);
1633 		kobject_put(notes_attrs->dir);
1634 	}
1635 	kfree(notes_attrs);
1636 }
1637 
add_notes_attrs(struct module * mod,const struct load_info * info)1638 static void add_notes_attrs(struct module *mod, const struct load_info *info)
1639 {
1640 	unsigned int notes, loaded, i;
1641 	struct module_notes_attrs *notes_attrs;
1642 	struct bin_attribute *nattr;
1643 
1644 	/* failed to create section attributes, so can't create notes */
1645 	if (!mod->sect_attrs)
1646 		return;
1647 
1648 	/* Count notes sections and allocate structures.  */
1649 	notes = 0;
1650 	for (i = 0; i < info->hdr->e_shnum; i++)
1651 		if (!sect_empty(&info->sechdrs[i]) &&
1652 		    (info->sechdrs[i].sh_type == SHT_NOTE))
1653 			++notes;
1654 
1655 	if (notes == 0)
1656 		return;
1657 
1658 	notes_attrs = kzalloc(struct_size(notes_attrs, attrs, notes),
1659 			      GFP_KERNEL);
1660 	if (notes_attrs == NULL)
1661 		return;
1662 
1663 	notes_attrs->notes = notes;
1664 	nattr = &notes_attrs->attrs[0];
1665 	for (loaded = i = 0; i < info->hdr->e_shnum; ++i) {
1666 		if (sect_empty(&info->sechdrs[i]))
1667 			continue;
1668 		if (info->sechdrs[i].sh_type == SHT_NOTE) {
1669 			sysfs_bin_attr_init(nattr);
1670 			nattr->attr.name = mod->sect_attrs->attrs[loaded].battr.attr.name;
1671 			nattr->attr.mode = S_IRUGO;
1672 			nattr->size = info->sechdrs[i].sh_size;
1673 			nattr->private = (void *) info->sechdrs[i].sh_addr;
1674 			nattr->read = module_notes_read;
1675 			++nattr;
1676 		}
1677 		++loaded;
1678 	}
1679 
1680 	notes_attrs->dir = kobject_create_and_add("notes", &mod->mkobj.kobj);
1681 	if (!notes_attrs->dir)
1682 		goto out;
1683 
1684 	for (i = 0; i < notes; ++i)
1685 		if (sysfs_create_bin_file(notes_attrs->dir,
1686 					  &notes_attrs->attrs[i]))
1687 			goto out;
1688 
1689 	mod->notes_attrs = notes_attrs;
1690 	return;
1691 
1692   out:
1693 	free_notes_attrs(notes_attrs, i);
1694 }
1695 
remove_notes_attrs(struct module * mod)1696 static void remove_notes_attrs(struct module *mod)
1697 {
1698 	if (mod->notes_attrs)
1699 		free_notes_attrs(mod->notes_attrs, mod->notes_attrs->notes);
1700 }
1701 
1702 #else
1703 
add_sect_attrs(struct module * mod,const struct load_info * info)1704 static inline void add_sect_attrs(struct module *mod,
1705 				  const struct load_info *info)
1706 {
1707 }
1708 
remove_sect_attrs(struct module * mod)1709 static inline void remove_sect_attrs(struct module *mod)
1710 {
1711 }
1712 
add_notes_attrs(struct module * mod,const struct load_info * info)1713 static inline void add_notes_attrs(struct module *mod,
1714 				   const struct load_info *info)
1715 {
1716 }
1717 
remove_notes_attrs(struct module * mod)1718 static inline void remove_notes_attrs(struct module *mod)
1719 {
1720 }
1721 #endif /* CONFIG_KALLSYMS */
1722 
del_usage_links(struct module * mod)1723 static void del_usage_links(struct module *mod)
1724 {
1725 #ifdef CONFIG_MODULE_UNLOAD
1726 	struct module_use *use;
1727 
1728 	mutex_lock(&module_mutex);
1729 	list_for_each_entry(use, &mod->target_list, target_list)
1730 		sysfs_remove_link(use->target->holders_dir, mod->name);
1731 	mutex_unlock(&module_mutex);
1732 #endif
1733 }
1734 
add_usage_links(struct module * mod)1735 static int add_usage_links(struct module *mod)
1736 {
1737 	int ret = 0;
1738 #ifdef CONFIG_MODULE_UNLOAD
1739 	struct module_use *use;
1740 
1741 	mutex_lock(&module_mutex);
1742 	list_for_each_entry(use, &mod->target_list, target_list) {
1743 		ret = sysfs_create_link(use->target->holders_dir,
1744 					&mod->mkobj.kobj, mod->name);
1745 		if (ret)
1746 			break;
1747 	}
1748 	mutex_unlock(&module_mutex);
1749 	if (ret)
1750 		del_usage_links(mod);
1751 #endif
1752 	return ret;
1753 }
1754 
1755 static void module_remove_modinfo_attrs(struct module *mod, int end);
1756 
module_add_modinfo_attrs(struct module * mod)1757 static int module_add_modinfo_attrs(struct module *mod)
1758 {
1759 	struct module_attribute *attr;
1760 	struct module_attribute *temp_attr;
1761 	int error = 0;
1762 	int i;
1763 
1764 	mod->modinfo_attrs = kzalloc((sizeof(struct module_attribute) *
1765 					(ARRAY_SIZE(modinfo_attrs) + 1)),
1766 					GFP_KERNEL);
1767 	if (!mod->modinfo_attrs)
1768 		return -ENOMEM;
1769 
1770 	temp_attr = mod->modinfo_attrs;
1771 	for (i = 0; (attr = modinfo_attrs[i]); i++) {
1772 		if (!attr->test || attr->test(mod)) {
1773 			memcpy(temp_attr, attr, sizeof(*temp_attr));
1774 			sysfs_attr_init(&temp_attr->attr);
1775 			error = sysfs_create_file(&mod->mkobj.kobj,
1776 					&temp_attr->attr);
1777 			if (error)
1778 				goto error_out;
1779 			++temp_attr;
1780 		}
1781 	}
1782 
1783 	return 0;
1784 
1785 error_out:
1786 	if (i > 0)
1787 		module_remove_modinfo_attrs(mod, --i);
1788 	else
1789 		kfree(mod->modinfo_attrs);
1790 	return error;
1791 }
1792 
module_remove_modinfo_attrs(struct module * mod,int end)1793 static void module_remove_modinfo_attrs(struct module *mod, int end)
1794 {
1795 	struct module_attribute *attr;
1796 	int i;
1797 
1798 	for (i = 0; (attr = &mod->modinfo_attrs[i]); i++) {
1799 		if (end >= 0 && i > end)
1800 			break;
1801 		/* pick a field to test for end of list */
1802 		if (!attr->attr.name)
1803 			break;
1804 		sysfs_remove_file(&mod->mkobj.kobj, &attr->attr);
1805 		if (attr->free)
1806 			attr->free(mod);
1807 	}
1808 	kfree(mod->modinfo_attrs);
1809 }
1810 
mod_kobject_put(struct module * mod)1811 static void mod_kobject_put(struct module *mod)
1812 {
1813 	DECLARE_COMPLETION_ONSTACK(c);
1814 	mod->mkobj.kobj_completion = &c;
1815 	kobject_put(&mod->mkobj.kobj);
1816 	wait_for_completion(&c);
1817 }
1818 
mod_sysfs_init(struct module * mod)1819 static int mod_sysfs_init(struct module *mod)
1820 {
1821 	int err;
1822 	struct kobject *kobj;
1823 
1824 	if (!module_sysfs_initialized) {
1825 		pr_err("%s: module sysfs not initialized\n", mod->name);
1826 		err = -EINVAL;
1827 		goto out;
1828 	}
1829 
1830 	kobj = kset_find_obj(module_kset, mod->name);
1831 	if (kobj) {
1832 		pr_err("%s: module is already loaded\n", mod->name);
1833 		kobject_put(kobj);
1834 		err = -EINVAL;
1835 		goto out;
1836 	}
1837 
1838 	mod->mkobj.mod = mod;
1839 
1840 	memset(&mod->mkobj.kobj, 0, sizeof(mod->mkobj.kobj));
1841 	mod->mkobj.kobj.kset = module_kset;
1842 	err = kobject_init_and_add(&mod->mkobj.kobj, &module_ktype, NULL,
1843 				   "%s", mod->name);
1844 	if (err)
1845 		mod_kobject_put(mod);
1846 
1847 out:
1848 	return err;
1849 }
1850 
mod_sysfs_setup(struct module * mod,const struct load_info * info,struct kernel_param * kparam,unsigned int num_params)1851 static int mod_sysfs_setup(struct module *mod,
1852 			   const struct load_info *info,
1853 			   struct kernel_param *kparam,
1854 			   unsigned int num_params)
1855 {
1856 	int err;
1857 
1858 	err = mod_sysfs_init(mod);
1859 	if (err)
1860 		goto out;
1861 
1862 	mod->holders_dir = kobject_create_and_add("holders", &mod->mkobj.kobj);
1863 	if (!mod->holders_dir) {
1864 		err = -ENOMEM;
1865 		goto out_unreg;
1866 	}
1867 
1868 	err = module_param_sysfs_setup(mod, kparam, num_params);
1869 	if (err)
1870 		goto out_unreg_holders;
1871 
1872 	err = module_add_modinfo_attrs(mod);
1873 	if (err)
1874 		goto out_unreg_param;
1875 
1876 	err = add_usage_links(mod);
1877 	if (err)
1878 		goto out_unreg_modinfo_attrs;
1879 
1880 	add_sect_attrs(mod, info);
1881 	add_notes_attrs(mod, info);
1882 
1883 	return 0;
1884 
1885 out_unreg_modinfo_attrs:
1886 	module_remove_modinfo_attrs(mod, -1);
1887 out_unreg_param:
1888 	module_param_sysfs_remove(mod);
1889 out_unreg_holders:
1890 	kobject_put(mod->holders_dir);
1891 out_unreg:
1892 	mod_kobject_put(mod);
1893 out:
1894 	return err;
1895 }
1896 
mod_sysfs_fini(struct module * mod)1897 static void mod_sysfs_fini(struct module *mod)
1898 {
1899 	remove_notes_attrs(mod);
1900 	remove_sect_attrs(mod);
1901 	mod_kobject_put(mod);
1902 }
1903 
init_param_lock(struct module * mod)1904 static void init_param_lock(struct module *mod)
1905 {
1906 	mutex_init(&mod->param_lock);
1907 }
1908 #else /* !CONFIG_SYSFS */
1909 
mod_sysfs_setup(struct module * mod,const struct load_info * info,struct kernel_param * kparam,unsigned int num_params)1910 static int mod_sysfs_setup(struct module *mod,
1911 			   const struct load_info *info,
1912 			   struct kernel_param *kparam,
1913 			   unsigned int num_params)
1914 {
1915 	return 0;
1916 }
1917 
mod_sysfs_fini(struct module * mod)1918 static void mod_sysfs_fini(struct module *mod)
1919 {
1920 }
1921 
module_remove_modinfo_attrs(struct module * mod,int end)1922 static void module_remove_modinfo_attrs(struct module *mod, int end)
1923 {
1924 }
1925 
del_usage_links(struct module * mod)1926 static void del_usage_links(struct module *mod)
1927 {
1928 }
1929 
init_param_lock(struct module * mod)1930 static void init_param_lock(struct module *mod)
1931 {
1932 }
1933 #endif /* CONFIG_SYSFS */
1934 
mod_sysfs_teardown(struct module * mod)1935 static void mod_sysfs_teardown(struct module *mod)
1936 {
1937 	del_usage_links(mod);
1938 	module_remove_modinfo_attrs(mod, -1);
1939 	module_param_sysfs_remove(mod);
1940 	kobject_put(mod->mkobj.drivers_dir);
1941 	kobject_put(mod->holders_dir);
1942 	mod_sysfs_fini(mod);
1943 }
1944 
1945 /*
1946  * LKM RO/NX protection: protect module's text/ro-data
1947  * from modification and any data from execution.
1948  *
1949  * General layout of module is:
1950  *          [text] [read-only-data] [ro-after-init] [writable data]
1951  * text_size -----^                ^               ^               ^
1952  * ro_size ------------------------|               |               |
1953  * ro_after_init_size -----------------------------|               |
1954  * size -----------------------------------------------------------|
1955  *
1956  * These values are always page-aligned (as is base)
1957  */
1958 
1959 /*
1960  * Since some arches are moving towards PAGE_KERNEL module allocations instead
1961  * of PAGE_KERNEL_EXEC, keep frob_text() and module_enable_x() outside of the
1962  * CONFIG_STRICT_MODULE_RWX block below because they are needed regardless of
1963  * whether we are strict.
1964  */
1965 #ifdef CONFIG_ARCH_HAS_STRICT_MODULE_RWX
frob_text(const struct module_layout * layout,int (* set_memory)(unsigned long start,int num_pages))1966 static void frob_text(const struct module_layout *layout,
1967 		      int (*set_memory)(unsigned long start, int num_pages))
1968 {
1969 	BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
1970 	BUG_ON((unsigned long)layout->text_size & (PAGE_SIZE-1));
1971 	set_memory((unsigned long)layout->base,
1972 		   layout->text_size >> PAGE_SHIFT);
1973 }
1974 
module_enable_x(const struct module * mod)1975 static void module_enable_x(const struct module *mod)
1976 {
1977 	frob_text(&mod->core_layout, set_memory_x);
1978 	frob_text(&mod->init_layout, set_memory_x);
1979 }
1980 #else /* !CONFIG_ARCH_HAS_STRICT_MODULE_RWX */
module_enable_x(const struct module * mod)1981 static void module_enable_x(const struct module *mod) { }
1982 #endif /* CONFIG_ARCH_HAS_STRICT_MODULE_RWX */
1983 
1984 #ifdef CONFIG_STRICT_MODULE_RWX
frob_rodata(const struct module_layout * layout,int (* set_memory)(unsigned long start,int num_pages))1985 static void frob_rodata(const struct module_layout *layout,
1986 			int (*set_memory)(unsigned long start, int num_pages))
1987 {
1988 	BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
1989 	BUG_ON((unsigned long)layout->text_size & (PAGE_SIZE-1));
1990 	BUG_ON((unsigned long)layout->ro_size & (PAGE_SIZE-1));
1991 	set_memory((unsigned long)layout->base + layout->text_size,
1992 		   (layout->ro_size - layout->text_size) >> PAGE_SHIFT);
1993 }
1994 
frob_ro_after_init(const struct module_layout * layout,int (* set_memory)(unsigned long start,int num_pages))1995 static void frob_ro_after_init(const struct module_layout *layout,
1996 				int (*set_memory)(unsigned long start, int num_pages))
1997 {
1998 	BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
1999 	BUG_ON((unsigned long)layout->ro_size & (PAGE_SIZE-1));
2000 	BUG_ON((unsigned long)layout->ro_after_init_size & (PAGE_SIZE-1));
2001 	set_memory((unsigned long)layout->base + layout->ro_size,
2002 		   (layout->ro_after_init_size - layout->ro_size) >> PAGE_SHIFT);
2003 }
2004 
frob_writable_data(const struct module_layout * layout,int (* set_memory)(unsigned long start,int num_pages))2005 static void frob_writable_data(const struct module_layout *layout,
2006 			       int (*set_memory)(unsigned long start, int num_pages))
2007 {
2008 	BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
2009 	BUG_ON((unsigned long)layout->ro_after_init_size & (PAGE_SIZE-1));
2010 	BUG_ON((unsigned long)layout->size & (PAGE_SIZE-1));
2011 	set_memory((unsigned long)layout->base + layout->ro_after_init_size,
2012 		   (layout->size - layout->ro_after_init_size) >> PAGE_SHIFT);
2013 }
2014 
module_enable_ro(const struct module * mod,bool after_init)2015 static void module_enable_ro(const struct module *mod, bool after_init)
2016 {
2017 	if (!rodata_enabled)
2018 		return;
2019 
2020 	set_vm_flush_reset_perms(mod->core_layout.base);
2021 	set_vm_flush_reset_perms(mod->init_layout.base);
2022 	frob_text(&mod->core_layout, set_memory_ro);
2023 
2024 	frob_rodata(&mod->core_layout, set_memory_ro);
2025 	frob_text(&mod->init_layout, set_memory_ro);
2026 	frob_rodata(&mod->init_layout, set_memory_ro);
2027 
2028 	if (after_init)
2029 		frob_ro_after_init(&mod->core_layout, set_memory_ro);
2030 }
2031 
module_enable_nx(const struct module * mod)2032 static void module_enable_nx(const struct module *mod)
2033 {
2034 	frob_rodata(&mod->core_layout, set_memory_nx);
2035 	frob_ro_after_init(&mod->core_layout, set_memory_nx);
2036 	frob_writable_data(&mod->core_layout, set_memory_nx);
2037 	frob_rodata(&mod->init_layout, set_memory_nx);
2038 	frob_writable_data(&mod->init_layout, set_memory_nx);
2039 }
2040 
module_enforce_rwx_sections(Elf_Ehdr * hdr,Elf_Shdr * sechdrs,char * secstrings,struct module * mod)2041 static int module_enforce_rwx_sections(Elf_Ehdr *hdr, Elf_Shdr *sechdrs,
2042 				       char *secstrings, struct module *mod)
2043 {
2044 	const unsigned long shf_wx = SHF_WRITE|SHF_EXECINSTR;
2045 	int i;
2046 
2047 	for (i = 0; i < hdr->e_shnum; i++) {
2048 		if ((sechdrs[i].sh_flags & shf_wx) == shf_wx) {
2049 			pr_err("%s: section %s (index %d) has invalid WRITE|EXEC flags\n",
2050 				mod->name, secstrings + sechdrs[i].sh_name, i);
2051 			return -ENOEXEC;
2052 		}
2053 	}
2054 
2055 	return 0;
2056 }
2057 
2058 #else /* !CONFIG_STRICT_MODULE_RWX */
module_enable_nx(const struct module * mod)2059 static void module_enable_nx(const struct module *mod) { }
module_enable_ro(const struct module * mod,bool after_init)2060 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)2061 static int module_enforce_rwx_sections(Elf_Ehdr *hdr, Elf_Shdr *sechdrs,
2062 				       char *secstrings, struct module *mod)
2063 {
2064 	return 0;
2065 }
2066 #endif /*  CONFIG_STRICT_MODULE_RWX */
2067 
2068 #ifdef CONFIG_LIVEPATCH
2069 /*
2070  * Persist Elf information about a module. Copy the Elf header,
2071  * section header table, section string table, and symtab section
2072  * index from info to mod->klp_info.
2073  */
copy_module_elf(struct module * mod,struct load_info * info)2074 static int copy_module_elf(struct module *mod, struct load_info *info)
2075 {
2076 	unsigned int size, symndx;
2077 	int ret;
2078 
2079 	size = sizeof(*mod->klp_info);
2080 	mod->klp_info = kmalloc(size, GFP_KERNEL);
2081 	if (mod->klp_info == NULL)
2082 		return -ENOMEM;
2083 
2084 	/* Elf header */
2085 	size = sizeof(mod->klp_info->hdr);
2086 	memcpy(&mod->klp_info->hdr, info->hdr, size);
2087 
2088 	/* Elf section header table */
2089 	size = sizeof(*info->sechdrs) * info->hdr->e_shnum;
2090 	mod->klp_info->sechdrs = kmemdup(info->sechdrs, size, GFP_KERNEL);
2091 	if (mod->klp_info->sechdrs == NULL) {
2092 		ret = -ENOMEM;
2093 		goto free_info;
2094 	}
2095 
2096 	/* Elf section name string table */
2097 	size = info->sechdrs[info->hdr->e_shstrndx].sh_size;
2098 	mod->klp_info->secstrings = kmemdup(info->secstrings, size, GFP_KERNEL);
2099 	if (mod->klp_info->secstrings == NULL) {
2100 		ret = -ENOMEM;
2101 		goto free_sechdrs;
2102 	}
2103 
2104 	/* Elf symbol section index */
2105 	symndx = info->index.sym;
2106 	mod->klp_info->symndx = symndx;
2107 
2108 	/*
2109 	 * For livepatch modules, core_kallsyms.symtab is a complete
2110 	 * copy of the original symbol table. Adjust sh_addr to point
2111 	 * to core_kallsyms.symtab since the copy of the symtab in module
2112 	 * init memory is freed at the end of do_init_module().
2113 	 */
2114 	mod->klp_info->sechdrs[symndx].sh_addr = \
2115 		(unsigned long) mod->core_kallsyms.symtab;
2116 
2117 	return 0;
2118 
2119 free_sechdrs:
2120 	kfree(mod->klp_info->sechdrs);
2121 free_info:
2122 	kfree(mod->klp_info);
2123 	return ret;
2124 }
2125 
free_module_elf(struct module * mod)2126 static void free_module_elf(struct module *mod)
2127 {
2128 	kfree(mod->klp_info->sechdrs);
2129 	kfree(mod->klp_info->secstrings);
2130 	kfree(mod->klp_info);
2131 }
2132 #else /* !CONFIG_LIVEPATCH */
copy_module_elf(struct module * mod,struct load_info * info)2133 static int copy_module_elf(struct module *mod, struct load_info *info)
2134 {
2135 	return 0;
2136 }
2137 
free_module_elf(struct module * mod)2138 static void free_module_elf(struct module *mod)
2139 {
2140 }
2141 #endif /* CONFIG_LIVEPATCH */
2142 
module_memfree(void * module_region)2143 void __weak module_memfree(void *module_region)
2144 {
2145 	/*
2146 	 * This memory may be RO, and freeing RO memory in an interrupt is not
2147 	 * supported by vmalloc.
2148 	 */
2149 	WARN_ON(in_interrupt());
2150 	vfree(module_region);
2151 }
2152 
module_arch_cleanup(struct module * mod)2153 void __weak module_arch_cleanup(struct module *mod)
2154 {
2155 }
2156 
module_arch_freeing_init(struct module * mod)2157 void __weak module_arch_freeing_init(struct module *mod)
2158 {
2159 }
2160 
2161 static void cfi_cleanup(struct module *mod);
2162 
2163 /* Free a module, remove from lists, etc. */
free_module(struct module * mod)2164 static void free_module(struct module *mod)
2165 {
2166 	trace_module_free(mod);
2167 
2168 	mod_sysfs_teardown(mod);
2169 
2170 	/*
2171 	 * We leave it in list to prevent duplicate loads, but make sure
2172 	 * that noone uses it while it's being deconstructed.
2173 	 */
2174 	mutex_lock(&module_mutex);
2175 	mod->state = MODULE_STATE_UNFORMED;
2176 	mutex_unlock(&module_mutex);
2177 
2178 	/* Remove dynamic debug info */
2179 	ddebug_remove_module(mod->name);
2180 
2181 	/* Arch-specific cleanup. */
2182 	module_arch_cleanup(mod);
2183 
2184 	/* Module unload stuff */
2185 	module_unload_free(mod);
2186 
2187 	/* Free any allocated parameters. */
2188 	destroy_params(mod->kp, mod->num_kp);
2189 
2190 	if (is_livepatch_module(mod))
2191 		free_module_elf(mod);
2192 
2193 	/* Now we can delete it from the lists */
2194 	mutex_lock(&module_mutex);
2195 	/* Unlink carefully: kallsyms could be walking list. */
2196 	list_del_rcu(&mod->list);
2197 	mod_tree_remove(mod);
2198 	/* Remove this module from bug list, this uses list_del_rcu */
2199 	module_bug_cleanup(mod);
2200 	/* Wait for RCU-sched synchronizing before releasing mod->list and buglist. */
2201 	synchronize_rcu();
2202 	mutex_unlock(&module_mutex);
2203 
2204 	/* Clean up CFI for the module. */
2205 	cfi_cleanup(mod);
2206 
2207 	/* This may be empty, but that's OK */
2208 	module_arch_freeing_init(mod);
2209 	trace_android_vh_set_memory_rw((unsigned long)mod->init_layout.base,
2210 		(mod->init_layout.size)>>PAGE_SHIFT);
2211 	trace_android_vh_set_memory_nx((unsigned long)mod->init_layout.base,
2212 		(mod->init_layout.size)>>PAGE_SHIFT);
2213 	module_memfree(mod->init_layout.base);
2214 	kfree(mod->args);
2215 	percpu_modfree(mod);
2216 
2217 	/* Free lock-classes; relies on the preceding sync_rcu(). */
2218 	lockdep_free_key_range(mod->core_layout.base, mod->core_layout.size);
2219 
2220 	/* Finally, free the core (containing the module structure) */
2221 	trace_android_vh_set_memory_rw((unsigned long)mod->core_layout.base,
2222 		(mod->core_layout.size)>>PAGE_SHIFT);
2223 	trace_android_vh_set_memory_nx((unsigned long)mod->core_layout.base,
2224 		(mod->core_layout.size)>>PAGE_SHIFT);
2225 	module_memfree(mod->core_layout.base);
2226 }
2227 
__symbol_get(const char * symbol)2228 void *__symbol_get(const char *symbol)
2229 {
2230 	struct find_symbol_arg fsa = {
2231 		.name	= symbol,
2232 		.gplok	= true,
2233 		.warn	= true,
2234 	};
2235 
2236 	preempt_disable();
2237 	if (!find_symbol(&fsa))
2238 		goto fail;
2239 	if (fsa.license != GPL_ONLY) {
2240 		pr_warn("failing symbol_get of non-GPLONLY symbol %s.\n",
2241 			symbol);
2242 		goto fail;
2243 	}
2244 	if (strong_try_module_get(fsa.owner))
2245 		goto fail;
2246 	preempt_enable();
2247 	return (void *)kernel_symbol_value(fsa.sym);
2248 fail:
2249 	preempt_enable();
2250 	return NULL;
2251 }
2252 EXPORT_SYMBOL_GPL(__symbol_get);
2253 
2254 /*
2255  * Ensure that an exported symbol [global namespace] does not already exist
2256  * in the kernel or in some other module's exported symbol table.
2257  *
2258  * You must hold the module_mutex.
2259  */
verify_exported_symbols(struct module * mod)2260 static int verify_exported_symbols(struct module *mod)
2261 {
2262 	unsigned int i;
2263 	const struct kernel_symbol *s;
2264 	struct {
2265 		const struct kernel_symbol *sym;
2266 		unsigned int num;
2267 	} arr[] = {
2268 		{ mod->syms, mod->num_syms },
2269 		{ mod->gpl_syms, mod->num_gpl_syms },
2270 	};
2271 
2272 	for (i = 0; i < ARRAY_SIZE(arr); i++) {
2273 		for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
2274 			struct find_symbol_arg fsa = {
2275 				.name	= kernel_symbol_name(s),
2276 				.gplok	= true,
2277 			};
2278 
2279 			if (!mod->sig_ok && gki_is_module_exported_symbol(
2280 						    kernel_symbol_name(s))) {
2281 				pr_err("%s: exporting protected symbol(%s)\n",
2282 				       mod->name, kernel_symbol_name(s));
2283 				return -EACCES;
2284 			}
2285 
2286 			if (find_symbol(&fsa)) {
2287 				pr_err("%s: exports duplicate symbol %s"
2288 				       " (owned by %s)\n",
2289 				       mod->name, kernel_symbol_name(s),
2290 				       module_name(fsa.owner));
2291 				return -ENOEXEC;
2292 			}
2293 		}
2294 	}
2295 	return 0;
2296 }
2297 
ignore_undef_symbol(Elf_Half emachine,const char * name)2298 static bool ignore_undef_symbol(Elf_Half emachine, const char *name)
2299 {
2300 	/*
2301 	 * On x86, PIC code and Clang non-PIC code may have call foo@PLT. GNU as
2302 	 * before 2.37 produces an unreferenced _GLOBAL_OFFSET_TABLE_ on x86-64.
2303 	 * i386 has a similar problem but may not deserve a fix.
2304 	 *
2305 	 * If we ever have to ignore many symbols, consider refactoring the code to
2306 	 * only warn if referenced by a relocation.
2307 	 */
2308 	if (emachine == EM_386 || emachine == EM_X86_64)
2309 		return !strcmp(name, "_GLOBAL_OFFSET_TABLE_");
2310 	return false;
2311 }
2312 
2313 /* Change all symbols so that st_value encodes the pointer directly. */
simplify_symbols(struct module * mod,const struct load_info * info)2314 static int simplify_symbols(struct module *mod, const struct load_info *info)
2315 {
2316 	Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2317 	Elf_Sym *sym = (void *)symsec->sh_addr;
2318 	unsigned long secbase;
2319 	unsigned int i;
2320 	int ret = 0;
2321 	const struct kernel_symbol *ksym;
2322 
2323 	for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
2324 		const char *name = info->strtab + sym[i].st_name;
2325 
2326 		switch (sym[i].st_shndx) {
2327 		case SHN_COMMON:
2328 			/* Ignore common symbols */
2329 			if (!strncmp(name, "__gnu_lto", 9))
2330 				break;
2331 
2332 			/*
2333 			 * We compiled with -fno-common.  These are not
2334 			 * supposed to happen.
2335 			 */
2336 			pr_debug("Common symbol: %s\n", name);
2337 			pr_warn("%s: please compile with -fno-common\n",
2338 			       mod->name);
2339 			ret = -ENOEXEC;
2340 			break;
2341 
2342 		case SHN_ABS:
2343 			/* Don't need to do anything */
2344 			pr_debug("Absolute symbol: 0x%08lx\n",
2345 			       (long)sym[i].st_value);
2346 			break;
2347 
2348 		case SHN_LIVEPATCH:
2349 			/* Livepatch symbols are resolved by livepatch */
2350 			break;
2351 
2352 		case SHN_UNDEF:
2353 			if (!mod->sig_ok &&
2354 			    gki_is_module_protected_symbol(name)) {
2355 				pr_err("%s: is not an Android GKI signed module. It can not access protected symbol: %s\n",
2356 				       mod->name, name);
2357 				return -EACCES;
2358 			}
2359 
2360 			ksym = resolve_symbol_wait(mod, info, name);
2361 			/* Ok if resolved.  */
2362 			if (ksym && !IS_ERR(ksym)) {
2363 				sym[i].st_value = kernel_symbol_value(ksym);
2364 				break;
2365 			}
2366 
2367 			/* Ok if weak or ignored.  */
2368 			if (!ksym &&
2369 			    (ELF_ST_BIND(sym[i].st_info) == STB_WEAK ||
2370 			     ignore_undef_symbol(info->hdr->e_machine, name)))
2371 				break;
2372 
2373 			ret = PTR_ERR(ksym) ?: -ENOENT;
2374 			pr_warn("%s: Unknown symbol %s (err %d)\n",
2375 				mod->name, name, ret);
2376 			break;
2377 
2378 		default:
2379 			/* Divert to percpu allocation if a percpu var. */
2380 			if (sym[i].st_shndx == info->index.pcpu)
2381 				secbase = (unsigned long)mod_percpu(mod);
2382 			else
2383 				secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
2384 			sym[i].st_value += secbase;
2385 			break;
2386 		}
2387 	}
2388 
2389 	return ret;
2390 }
2391 
apply_relocations(struct module * mod,const struct load_info * info)2392 static int apply_relocations(struct module *mod, const struct load_info *info)
2393 {
2394 	unsigned int i;
2395 	int err = 0;
2396 
2397 	/* Now do relocations. */
2398 	for (i = 1; i < info->hdr->e_shnum; i++) {
2399 		unsigned int infosec = info->sechdrs[i].sh_info;
2400 
2401 		/* Not a valid relocation section? */
2402 		if (infosec >= info->hdr->e_shnum)
2403 			continue;
2404 
2405 		/* Don't bother with non-allocated sections */
2406 		if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
2407 			continue;
2408 
2409 		if (info->sechdrs[i].sh_flags & SHF_RELA_LIVEPATCH)
2410 			err = klp_apply_section_relocs(mod, info->sechdrs,
2411 						       info->secstrings,
2412 						       info->strtab,
2413 						       info->index.sym, i,
2414 						       NULL);
2415 		else if (info->sechdrs[i].sh_type == SHT_REL)
2416 			err = apply_relocate(info->sechdrs, info->strtab,
2417 					     info->index.sym, i, mod);
2418 		else if (info->sechdrs[i].sh_type == SHT_RELA)
2419 			err = apply_relocate_add(info->sechdrs, info->strtab,
2420 						 info->index.sym, i, mod);
2421 		if (err < 0)
2422 			break;
2423 	}
2424 	return err;
2425 }
2426 
2427 /* Additional bytes needed by arch in front of individual sections */
arch_mod_section_prepend(struct module * mod,unsigned int section)2428 unsigned int __weak arch_mod_section_prepend(struct module *mod,
2429 					     unsigned int section)
2430 {
2431 	/* default implementation just returns zero */
2432 	return 0;
2433 }
2434 
2435 /* Update size with this section: return offset. */
get_offset(struct module * mod,unsigned int * size,Elf_Shdr * sechdr,unsigned int section)2436 static long get_offset(struct module *mod, unsigned int *size,
2437 		       Elf_Shdr *sechdr, unsigned int section)
2438 {
2439 	long ret;
2440 
2441 	*size += arch_mod_section_prepend(mod, section);
2442 	ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
2443 	*size = ret + sechdr->sh_size;
2444 	return ret;
2445 }
2446 
module_init_layout_section(const char * sname)2447 bool module_init_layout_section(const char *sname)
2448 {
2449 #ifndef CONFIG_MODULE_UNLOAD
2450 	if (module_exit_section(sname))
2451 		return true;
2452 #endif
2453 	return module_init_section(sname);
2454 }
2455 
2456 /*
2457  * Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
2458  * might -- code, read-only data, read-write data, small data.  Tally
2459  * sizes, and place the offsets into sh_entsize fields: high bit means it
2460  * belongs in init.
2461  */
layout_sections(struct module * mod,struct load_info * info)2462 static void layout_sections(struct module *mod, struct load_info *info)
2463 {
2464 	static unsigned long const masks[][2] = {
2465 		/*
2466 		 * NOTE: all executable code must be the first section
2467 		 * in this array; otherwise modify the text_size
2468 		 * finder in the two loops below
2469 		 */
2470 		{ SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
2471 		{ SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
2472 		{ SHF_RO_AFTER_INIT | SHF_ALLOC, ARCH_SHF_SMALL },
2473 		{ SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
2474 		{ ARCH_SHF_SMALL | SHF_ALLOC, 0 }
2475 	};
2476 	unsigned int m, i;
2477 
2478 	for (i = 0; i < info->hdr->e_shnum; i++)
2479 		info->sechdrs[i].sh_entsize = ~0UL;
2480 
2481 	pr_debug("Core section allocation order:\n");
2482 	for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2483 		for (i = 0; i < info->hdr->e_shnum; ++i) {
2484 			Elf_Shdr *s = &info->sechdrs[i];
2485 			const char *sname = info->secstrings + s->sh_name;
2486 
2487 			if ((s->sh_flags & masks[m][0]) != masks[m][0]
2488 			    || (s->sh_flags & masks[m][1])
2489 			    || s->sh_entsize != ~0UL
2490 			    || module_init_layout_section(sname))
2491 				continue;
2492 			s->sh_entsize = get_offset(mod, &mod->core_layout.size, s, i);
2493 			pr_debug("\t%s\n", sname);
2494 		}
2495 		switch (m) {
2496 		case 0: /* executable */
2497 			mod->core_layout.size = debug_align(mod->core_layout.size);
2498 			mod->core_layout.text_size = mod->core_layout.size;
2499 			break;
2500 		case 1: /* RO: text and ro-data */
2501 			mod->core_layout.size = debug_align(mod->core_layout.size);
2502 			mod->core_layout.ro_size = mod->core_layout.size;
2503 			break;
2504 		case 2: /* RO after init */
2505 			mod->core_layout.size = debug_align(mod->core_layout.size);
2506 			mod->core_layout.ro_after_init_size = mod->core_layout.size;
2507 			break;
2508 		case 4: /* whole core */
2509 			mod->core_layout.size = debug_align(mod->core_layout.size);
2510 			break;
2511 		}
2512 	}
2513 
2514 	pr_debug("Init section allocation order:\n");
2515 	for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2516 		for (i = 0; i < info->hdr->e_shnum; ++i) {
2517 			Elf_Shdr *s = &info->sechdrs[i];
2518 			const char *sname = info->secstrings + s->sh_name;
2519 
2520 			if ((s->sh_flags & masks[m][0]) != masks[m][0]
2521 			    || (s->sh_flags & masks[m][1])
2522 			    || s->sh_entsize != ~0UL
2523 			    || !module_init_layout_section(sname))
2524 				continue;
2525 			s->sh_entsize = (get_offset(mod, &mod->init_layout.size, s, i)
2526 					 | INIT_OFFSET_MASK);
2527 			pr_debug("\t%s\n", sname);
2528 		}
2529 		switch (m) {
2530 		case 0: /* executable */
2531 			mod->init_layout.size = debug_align(mod->init_layout.size);
2532 			mod->init_layout.text_size = mod->init_layout.size;
2533 			break;
2534 		case 1: /* RO: text and ro-data */
2535 			mod->init_layout.size = debug_align(mod->init_layout.size);
2536 			mod->init_layout.ro_size = mod->init_layout.size;
2537 			break;
2538 		case 2:
2539 			/*
2540 			 * RO after init doesn't apply to init_layout (only
2541 			 * core_layout), so it just takes the value of ro_size.
2542 			 */
2543 			mod->init_layout.ro_after_init_size = mod->init_layout.ro_size;
2544 			break;
2545 		case 4: /* whole init */
2546 			mod->init_layout.size = debug_align(mod->init_layout.size);
2547 			break;
2548 		}
2549 	}
2550 }
2551 
set_license(struct module * mod,const char * license)2552 static void set_license(struct module *mod, const char *license)
2553 {
2554 	if (!license)
2555 		license = "unspecified";
2556 
2557 	if (!license_is_gpl_compatible(license)) {
2558 		if (!test_taint(TAINT_PROPRIETARY_MODULE))
2559 			pr_warn("%s: module license '%s' taints kernel.\n",
2560 				mod->name, license);
2561 		add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2562 				 LOCKDEP_NOW_UNRELIABLE);
2563 	}
2564 }
2565 
2566 /* Parse tag=value strings from .modinfo section */
next_string(char * string,unsigned long * secsize)2567 static char *next_string(char *string, unsigned long *secsize)
2568 {
2569 	/* Skip non-zero chars */
2570 	while (string[0]) {
2571 		string++;
2572 		if ((*secsize)-- <= 1)
2573 			return NULL;
2574 	}
2575 
2576 	/* Skip any zero padding. */
2577 	while (!string[0]) {
2578 		string++;
2579 		if ((*secsize)-- <= 1)
2580 			return NULL;
2581 	}
2582 	return string;
2583 }
2584 
get_next_modinfo(const struct load_info * info,const char * tag,char * prev)2585 static char *get_next_modinfo(const struct load_info *info, const char *tag,
2586 			      char *prev)
2587 {
2588 	char *p;
2589 	unsigned int taglen = strlen(tag);
2590 	Elf_Shdr *infosec = &info->sechdrs[info->index.info];
2591 	unsigned long size = infosec->sh_size;
2592 
2593 	/*
2594 	 * get_modinfo() calls made before rewrite_section_headers()
2595 	 * must use sh_offset, as sh_addr isn't set!
2596 	 */
2597 	char *modinfo = (char *)info->hdr + infosec->sh_offset;
2598 
2599 	if (prev) {
2600 		size -= prev - modinfo;
2601 		modinfo = next_string(prev, &size);
2602 	}
2603 
2604 	for (p = modinfo; p; p = next_string(p, &size)) {
2605 		if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
2606 			return p + taglen + 1;
2607 	}
2608 	return NULL;
2609 }
2610 
get_modinfo(const struct load_info * info,const char * tag)2611 static char *get_modinfo(const struct load_info *info, const char *tag)
2612 {
2613 	return get_next_modinfo(info, tag, NULL);
2614 }
2615 
setup_modinfo(struct module * mod,struct load_info * info)2616 static void setup_modinfo(struct module *mod, struct load_info *info)
2617 {
2618 	struct module_attribute *attr;
2619 	int i;
2620 
2621 	for (i = 0; (attr = modinfo_attrs[i]); i++) {
2622 		if (attr->setup)
2623 			attr->setup(mod, get_modinfo(info, attr->attr.name));
2624 	}
2625 }
2626 
free_modinfo(struct module * mod)2627 static void free_modinfo(struct module *mod)
2628 {
2629 	struct module_attribute *attr;
2630 	int i;
2631 
2632 	for (i = 0; (attr = modinfo_attrs[i]); i++) {
2633 		if (attr->free)
2634 			attr->free(mod);
2635 	}
2636 }
2637 
2638 #ifdef CONFIG_KALLSYMS
2639 
2640 /* 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)2641 static const struct kernel_symbol *lookup_exported_symbol(const char *name,
2642 							  const struct kernel_symbol *start,
2643 							  const struct kernel_symbol *stop)
2644 {
2645 	return bsearch(name, start, stop - start,
2646 			sizeof(struct kernel_symbol), cmp_name);
2647 }
2648 
is_exported(const char * name,unsigned long value,const struct module * mod)2649 static int is_exported(const char *name, unsigned long value,
2650 		       const struct module *mod)
2651 {
2652 	const struct kernel_symbol *ks;
2653 	if (!mod)
2654 		ks = lookup_exported_symbol(name, __start___ksymtab, __stop___ksymtab);
2655 	else
2656 		ks = lookup_exported_symbol(name, mod->syms, mod->syms + mod->num_syms);
2657 
2658 	return ks != NULL && kernel_symbol_value(ks) == value;
2659 }
2660 
2661 /* As per nm */
elf_type(const Elf_Sym * sym,const struct load_info * info)2662 static char elf_type(const Elf_Sym *sym, const struct load_info *info)
2663 {
2664 	const Elf_Shdr *sechdrs = info->sechdrs;
2665 
2666 	if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
2667 		if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT)
2668 			return 'v';
2669 		else
2670 			return 'w';
2671 	}
2672 	if (sym->st_shndx == SHN_UNDEF)
2673 		return 'U';
2674 	if (sym->st_shndx == SHN_ABS || sym->st_shndx == info->index.pcpu)
2675 		return 'a';
2676 	if (sym->st_shndx >= SHN_LORESERVE)
2677 		return '?';
2678 	if (sechdrs[sym->st_shndx].sh_flags & SHF_EXECINSTR)
2679 		return 't';
2680 	if (sechdrs[sym->st_shndx].sh_flags & SHF_ALLOC
2681 	    && sechdrs[sym->st_shndx].sh_type != SHT_NOBITS) {
2682 		if (!(sechdrs[sym->st_shndx].sh_flags & SHF_WRITE))
2683 			return 'r';
2684 		else if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2685 			return 'g';
2686 		else
2687 			return 'd';
2688 	}
2689 	if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
2690 		if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2691 			return 's';
2692 		else
2693 			return 'b';
2694 	}
2695 	if (strstarts(info->secstrings + sechdrs[sym->st_shndx].sh_name,
2696 		      ".debug")) {
2697 		return 'n';
2698 	}
2699 	return '?';
2700 }
2701 
is_core_symbol(const Elf_Sym * src,const Elf_Shdr * sechdrs,unsigned int shnum,unsigned int pcpundx)2702 static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
2703 			unsigned int shnum, unsigned int pcpundx)
2704 {
2705 	const Elf_Shdr *sec;
2706 
2707 	if (src->st_shndx == SHN_UNDEF
2708 	    || src->st_shndx >= shnum
2709 	    || !src->st_name)
2710 		return false;
2711 
2712 #ifdef CONFIG_KALLSYMS_ALL
2713 	if (src->st_shndx == pcpundx)
2714 		return true;
2715 #endif
2716 
2717 	sec = sechdrs + src->st_shndx;
2718 	if (!(sec->sh_flags & SHF_ALLOC)
2719 #ifndef CONFIG_KALLSYMS_ALL
2720 	    || !(sec->sh_flags & SHF_EXECINSTR)
2721 #endif
2722 	    || (sec->sh_entsize & INIT_OFFSET_MASK))
2723 		return false;
2724 
2725 	return true;
2726 }
2727 
2728 /*
2729  * We only allocate and copy the strings needed by the parts of symtab
2730  * we keep.  This is simple, but has the effect of making multiple
2731  * copies of duplicates.  We could be more sophisticated, see
2732  * linux-kernel thread starting with
2733  * <73defb5e4bca04a6431392cc341112b1@localhost>.
2734  */
layout_symtab(struct module * mod,struct load_info * info)2735 static void layout_symtab(struct module *mod, struct load_info *info)
2736 {
2737 	Elf_Shdr *symsect = info->sechdrs + info->index.sym;
2738 	Elf_Shdr *strsect = info->sechdrs + info->index.str;
2739 	const Elf_Sym *src;
2740 	unsigned int i, nsrc, ndst, strtab_size = 0;
2741 
2742 	/* Put symbol section at end of init part of module. */
2743 	symsect->sh_flags |= SHF_ALLOC;
2744 	symsect->sh_entsize = get_offset(mod, &mod->init_layout.size, symsect,
2745 					 info->index.sym) | INIT_OFFSET_MASK;
2746 	pr_debug("\t%s\n", info->secstrings + symsect->sh_name);
2747 
2748 	src = (void *)info->hdr + symsect->sh_offset;
2749 	nsrc = symsect->sh_size / sizeof(*src);
2750 
2751 	/* Compute total space required for the core symbols' strtab. */
2752 	for (ndst = i = 0; i < nsrc; i++) {
2753 		if (i == 0 || is_livepatch_module(mod) ||
2754 		    is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum,
2755 				   info->index.pcpu)) {
2756 			strtab_size += strlen(&info->strtab[src[i].st_name])+1;
2757 			ndst++;
2758 		}
2759 	}
2760 
2761 	/* Append room for core symbols at end of core part. */
2762 	info->symoffs = ALIGN(mod->core_layout.size, symsect->sh_addralign ?: 1);
2763 	info->stroffs = mod->core_layout.size = info->symoffs + ndst * sizeof(Elf_Sym);
2764 	mod->core_layout.size += strtab_size;
2765 	info->core_typeoffs = mod->core_layout.size;
2766 	mod->core_layout.size += ndst * sizeof(char);
2767 	mod->core_layout.size = debug_align(mod->core_layout.size);
2768 
2769 	/* Put string table section at end of init part of module. */
2770 	strsect->sh_flags |= SHF_ALLOC;
2771 	strsect->sh_entsize = get_offset(mod, &mod->init_layout.size, strsect,
2772 					 info->index.str) | INIT_OFFSET_MASK;
2773 	pr_debug("\t%s\n", info->secstrings + strsect->sh_name);
2774 
2775 	/* We'll tack temporary mod_kallsyms on the end. */
2776 	mod->init_layout.size = ALIGN(mod->init_layout.size,
2777 				      __alignof__(struct mod_kallsyms));
2778 	info->mod_kallsyms_init_off = mod->init_layout.size;
2779 	mod->init_layout.size += sizeof(struct mod_kallsyms);
2780 	info->init_typeoffs = mod->init_layout.size;
2781 	mod->init_layout.size += nsrc * sizeof(char);
2782 	mod->init_layout.size = debug_align(mod->init_layout.size);
2783 }
2784 
2785 /*
2786  * We use the full symtab and strtab which layout_symtab arranged to
2787  * be appended to the init section.  Later we switch to the cut-down
2788  * core-only ones.
2789  */
add_kallsyms(struct module * mod,const struct load_info * info)2790 static void add_kallsyms(struct module *mod, const struct load_info *info)
2791 {
2792 	unsigned int i, ndst;
2793 	const Elf_Sym *src;
2794 	Elf_Sym *dst;
2795 	char *s;
2796 	Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2797 
2798 	/* Set up to point into init section. */
2799 	mod->kallsyms = mod->init_layout.base + info->mod_kallsyms_init_off;
2800 
2801 	mod->kallsyms->symtab = (void *)symsec->sh_addr;
2802 	mod->kallsyms->num_symtab = symsec->sh_size / sizeof(Elf_Sym);
2803 	/* Make sure we get permanent strtab: don't use info->strtab. */
2804 	mod->kallsyms->strtab = (void *)info->sechdrs[info->index.str].sh_addr;
2805 	mod->kallsyms->typetab = mod->init_layout.base + info->init_typeoffs;
2806 
2807 	/*
2808 	 * Now populate the cut down core kallsyms for after init
2809 	 * and set types up while we still have access to sections.
2810 	 */
2811 	mod->core_kallsyms.symtab = dst = mod->core_layout.base + info->symoffs;
2812 	mod->core_kallsyms.strtab = s = mod->core_layout.base + info->stroffs;
2813 	mod->core_kallsyms.typetab = mod->core_layout.base + info->core_typeoffs;
2814 	src = mod->kallsyms->symtab;
2815 	for (ndst = i = 0; i < mod->kallsyms->num_symtab; i++) {
2816 		mod->kallsyms->typetab[i] = elf_type(src + i, info);
2817 		if (i == 0 || is_livepatch_module(mod) ||
2818 		    is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum,
2819 				   info->index.pcpu)) {
2820 			mod->core_kallsyms.typetab[ndst] =
2821 			    mod->kallsyms->typetab[i];
2822 			dst[ndst] = src[i];
2823 			dst[ndst++].st_name = s - mod->core_kallsyms.strtab;
2824 			s += strlcpy(s, &mod->kallsyms->strtab[src[i].st_name],
2825 				     KSYM_NAME_LEN) + 1;
2826 		}
2827 	}
2828 	mod->core_kallsyms.num_symtab = ndst;
2829 }
2830 #else
layout_symtab(struct module * mod,struct load_info * info)2831 static inline void layout_symtab(struct module *mod, struct load_info *info)
2832 {
2833 }
2834 
add_kallsyms(struct module * mod,const struct load_info * info)2835 static void add_kallsyms(struct module *mod, const struct load_info *info)
2836 {
2837 }
2838 #endif /* CONFIG_KALLSYMS */
2839 
2840 #if IS_ENABLED(CONFIG_KALLSYMS) && IS_ENABLED(CONFIG_STACKTRACE_BUILD_ID)
init_build_id(struct module * mod,const struct load_info * info)2841 static void init_build_id(struct module *mod, const struct load_info *info)
2842 {
2843 	const Elf_Shdr *sechdr;
2844 	unsigned int i;
2845 
2846 	for (i = 0; i < info->hdr->e_shnum; i++) {
2847 		sechdr = &info->sechdrs[i];
2848 		if (!sect_empty(sechdr) && sechdr->sh_type == SHT_NOTE &&
2849 		    !build_id_parse_buf((void *)sechdr->sh_addr, mod->build_id,
2850 					sechdr->sh_size))
2851 			break;
2852 	}
2853 }
2854 #else
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 }
2858 #endif
2859 
dynamic_debug_setup(struct module * mod,struct _ddebug * debug,unsigned int num)2860 static void dynamic_debug_setup(struct module *mod, struct _ddebug *debug, unsigned int num)
2861 {
2862 	if (!debug)
2863 		return;
2864 	ddebug_add_module(debug, num, mod->name);
2865 }
2866 
dynamic_debug_remove(struct module * mod,struct _ddebug * debug)2867 static void dynamic_debug_remove(struct module *mod, struct _ddebug *debug)
2868 {
2869 	if (debug)
2870 		ddebug_remove_module(mod->name);
2871 }
2872 
module_alloc(unsigned long size)2873 void * __weak module_alloc(unsigned long size)
2874 {
2875 	return __vmalloc_node_range(size, 1, VMALLOC_START, VMALLOC_END,
2876 			GFP_KERNEL, PAGE_KERNEL_EXEC, VM_FLUSH_RESET_PERMS,
2877 			NUMA_NO_NODE, __builtin_return_address(0));
2878 }
2879 
module_init_section(const char * name)2880 bool __weak module_init_section(const char *name)
2881 {
2882 	return strstarts(name, ".init");
2883 }
2884 
module_exit_section(const char * name)2885 bool __weak module_exit_section(const char *name)
2886 {
2887 	return strstarts(name, ".exit");
2888 }
2889 
2890 #ifdef CONFIG_DEBUG_KMEMLEAK
kmemleak_load_module(const struct module * mod,const struct load_info * info)2891 static void kmemleak_load_module(const struct module *mod,
2892 				 const struct load_info *info)
2893 {
2894 	unsigned int i;
2895 
2896 	/* only scan the sections containing data */
2897 	kmemleak_scan_area(mod, sizeof(struct module), GFP_KERNEL);
2898 
2899 	for (i = 1; i < info->hdr->e_shnum; i++) {
2900 		/* Scan all writable sections that's not executable */
2901 		if (!(info->sechdrs[i].sh_flags & SHF_ALLOC) ||
2902 		    !(info->sechdrs[i].sh_flags & SHF_WRITE) ||
2903 		    (info->sechdrs[i].sh_flags & SHF_EXECINSTR))
2904 			continue;
2905 
2906 		kmemleak_scan_area((void *)info->sechdrs[i].sh_addr,
2907 				   info->sechdrs[i].sh_size, GFP_KERNEL);
2908 	}
2909 }
2910 #else
kmemleak_load_module(const struct module * mod,const struct load_info * info)2911 static inline void kmemleak_load_module(const struct module *mod,
2912 					const struct load_info *info)
2913 {
2914 }
2915 #endif
2916 
2917 #ifdef CONFIG_MODULE_SIG
module_sig_check(struct load_info * info,int flags)2918 static int module_sig_check(struct load_info *info, int flags)
2919 {
2920 	int err = -ENODATA;
2921 	const unsigned long markerlen = sizeof(MODULE_SIG_STRING) - 1;
2922 	const char *reason;
2923 	const void *mod = info->hdr;
2924 
2925 	/*
2926 	 * Require flags == 0, as a module with version information
2927 	 * removed is no longer the module that was signed
2928 	 */
2929 	if (flags == 0 &&
2930 	    info->len > markerlen &&
2931 	    memcmp(mod + info->len - markerlen, MODULE_SIG_STRING, markerlen) == 0) {
2932 		/* We truncate the module to discard the signature */
2933 		info->len -= markerlen;
2934 		err = mod_verify_sig(mod, info);
2935 		if (!err) {
2936 			info->sig_ok = true;
2937 			return 0;
2938 		}
2939 	}
2940 
2941 	/*
2942 	 * We don't permit modules to be loaded into the trusted kernels
2943 	 * without a valid signature on them, but if we're not enforcing,
2944 	 * certain errors are non-fatal.
2945 	 */
2946 	switch (err) {
2947 	case -ENODATA:
2948 		reason = "unsigned module";
2949 		break;
2950 	case -ENOPKG:
2951 		reason = "module with unsupported crypto";
2952 		break;
2953 	case -ENOKEY:
2954 		reason = "module with unavailable key";
2955 		break;
2956 
2957 	default:
2958 		/*
2959 		 * All other errors are fatal, including lack of memory,
2960 		 * unparseable signatures, and signature check failures --
2961 		 * even if signatures aren't required.
2962 		 */
2963 		return err;
2964 	}
2965 
2966 	if (is_module_sig_enforced()) {
2967 		pr_notice("Loading of %s is rejected\n", reason);
2968 		return -EKEYREJECTED;
2969 	}
2970 
2971 /*
2972  * ANDROID: GKI: Do not prevent loading of unsigned modules;
2973  * as all modules except GKI modules are not signed.
2974  */
2975 #ifndef CONFIG_MODULE_SIG_PROTECT
2976 	return security_locked_down(LOCKDOWN_MODULE_SIGNATURE);
2977 #else
2978 	return 0;
2979 #endif
2980 }
2981 #else /* !CONFIG_MODULE_SIG */
module_sig_check(struct load_info * info,int flags)2982 static int module_sig_check(struct load_info *info, int flags)
2983 {
2984 	return 0;
2985 }
2986 #endif /* !CONFIG_MODULE_SIG */
2987 
validate_section_offset(struct load_info * info,Elf_Shdr * shdr)2988 static int validate_section_offset(struct load_info *info, Elf_Shdr *shdr)
2989 {
2990 	unsigned long secend;
2991 
2992 	/*
2993 	 * Check for both overflow and offset/size being
2994 	 * too large.
2995 	 */
2996 	secend = shdr->sh_offset + shdr->sh_size;
2997 	if (secend < shdr->sh_offset || secend > info->len)
2998 		return -ENOEXEC;
2999 
3000 	return 0;
3001 }
3002 
3003 /*
3004  * Sanity checks against invalid binaries, wrong arch, weird elf version.
3005  *
3006  * Also do basic validity checks against section offsets and sizes, the
3007  * section name string table, and the indices used for it (sh_name).
3008  */
elf_validity_check(struct load_info * info)3009 static int elf_validity_check(struct load_info *info)
3010 {
3011 	unsigned int i;
3012 	Elf_Shdr *shdr, *strhdr;
3013 	int err;
3014 
3015 	if (info->len < sizeof(*(info->hdr))) {
3016 		pr_err("Invalid ELF header len %lu\n", info->len);
3017 		goto no_exec;
3018 	}
3019 
3020 	if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0) {
3021 		pr_err("Invalid ELF header magic: != %s\n", ELFMAG);
3022 		goto no_exec;
3023 	}
3024 	if (info->hdr->e_type != ET_REL) {
3025 		pr_err("Invalid ELF header type: %u != %u\n",
3026 		       info->hdr->e_type, ET_REL);
3027 		goto no_exec;
3028 	}
3029 	if (!elf_check_arch(info->hdr)) {
3030 		pr_err("Invalid architecture in ELF header: %u\n",
3031 		       info->hdr->e_machine);
3032 		goto no_exec;
3033 	}
3034 	if (info->hdr->e_shentsize != sizeof(Elf_Shdr)) {
3035 		pr_err("Invalid ELF section header size\n");
3036 		goto no_exec;
3037 	}
3038 
3039 	/*
3040 	 * e_shnum is 16 bits, and sizeof(Elf_Shdr) is
3041 	 * known and small. So e_shnum * sizeof(Elf_Shdr)
3042 	 * will not overflow unsigned long on any platform.
3043 	 */
3044 	if (info->hdr->e_shoff >= info->len
3045 	    || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
3046 		info->len - info->hdr->e_shoff)) {
3047 		pr_err("Invalid ELF section header overflow\n");
3048 		goto no_exec;
3049 	}
3050 
3051 	info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
3052 
3053 	/*
3054 	 * Verify if the section name table index is valid.
3055 	 */
3056 	if (info->hdr->e_shstrndx == SHN_UNDEF
3057 	    || info->hdr->e_shstrndx >= info->hdr->e_shnum) {
3058 		pr_err("Invalid ELF section name index: %d || e_shstrndx (%d) >= e_shnum (%d)\n",
3059 		       info->hdr->e_shstrndx, info->hdr->e_shstrndx,
3060 		       info->hdr->e_shnum);
3061 		goto no_exec;
3062 	}
3063 
3064 	strhdr = &info->sechdrs[info->hdr->e_shstrndx];
3065 	err = validate_section_offset(info, strhdr);
3066 	if (err < 0) {
3067 		pr_err("Invalid ELF section hdr(type %u)\n", strhdr->sh_type);
3068 		return err;
3069 	}
3070 
3071 	/*
3072 	 * The section name table must be NUL-terminated, as required
3073 	 * by the spec. This makes strcmp and pr_* calls that access
3074 	 * strings in the section safe.
3075 	 */
3076 	info->secstrings = (void *)info->hdr + strhdr->sh_offset;
3077 	if (strhdr->sh_size == 0) {
3078 		pr_err("empty section name table\n");
3079 		goto no_exec;
3080 	}
3081 	if (info->secstrings[strhdr->sh_size - 1] != '\0') {
3082 		pr_err("ELF Spec violation: section name table isn't null terminated\n");
3083 		goto no_exec;
3084 	}
3085 
3086 	/*
3087 	 * The code assumes that section 0 has a length of zero and
3088 	 * an addr of zero, so check for it.
3089 	 */
3090 	if (info->sechdrs[0].sh_type != SHT_NULL
3091 	    || info->sechdrs[0].sh_size != 0
3092 	    || info->sechdrs[0].sh_addr != 0) {
3093 		pr_err("ELF Spec violation: section 0 type(%d)!=SH_NULL or non-zero len or addr\n",
3094 		       info->sechdrs[0].sh_type);
3095 		goto no_exec;
3096 	}
3097 
3098 	for (i = 1; i < info->hdr->e_shnum; i++) {
3099 		shdr = &info->sechdrs[i];
3100 		switch (shdr->sh_type) {
3101 		case SHT_NULL:
3102 		case SHT_NOBITS:
3103 			continue;
3104 		case SHT_SYMTAB:
3105 			if (shdr->sh_link == SHN_UNDEF
3106 			    || shdr->sh_link >= info->hdr->e_shnum) {
3107 				pr_err("Invalid ELF sh_link!=SHN_UNDEF(%d) or (sh_link(%d) >= hdr->e_shnum(%d)\n",
3108 				       shdr->sh_link, shdr->sh_link,
3109 				       info->hdr->e_shnum);
3110 				goto no_exec;
3111 			}
3112 			fallthrough;
3113 		default:
3114 			err = validate_section_offset(info, shdr);
3115 			if (err < 0) {
3116 				pr_err("Invalid ELF section in module (section %u type %u)\n",
3117 					i, shdr->sh_type);
3118 				return err;
3119 			}
3120 
3121 			if (shdr->sh_flags & SHF_ALLOC) {
3122 				if (shdr->sh_name >= strhdr->sh_size) {
3123 					pr_err("Invalid ELF section name in module (section %u type %u)\n",
3124 					       i, shdr->sh_type);
3125 					return -ENOEXEC;
3126 				}
3127 			}
3128 			break;
3129 		}
3130 	}
3131 
3132 	return 0;
3133 
3134 no_exec:
3135 	return -ENOEXEC;
3136 }
3137 
3138 #define COPY_CHUNK_SIZE (16*PAGE_SIZE)
3139 
copy_chunked_from_user(void * dst,const void __user * usrc,unsigned long len)3140 static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len)
3141 {
3142 	do {
3143 		unsigned long n = min(len, COPY_CHUNK_SIZE);
3144 
3145 		if (copy_from_user(dst, usrc, n) != 0)
3146 			return -EFAULT;
3147 		cond_resched();
3148 		dst += n;
3149 		usrc += n;
3150 		len -= n;
3151 	} while (len);
3152 	return 0;
3153 }
3154 
3155 #ifdef CONFIG_LIVEPATCH
check_modinfo_livepatch(struct module * mod,struct load_info * info)3156 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
3157 {
3158 	if (get_modinfo(info, "livepatch")) {
3159 		mod->klp = true;
3160 		add_taint_module(mod, TAINT_LIVEPATCH, LOCKDEP_STILL_OK);
3161 		pr_notice_once("%s: tainting kernel with TAINT_LIVEPATCH\n",
3162 			       mod->name);
3163 	}
3164 
3165 	return 0;
3166 }
3167 #else /* !CONFIG_LIVEPATCH */
check_modinfo_livepatch(struct module * mod,struct load_info * info)3168 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
3169 {
3170 	if (get_modinfo(info, "livepatch")) {
3171 		pr_err("%s: module is marked as livepatch module, but livepatch support is disabled",
3172 		       mod->name);
3173 		return -ENOEXEC;
3174 	}
3175 
3176 	return 0;
3177 }
3178 #endif /* CONFIG_LIVEPATCH */
3179 
check_modinfo_retpoline(struct module * mod,struct load_info * info)3180 static void check_modinfo_retpoline(struct module *mod, struct load_info *info)
3181 {
3182 	if (retpoline_module_ok(get_modinfo(info, "retpoline")))
3183 		return;
3184 
3185 	pr_warn("%s: loading module not compiled with retpoline compiler.\n",
3186 		mod->name);
3187 }
3188 
3189 /* Sets info->hdr and info->len. */
copy_module_from_user(const void __user * umod,unsigned long len,struct load_info * info)3190 static int copy_module_from_user(const void __user *umod, unsigned long len,
3191 				  struct load_info *info)
3192 {
3193 	int err;
3194 
3195 	info->len = len;
3196 	if (info->len < sizeof(*(info->hdr)))
3197 		return -ENOEXEC;
3198 
3199 	err = security_kernel_load_data(LOADING_MODULE, true);
3200 	if (err)
3201 		return err;
3202 
3203 	/* Suck in entire file: we'll want most of it. */
3204 	info->hdr = __vmalloc(info->len, GFP_KERNEL | __GFP_NOWARN);
3205 	if (!info->hdr)
3206 		return -ENOMEM;
3207 
3208 	if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) {
3209 		err = -EFAULT;
3210 		goto out;
3211 	}
3212 
3213 	err = security_kernel_post_load_data((char *)info->hdr, info->len,
3214 					     LOADING_MODULE, "init_module");
3215 out:
3216 	if (err)
3217 		vfree(info->hdr);
3218 
3219 	return err;
3220 }
3221 
free_copy(struct load_info * info)3222 static void free_copy(struct load_info *info)
3223 {
3224 	vfree(info->hdr);
3225 }
3226 
rewrite_section_headers(struct load_info * info,int flags)3227 static int rewrite_section_headers(struct load_info *info, int flags)
3228 {
3229 	unsigned int i;
3230 
3231 	/* This should always be true, but let's be sure. */
3232 	info->sechdrs[0].sh_addr = 0;
3233 
3234 	for (i = 1; i < info->hdr->e_shnum; i++) {
3235 		Elf_Shdr *shdr = &info->sechdrs[i];
3236 
3237 		/*
3238 		 * Mark all sections sh_addr with their address in the
3239 		 * temporary image.
3240 		 */
3241 		shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
3242 
3243 	}
3244 
3245 	/* Track but don't keep modinfo and version sections. */
3246 	info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
3247 	info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
3248 
3249 	return 0;
3250 }
3251 
3252 /*
3253  * Set up our basic convenience variables (pointers to section headers,
3254  * search for module section index etc), and do some basic section
3255  * verification.
3256  *
3257  * Set info->mod to the temporary copy of the module in info->hdr. The final one
3258  * will be allocated in move_module().
3259  */
setup_load_info(struct load_info * info,int flags)3260 static int setup_load_info(struct load_info *info, int flags)
3261 {
3262 	unsigned int i;
3263 
3264 	/* Try to find a name early so we can log errors with a module name */
3265 	info->index.info = find_sec(info, ".modinfo");
3266 	if (info->index.info)
3267 		info->name = get_modinfo(info, "name");
3268 
3269 	/* Find internal symbols and strings. */
3270 	for (i = 1; i < info->hdr->e_shnum; i++) {
3271 		if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
3272 			info->index.sym = i;
3273 			info->index.str = info->sechdrs[i].sh_link;
3274 			info->strtab = (char *)info->hdr
3275 				+ info->sechdrs[info->index.str].sh_offset;
3276 			break;
3277 		}
3278 	}
3279 
3280 	if (info->index.sym == 0) {
3281 		pr_warn("%s: module has no symbols (stripped?)\n",
3282 			info->name ?: "(missing .modinfo section or name field)");
3283 		return -ENOEXEC;
3284 	}
3285 
3286 	info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
3287 	if (!info->index.mod) {
3288 		pr_warn("%s: No module found in object\n",
3289 			info->name ?: "(missing .modinfo section or name field)");
3290 		return -ENOEXEC;
3291 	}
3292 	/* This is temporary: point mod into copy of data. */
3293 	info->mod = (void *)info->hdr + info->sechdrs[info->index.mod].sh_offset;
3294 
3295 	/*
3296 	 * If we didn't load the .modinfo 'name' field earlier, fall back to
3297 	 * on-disk struct mod 'name' field.
3298 	 */
3299 	if (!info->name)
3300 		info->name = info->mod->name;
3301 
3302 	if (flags & MODULE_INIT_IGNORE_MODVERSIONS)
3303 		info->index.vers = 0; /* Pretend no __versions section! */
3304 	else
3305 		info->index.vers = find_sec(info, "__versions");
3306 
3307 	info->index.pcpu = find_pcpusec(info);
3308 
3309 	return 0;
3310 }
3311 
check_modinfo(struct module * mod,struct load_info * info,int flags)3312 static int check_modinfo(struct module *mod, struct load_info *info, int flags)
3313 {
3314 	const char *modmagic = get_modinfo(info, "vermagic");
3315 	int err;
3316 
3317 	if (flags & MODULE_INIT_IGNORE_VERMAGIC)
3318 		modmagic = NULL;
3319 
3320 	/* This is allowed: modprobe --force will invalidate it. */
3321 	if (!modmagic) {
3322 		err = try_to_force_load(mod, "bad vermagic");
3323 		if (err)
3324 			return err;
3325 	} else if (!same_magic(modmagic, vermagic, info->index.vers)) {
3326 		pr_err("%s: version magic '%s' should be '%s'\n",
3327 		       info->name, modmagic, vermagic);
3328 		return -ENOEXEC;
3329 	}
3330 
3331 	if (!get_modinfo(info, "intree")) {
3332 		if (!test_taint(TAINT_OOT_MODULE))
3333 			pr_warn("%s: loading out-of-tree module taints kernel.\n",
3334 				mod->name);
3335 		add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
3336 	}
3337 
3338 	check_modinfo_retpoline(mod, info);
3339 
3340 	if (get_modinfo(info, "staging")) {
3341 		add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
3342 		pr_warn("%s: module is from the staging directory, the quality "
3343 			"is unknown, you have been warned.\n", mod->name);
3344 	}
3345 
3346 	err = check_modinfo_livepatch(mod, info);
3347 	if (err)
3348 		return err;
3349 
3350 	/* Set up license info based on the info section */
3351 	set_license(mod, get_modinfo(info, "license"));
3352 
3353 	return 0;
3354 }
3355 
find_module_sections(struct module * mod,struct load_info * info)3356 static int find_module_sections(struct module *mod, struct load_info *info)
3357 {
3358 	mod->kp = section_objs(info, "__param",
3359 			       sizeof(*mod->kp), &mod->num_kp);
3360 	mod->syms = section_objs(info, "__ksymtab",
3361 				 sizeof(*mod->syms), &mod->num_syms);
3362 	mod->crcs = section_addr(info, "__kcrctab");
3363 	mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
3364 				     sizeof(*mod->gpl_syms),
3365 				     &mod->num_gpl_syms);
3366 	mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
3367 
3368 #ifdef CONFIG_CONSTRUCTORS
3369 	mod->ctors = section_objs(info, ".ctors",
3370 				  sizeof(*mod->ctors), &mod->num_ctors);
3371 	if (!mod->ctors)
3372 		mod->ctors = section_objs(info, ".init_array",
3373 				sizeof(*mod->ctors), &mod->num_ctors);
3374 	else if (find_sec(info, ".init_array")) {
3375 		/*
3376 		 * This shouldn't happen with same compiler and binutils
3377 		 * building all parts of the module.
3378 		 */
3379 		pr_warn("%s: has both .ctors and .init_array.\n",
3380 		       mod->name);
3381 		return -EINVAL;
3382 	}
3383 #endif
3384 
3385 	mod->noinstr_text_start = section_objs(info, ".noinstr.text", 1,
3386 						&mod->noinstr_text_size);
3387 
3388 #ifdef CONFIG_TRACEPOINTS
3389 	mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
3390 					     sizeof(*mod->tracepoints_ptrs),
3391 					     &mod->num_tracepoints);
3392 #endif
3393 #ifdef CONFIG_TREE_SRCU
3394 	mod->srcu_struct_ptrs = section_objs(info, "___srcu_struct_ptrs",
3395 					     sizeof(*mod->srcu_struct_ptrs),
3396 					     &mod->num_srcu_structs);
3397 #endif
3398 #ifdef CONFIG_BPF_EVENTS
3399 	mod->bpf_raw_events = section_objs(info, "__bpf_raw_tp_map",
3400 					   sizeof(*mod->bpf_raw_events),
3401 					   &mod->num_bpf_raw_events);
3402 #endif
3403 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
3404 	mod->btf_data = any_section_objs(info, ".BTF", 1, &mod->btf_data_size);
3405 #endif
3406 #ifdef CONFIG_JUMP_LABEL
3407 	mod->jump_entries = section_objs(info, "__jump_table",
3408 					sizeof(*mod->jump_entries),
3409 					&mod->num_jump_entries);
3410 #endif
3411 #ifdef CONFIG_EVENT_TRACING
3412 	mod->trace_events = section_objs(info, "_ftrace_events",
3413 					 sizeof(*mod->trace_events),
3414 					 &mod->num_trace_events);
3415 	mod->trace_evals = section_objs(info, "_ftrace_eval_map",
3416 					sizeof(*mod->trace_evals),
3417 					&mod->num_trace_evals);
3418 #endif
3419 #ifdef CONFIG_TRACING
3420 	mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
3421 					 sizeof(*mod->trace_bprintk_fmt_start),
3422 					 &mod->num_trace_bprintk_fmt);
3423 #endif
3424 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
3425 	/* sechdrs[0].sh_size is always zero */
3426 	mod->ftrace_callsites = section_objs(info, FTRACE_CALLSITE_SECTION,
3427 					     sizeof(*mod->ftrace_callsites),
3428 					     &mod->num_ftrace_callsites);
3429 #endif
3430 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
3431 	mod->ei_funcs = section_objs(info, "_error_injection_whitelist",
3432 					    sizeof(*mod->ei_funcs),
3433 					    &mod->num_ei_funcs);
3434 #endif
3435 #ifdef CONFIG_KPROBES
3436 	mod->kprobes_text_start = section_objs(info, ".kprobes.text", 1,
3437 						&mod->kprobes_text_size);
3438 	mod->kprobe_blacklist = section_objs(info, "_kprobe_blacklist",
3439 						sizeof(unsigned long),
3440 						&mod->num_kprobe_blacklist);
3441 #endif
3442 #ifdef CONFIG_PRINTK_INDEX
3443 	mod->printk_index_start = section_objs(info, ".printk_index",
3444 					       sizeof(*mod->printk_index_start),
3445 					       &mod->printk_index_size);
3446 #endif
3447 #ifdef CONFIG_HAVE_STATIC_CALL_INLINE
3448 	mod->static_call_sites = section_objs(info, ".static_call_sites",
3449 					      sizeof(*mod->static_call_sites),
3450 					      &mod->num_static_call_sites);
3451 #endif
3452 	mod->extable = section_objs(info, "__ex_table",
3453 				    sizeof(*mod->extable), &mod->num_exentries);
3454 
3455 	if (section_addr(info, "__obsparm"))
3456 		pr_warn("%s: Ignoring obsolete parameters\n", mod->name);
3457 
3458 	info->debug = section_objs(info, "__dyndbg",
3459 				   sizeof(*info->debug), &info->num_debug);
3460 
3461 	return 0;
3462 }
3463 
move_module(struct module * mod,struct load_info * info)3464 static int move_module(struct module *mod, struct load_info *info)
3465 {
3466 	int i;
3467 	void *ptr;
3468 
3469 	/* Do the allocs. */
3470 	ptr = module_alloc(mod->core_layout.size);
3471 	/*
3472 	 * The pointer to this block is stored in the module structure
3473 	 * which is inside the block. Just mark it as not being a
3474 	 * leak.
3475 	 */
3476 	kmemleak_not_leak(ptr);
3477 	if (!ptr)
3478 		return -ENOMEM;
3479 
3480 	memset(ptr, 0, mod->core_layout.size);
3481 	mod->core_layout.base = ptr;
3482 
3483 	if (mod->init_layout.size) {
3484 		ptr = module_alloc(mod->init_layout.size);
3485 		/*
3486 		 * The pointer to this block is stored in the module structure
3487 		 * which is inside the block. This block doesn't need to be
3488 		 * scanned as it contains data and code that will be freed
3489 		 * after the module is initialized.
3490 		 */
3491 		kmemleak_ignore(ptr);
3492 		if (!ptr) {
3493 			module_memfree(mod->core_layout.base);
3494 			return -ENOMEM;
3495 		}
3496 		memset(ptr, 0, mod->init_layout.size);
3497 		mod->init_layout.base = ptr;
3498 	} else
3499 		mod->init_layout.base = NULL;
3500 
3501 	/* Transfer each section which specifies SHF_ALLOC */
3502 	pr_debug("final section addresses:\n");
3503 	for (i = 0; i < info->hdr->e_shnum; i++) {
3504 		void *dest;
3505 		Elf_Shdr *shdr = &info->sechdrs[i];
3506 
3507 		if (!(shdr->sh_flags & SHF_ALLOC))
3508 			continue;
3509 
3510 		if (shdr->sh_entsize & INIT_OFFSET_MASK)
3511 			dest = mod->init_layout.base
3512 				+ (shdr->sh_entsize & ~INIT_OFFSET_MASK);
3513 		else
3514 			dest = mod->core_layout.base + shdr->sh_entsize;
3515 
3516 		if (shdr->sh_type != SHT_NOBITS)
3517 			memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
3518 		/* Update sh_addr to point to copy in image. */
3519 		shdr->sh_addr = (unsigned long)dest;
3520 		pr_debug("\t0x%lx %s\n",
3521 			 (long)shdr->sh_addr, info->secstrings + shdr->sh_name);
3522 	}
3523 
3524 	return 0;
3525 }
3526 
check_module_license_and_versions(struct module * mod)3527 static int check_module_license_and_versions(struct module *mod)
3528 {
3529 	int prev_taint = test_taint(TAINT_PROPRIETARY_MODULE);
3530 
3531 	/*
3532 	 * ndiswrapper is under GPL by itself, but loads proprietary modules.
3533 	 * Don't use add_taint_module(), as it would prevent ndiswrapper from
3534 	 * using GPL-only symbols it needs.
3535 	 */
3536 	if (strcmp(mod->name, "ndiswrapper") == 0)
3537 		add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
3538 
3539 	/* driverloader was caught wrongly pretending to be under GPL */
3540 	if (strcmp(mod->name, "driverloader") == 0)
3541 		add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
3542 				 LOCKDEP_NOW_UNRELIABLE);
3543 
3544 	/* lve claims to be GPL but upstream won't provide source */
3545 	if (strcmp(mod->name, "lve") == 0)
3546 		add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
3547 				 LOCKDEP_NOW_UNRELIABLE);
3548 
3549 	if (!prev_taint && test_taint(TAINT_PROPRIETARY_MODULE))
3550 		pr_warn("%s: module license taints kernel.\n", mod->name);
3551 
3552 #ifdef CONFIG_MODVERSIONS
3553 	if ((mod->num_syms && !mod->crcs) ||
3554 	    (mod->num_gpl_syms && !mod->gpl_crcs)) {
3555 		return try_to_force_load(mod,
3556 					 "no versions for exported symbols");
3557 	}
3558 #endif
3559 	return 0;
3560 }
3561 
flush_module_icache(const struct module * mod)3562 static void flush_module_icache(const struct module *mod)
3563 {
3564 	/*
3565 	 * Flush the instruction cache, since we've played with text.
3566 	 * Do it before processing of module parameters, so the module
3567 	 * can provide parameter accessor functions of its own.
3568 	 */
3569 	if (mod->init_layout.base)
3570 		flush_icache_range((unsigned long)mod->init_layout.base,
3571 				   (unsigned long)mod->init_layout.base
3572 				   + mod->init_layout.size);
3573 	flush_icache_range((unsigned long)mod->core_layout.base,
3574 			   (unsigned long)mod->core_layout.base + mod->core_layout.size);
3575 }
3576 
module_frob_arch_sections(Elf_Ehdr * hdr,Elf_Shdr * sechdrs,char * secstrings,struct module * mod)3577 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
3578 				     Elf_Shdr *sechdrs,
3579 				     char *secstrings,
3580 				     struct module *mod)
3581 {
3582 	return 0;
3583 }
3584 
3585 /* module_blacklist is a comma-separated list of module names */
3586 static char *module_blacklist;
blacklisted(const char * module_name)3587 static bool blacklisted(const char *module_name)
3588 {
3589 	const char *p;
3590 	size_t len;
3591 
3592 	if (!module_blacklist)
3593 		return false;
3594 
3595 	for (p = module_blacklist; *p; p += len) {
3596 		len = strcspn(p, ",");
3597 		if (strlen(module_name) == len && !memcmp(module_name, p, len))
3598 			return true;
3599 		if (p[len] == ',')
3600 			len++;
3601 	}
3602 	return false;
3603 }
3604 core_param(module_blacklist, module_blacklist, charp, 0400);
3605 
layout_and_allocate(struct load_info * info,int flags)3606 static struct module *layout_and_allocate(struct load_info *info, int flags)
3607 {
3608 	struct module *mod;
3609 	unsigned int ndx;
3610 	int err;
3611 
3612 	err = check_modinfo(info->mod, info, flags);
3613 	if (err)
3614 		return ERR_PTR(err);
3615 
3616 	/* Allow arches to frob section contents and sizes.  */
3617 	err = module_frob_arch_sections(info->hdr, info->sechdrs,
3618 					info->secstrings, info->mod);
3619 	if (err < 0)
3620 		return ERR_PTR(err);
3621 
3622 	err = module_enforce_rwx_sections(info->hdr, info->sechdrs,
3623 					  info->secstrings, info->mod);
3624 	if (err < 0)
3625 		return ERR_PTR(err);
3626 
3627 	/* We will do a special allocation for per-cpu sections later. */
3628 	info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
3629 
3630 	/*
3631 	 * Mark ro_after_init section with SHF_RO_AFTER_INIT so that
3632 	 * layout_sections() can put it in the right place.
3633 	 * Note: ro_after_init sections also have SHF_{WRITE,ALLOC} set.
3634 	 */
3635 	ndx = find_sec(info, ".data..ro_after_init");
3636 	if (ndx)
3637 		info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
3638 	/*
3639 	 * Mark the __jump_table section as ro_after_init as well: these data
3640 	 * structures are never modified, with the exception of entries that
3641 	 * refer to code in the __init section, which are annotated as such
3642 	 * at module load time.
3643 	 */
3644 	ndx = find_sec(info, "__jump_table");
3645 	if (ndx)
3646 		info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
3647 
3648 	/*
3649 	 * Determine total sizes, and put offsets in sh_entsize.  For now
3650 	 * this is done generically; there doesn't appear to be any
3651 	 * special cases for the architectures.
3652 	 */
3653 	layout_sections(info->mod, info);
3654 	layout_symtab(info->mod, info);
3655 
3656 	/* Allocate and move to the final place */
3657 	err = move_module(info->mod, info);
3658 	if (err)
3659 		return ERR_PTR(err);
3660 
3661 	/* Module has been copied to its final place now: return it. */
3662 	mod = (void *)info->sechdrs[info->index.mod].sh_addr;
3663 	kmemleak_load_module(mod, info);
3664 	return mod;
3665 }
3666 
3667 /* mod is no longer valid after this! */
module_deallocate(struct module * mod,struct load_info * info)3668 static void module_deallocate(struct module *mod, struct load_info *info)
3669 {
3670 	percpu_modfree(mod);
3671 	module_arch_freeing_init(mod);
3672 	trace_android_vh_set_memory_rw((unsigned long)mod->init_layout.base,
3673 		(mod->init_layout.size)>>PAGE_SHIFT);
3674 	trace_android_vh_set_memory_nx((unsigned long)mod->init_layout.base,
3675 		(mod->init_layout.size)>>PAGE_SHIFT);
3676 	module_memfree(mod->init_layout.base);
3677 	trace_android_vh_set_memory_rw((unsigned long)mod->core_layout.base,
3678 		(mod->core_layout.size)>>PAGE_SHIFT);
3679 	trace_android_vh_set_memory_nx((unsigned long)mod->core_layout.base,
3680 		(mod->core_layout.size)>>PAGE_SHIFT);
3681 	module_memfree(mod->core_layout.base);
3682 }
3683 
module_finalize(const Elf_Ehdr * hdr,const Elf_Shdr * sechdrs,struct module * me)3684 int __weak module_finalize(const Elf_Ehdr *hdr,
3685 			   const Elf_Shdr *sechdrs,
3686 			   struct module *me)
3687 {
3688 	return 0;
3689 }
3690 
post_relocation(struct module * mod,const struct load_info * info)3691 static int post_relocation(struct module *mod, const struct load_info *info)
3692 {
3693 	/* Sort exception table now relocations are done. */
3694 	sort_extable(mod->extable, mod->extable + mod->num_exentries);
3695 
3696 	/* Copy relocated percpu area over. */
3697 	percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
3698 		       info->sechdrs[info->index.pcpu].sh_size);
3699 
3700 	/* Setup kallsyms-specific fields. */
3701 	add_kallsyms(mod, info);
3702 
3703 	/* Arch-specific module finalizing. */
3704 	return module_finalize(info->hdr, info->sechdrs, mod);
3705 }
3706 
3707 /* Is this module of this name done loading?  No locks held. */
finished_loading(const char * name)3708 static bool finished_loading(const char *name)
3709 {
3710 	struct module *mod;
3711 	bool ret;
3712 
3713 	/*
3714 	 * The module_mutex should not be a heavily contended lock;
3715 	 * if we get the occasional sleep here, we'll go an extra iteration
3716 	 * in the wait_event_interruptible(), which is harmless.
3717 	 */
3718 	sched_annotate_sleep();
3719 	mutex_lock(&module_mutex);
3720 	mod = find_module_all(name, strlen(name), true);
3721 	ret = !mod || mod->state == MODULE_STATE_LIVE
3722 		|| mod->state == MODULE_STATE_GOING;
3723 	mutex_unlock(&module_mutex);
3724 
3725 	return ret;
3726 }
3727 
3728 /* Call module constructors. */
do_mod_ctors(struct module * mod)3729 static void do_mod_ctors(struct module *mod)
3730 {
3731 #ifdef CONFIG_CONSTRUCTORS
3732 	unsigned long i;
3733 
3734 	for (i = 0; i < mod->num_ctors; i++)
3735 		mod->ctors[i]();
3736 #endif
3737 }
3738 
3739 /* For freeing module_init on success, in case kallsyms traversing */
3740 struct mod_initfree {
3741 	struct llist_node node;
3742 	void *module_init;
3743 };
3744 
do_free_init(struct work_struct * w)3745 static void do_free_init(struct work_struct *w)
3746 {
3747 	struct llist_node *pos, *n, *list;
3748 	struct mod_initfree *initfree;
3749 
3750 	list = llist_del_all(&init_free_list);
3751 
3752 	synchronize_rcu();
3753 
3754 	llist_for_each_safe(pos, n, list) {
3755 		initfree = container_of(pos, struct mod_initfree, node);
3756 		module_memfree(initfree->module_init);
3757 		kfree(initfree);
3758 	}
3759 }
3760 
3761 /*
3762  * This is where the real work happens.
3763  *
3764  * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb
3765  * helper command 'lx-symbols'.
3766  */
do_init_module(struct module * mod)3767 static noinline int do_init_module(struct module *mod)
3768 {
3769 	int ret = 0;
3770 	struct mod_initfree *freeinit;
3771 
3772 	freeinit = kmalloc(sizeof(*freeinit), GFP_KERNEL);
3773 	if (!freeinit) {
3774 		ret = -ENOMEM;
3775 		goto fail;
3776 	}
3777 	freeinit->module_init = mod->init_layout.base;
3778 
3779 	do_mod_ctors(mod);
3780 	/* Start the module */
3781 	if (mod->init != NULL)
3782 		ret = do_one_initcall(mod->init);
3783 	if (ret < 0) {
3784 		goto fail_free_freeinit;
3785 	}
3786 	if (ret > 0) {
3787 		pr_warn("%s: '%s'->init suspiciously returned %d, it should "
3788 			"follow 0/-E convention\n"
3789 			"%s: loading module anyway...\n",
3790 			__func__, mod->name, ret, __func__);
3791 		dump_stack();
3792 	}
3793 
3794 	/* Now it's a first class citizen! */
3795 	mod->state = MODULE_STATE_LIVE;
3796 	blocking_notifier_call_chain(&module_notify_list,
3797 				     MODULE_STATE_LIVE, mod);
3798 
3799 	/* Delay uevent until module has finished its init routine */
3800 	kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
3801 
3802 	/*
3803 	 * We need to finish all async code before the module init sequence
3804 	 * is done. This has potential to deadlock if synchronous module
3805 	 * loading is requested from async (which is not allowed!).
3806 	 *
3807 	 * See commit 0fdff3ec6d87 ("async, kmod: warn on synchronous
3808 	 * request_module() from async workers") for more details.
3809 	 */
3810 	if (!mod->async_probe_requested)
3811 		async_synchronize_full();
3812 
3813 	ftrace_free_mem(mod, mod->init_layout.base, mod->init_layout.base +
3814 			mod->init_layout.size);
3815 	mutex_lock(&module_mutex);
3816 	/* Drop initial reference. */
3817 	module_put(mod);
3818 	trim_init_extable(mod);
3819 #ifdef CONFIG_KALLSYMS
3820 	/* Switch to core kallsyms now init is done: kallsyms may be walking! */
3821 	rcu_assign_pointer(mod->kallsyms, &mod->core_kallsyms);
3822 #endif
3823 	module_enable_ro(mod, true);
3824 	trace_android_vh_set_module_permit_after_init(mod);
3825 	mod_tree_remove_init(mod);
3826 	module_arch_freeing_init(mod);
3827 	trace_android_vh_set_memory_rw((unsigned long)mod->init_layout.base,
3828 		(mod->init_layout.size)>>PAGE_SHIFT);
3829 	trace_android_vh_set_memory_nx((unsigned long)mod->init_layout.base,
3830 		(mod->init_layout.size)>>PAGE_SHIFT);
3831 	mod->init_layout.base = NULL;
3832 	mod->init_layout.size = 0;
3833 	mod->init_layout.ro_size = 0;
3834 	mod->init_layout.ro_after_init_size = 0;
3835 	mod->init_layout.text_size = 0;
3836 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
3837 	/* .BTF is not SHF_ALLOC and will get removed, so sanitize pointer */
3838 	mod->btf_data = NULL;
3839 #endif
3840 	/*
3841 	 * We want to free module_init, but be aware that kallsyms may be
3842 	 * walking this with preempt disabled.  In all the failure paths, we
3843 	 * call synchronize_rcu(), but we don't want to slow down the success
3844 	 * path. module_memfree() cannot be called in an interrupt, so do the
3845 	 * work and call synchronize_rcu() in a work queue.
3846 	 *
3847 	 * Note that module_alloc() on most architectures creates W+X page
3848 	 * mappings which won't be cleaned up until do_free_init() runs.  Any
3849 	 * code such as mark_rodata_ro() which depends on those mappings to
3850 	 * be cleaned up needs to sync with the queued work - ie
3851 	 * rcu_barrier()
3852 	 */
3853 	if (llist_add(&freeinit->node, &init_free_list))
3854 		schedule_work(&init_free_wq);
3855 
3856 	mutex_unlock(&module_mutex);
3857 	wake_up_all(&module_wq);
3858 
3859 	return 0;
3860 
3861 fail_free_freeinit:
3862 	kfree(freeinit);
3863 fail:
3864 	/* Try to protect us from buggy refcounters. */
3865 	mod->state = MODULE_STATE_GOING;
3866 	synchronize_rcu();
3867 	module_put(mod);
3868 	blocking_notifier_call_chain(&module_notify_list,
3869 				     MODULE_STATE_GOING, mod);
3870 	klp_module_going(mod);
3871 	ftrace_release_mod(mod);
3872 	free_module(mod);
3873 	wake_up_all(&module_wq);
3874 	return ret;
3875 }
3876 
may_init_module(void)3877 static int may_init_module(void)
3878 {
3879 	if (!capable(CAP_SYS_MODULE) || modules_disabled)
3880 		return -EPERM;
3881 
3882 	return 0;
3883 }
3884 
3885 /*
3886  * We try to place it in the list now to make sure it's unique before
3887  * we dedicate too many resources.  In particular, temporary percpu
3888  * memory exhaustion.
3889  */
add_unformed_module(struct module * mod)3890 static int add_unformed_module(struct module *mod)
3891 {
3892 	int err;
3893 	struct module *old;
3894 
3895 	mod->state = MODULE_STATE_UNFORMED;
3896 
3897 	mutex_lock(&module_mutex);
3898 	old = find_module_all(mod->name, strlen(mod->name), true);
3899 	if (old != NULL) {
3900 		if (old->state == MODULE_STATE_COMING
3901 		    || old->state == MODULE_STATE_UNFORMED) {
3902 			/* Wait in case it fails to load. */
3903 			mutex_unlock(&module_mutex);
3904 			err = wait_event_interruptible(module_wq,
3905 					       finished_loading(mod->name));
3906 			if (err)
3907 				goto out_unlocked;
3908 
3909 			/* The module might have gone in the meantime. */
3910 			mutex_lock(&module_mutex);
3911 			old = find_module_all(mod->name, strlen(mod->name),
3912 					      true);
3913 		}
3914 
3915 		/*
3916 		 * We are here only when the same module was being loaded. Do
3917 		 * not try to load it again right now. It prevents long delays
3918 		 * caused by serialized module load failures. It might happen
3919 		 * when more devices of the same type trigger load of
3920 		 * a particular module.
3921 		 */
3922 		if (old && old->state == MODULE_STATE_LIVE)
3923 			err = -EEXIST;
3924 		else
3925 			err = -EBUSY;
3926 		goto out;
3927 	}
3928 	mod_update_bounds(mod);
3929 	list_add_rcu(&mod->list, &modules);
3930 	mod_tree_insert(mod);
3931 	err = 0;
3932 
3933 out:
3934 	mutex_unlock(&module_mutex);
3935 out_unlocked:
3936 	return err;
3937 }
3938 
complete_formation(struct module * mod,struct load_info * info)3939 static int complete_formation(struct module *mod, struct load_info *info)
3940 {
3941 	int err;
3942 
3943 	mutex_lock(&module_mutex);
3944 
3945 	/* Find duplicate symbols (must be called under lock). */
3946 	err = verify_exported_symbols(mod);
3947 	if (err < 0)
3948 		goto out;
3949 
3950 	/* This relies on module_mutex for list integrity. */
3951 	module_bug_finalize(info->hdr, info->sechdrs, mod);
3952 
3953 	module_enable_ro(mod, false);
3954 	module_enable_nx(mod);
3955 	module_enable_x(mod);
3956 	trace_android_vh_set_module_permit_before_init(mod);
3957 
3958 	/*
3959 	 * Mark state as coming so strong_try_module_get() ignores us,
3960 	 * but kallsyms etc. can see us.
3961 	 */
3962 	mod->state = MODULE_STATE_COMING;
3963 	mutex_unlock(&module_mutex);
3964 
3965 	return 0;
3966 
3967 out:
3968 	mutex_unlock(&module_mutex);
3969 	return err;
3970 }
3971 
prepare_coming_module(struct module * mod)3972 static int prepare_coming_module(struct module *mod)
3973 {
3974 	int err;
3975 
3976 	ftrace_module_enable(mod);
3977 	err = klp_module_coming(mod);
3978 	if (err)
3979 		return err;
3980 
3981 	err = blocking_notifier_call_chain_robust(&module_notify_list,
3982 			MODULE_STATE_COMING, MODULE_STATE_GOING, mod);
3983 	err = notifier_to_errno(err);
3984 	if (err)
3985 		klp_module_going(mod);
3986 
3987 	return err;
3988 }
3989 
unknown_module_param_cb(char * param,char * val,const char * modname,void * arg)3990 static int unknown_module_param_cb(char *param, char *val, const char *modname,
3991 				   void *arg)
3992 {
3993 	struct module *mod = arg;
3994 	int ret;
3995 
3996 	if (strcmp(param, "async_probe") == 0) {
3997 		mod->async_probe_requested = true;
3998 		return 0;
3999 	}
4000 
4001 	/* Check for magic 'dyndbg' arg */
4002 	ret = ddebug_dyndbg_module_param_cb(param, val, modname);
4003 	if (ret != 0)
4004 		pr_warn("%s: unknown parameter '%s' ignored\n", modname, param);
4005 	return 0;
4006 }
4007 
4008 static void cfi_init(struct module *mod);
4009 
4010 /*
4011  * Allocate and load the module: note that size of section 0 is always
4012  * zero, and we rely on this for optional sections.
4013  */
load_module(struct load_info * info,const char __user * uargs,int flags)4014 static int load_module(struct load_info *info, const char __user *uargs,
4015 		       int flags)
4016 {
4017 	struct module *mod;
4018 	long err = 0;
4019 	char *after_dashes;
4020 
4021 	/*
4022 	 * Do the signature check (if any) first. All that
4023 	 * the signature check needs is info->len, it does
4024 	 * not need any of the section info. That can be
4025 	 * set up later. This will minimize the chances
4026 	 * of a corrupt module causing problems before
4027 	 * we even get to the signature check.
4028 	 *
4029 	 * The check will also adjust info->len by stripping
4030 	 * off the sig length at the end of the module, making
4031 	 * checks against info->len more correct.
4032 	 */
4033 	err = module_sig_check(info, flags);
4034 	if (err)
4035 		goto free_copy;
4036 
4037 	/*
4038 	 * Do basic sanity checks against the ELF header and
4039 	 * sections.
4040 	 */
4041 	err = elf_validity_check(info);
4042 	if (err)
4043 		goto free_copy;
4044 
4045 	/*
4046 	 * Everything checks out, so set up the section info
4047 	 * in the info structure.
4048 	 */
4049 	err = setup_load_info(info, flags);
4050 	if (err)
4051 		goto free_copy;
4052 
4053 	/*
4054 	 * Now that we know we have the correct module name, check
4055 	 * if it's blacklisted.
4056 	 */
4057 	if (blacklisted(info->name)) {
4058 		err = -EPERM;
4059 		pr_err("Module %s is blacklisted\n", info->name);
4060 		goto free_copy;
4061 	}
4062 
4063 	err = rewrite_section_headers(info, flags);
4064 	if (err)
4065 		goto free_copy;
4066 
4067 	/* Check module struct version now, before we try to use module. */
4068 	if (!check_modstruct_version(info, info->mod)) {
4069 		err = -ENOEXEC;
4070 		goto free_copy;
4071 	}
4072 
4073 	/* Figure out module layout, and allocate all the memory. */
4074 	mod = layout_and_allocate(info, flags);
4075 	if (IS_ERR(mod)) {
4076 		err = PTR_ERR(mod);
4077 		goto free_copy;
4078 	}
4079 
4080 	audit_log_kern_module(mod->name);
4081 
4082 	/* Reserve our place in the list. */
4083 	err = add_unformed_module(mod);
4084 	if (err)
4085 		goto free_module;
4086 
4087 #ifdef CONFIG_MODULE_SIG
4088 	mod->sig_ok = info->sig_ok;
4089 	if (!mod->sig_ok) {
4090 		pr_notice_once("%s: module verification failed: signature "
4091 			       "and/or required key missing - tainting "
4092 			       "kernel\n", mod->name);
4093 		add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
4094 	}
4095 #else
4096 	mod->sig_ok = 0;
4097 #endif
4098 
4099 	/* To avoid stressing percpu allocator, do this once we're unique. */
4100 	err = percpu_modalloc(mod, info);
4101 	if (err)
4102 		goto unlink_mod;
4103 
4104 	/* Now module is in final location, initialize linked lists, etc. */
4105 	err = module_unload_init(mod);
4106 	if (err)
4107 		goto unlink_mod;
4108 
4109 	init_param_lock(mod);
4110 
4111 	/*
4112 	 * Now we've got everything in the final locations, we can
4113 	 * find optional sections.
4114 	 */
4115 	err = find_module_sections(mod, info);
4116 	if (err)
4117 		goto free_unload;
4118 
4119 	err = check_module_license_and_versions(mod);
4120 	if (err)
4121 		goto free_unload;
4122 
4123 	/* Set up MODINFO_ATTR fields */
4124 	setup_modinfo(mod, info);
4125 
4126 	/* Fix up syms, so that st_value is a pointer to location. */
4127 	err = simplify_symbols(mod, info);
4128 	if (err < 0)
4129 		goto free_modinfo;
4130 
4131 	err = apply_relocations(mod, info);
4132 	if (err < 0)
4133 		goto free_modinfo;
4134 
4135 	err = post_relocation(mod, info);
4136 	if (err < 0)
4137 		goto free_modinfo;
4138 
4139 	flush_module_icache(mod);
4140 
4141 	/* Setup CFI for the module. */
4142 	cfi_init(mod);
4143 
4144 	/* Now copy in args */
4145 	mod->args = strndup_user(uargs, ~0UL >> 1);
4146 	if (IS_ERR(mod->args)) {
4147 		err = PTR_ERR(mod->args);
4148 		goto free_arch_cleanup;
4149 	}
4150 
4151 	init_build_id(mod, info);
4152 	dynamic_debug_setup(mod, info->debug, info->num_debug);
4153 
4154 	/* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
4155 	ftrace_module_init(mod);
4156 
4157 	/* Finally it's fully formed, ready to start executing. */
4158 	err = complete_formation(mod, info);
4159 	if (err)
4160 		goto ddebug_cleanup;
4161 
4162 	err = prepare_coming_module(mod);
4163 	if (err)
4164 		goto bug_cleanup;
4165 
4166 	/* Module is ready to execute: parsing args may do that. */
4167 	after_dashes = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
4168 				  -32768, 32767, mod,
4169 				  unknown_module_param_cb);
4170 	if (IS_ERR(after_dashes)) {
4171 		err = PTR_ERR(after_dashes);
4172 		goto coming_cleanup;
4173 	} else if (after_dashes) {
4174 		pr_warn("%s: parameters '%s' after `--' ignored\n",
4175 		       mod->name, after_dashes);
4176 	}
4177 
4178 	/* Link in to sysfs. */
4179 	err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
4180 	if (err < 0)
4181 		goto coming_cleanup;
4182 
4183 	if (is_livepatch_module(mod)) {
4184 		err = copy_module_elf(mod, info);
4185 		if (err < 0)
4186 			goto sysfs_cleanup;
4187 	}
4188 
4189 	/* Get rid of temporary copy. */
4190 	free_copy(info);
4191 
4192 	/* Done! */
4193 	trace_module_load(mod);
4194 
4195 	return do_init_module(mod);
4196 
4197  sysfs_cleanup:
4198 	mod_sysfs_teardown(mod);
4199  coming_cleanup:
4200 	mod->state = MODULE_STATE_GOING;
4201 	destroy_params(mod->kp, mod->num_kp);
4202 	blocking_notifier_call_chain(&module_notify_list,
4203 				     MODULE_STATE_GOING, mod);
4204 	klp_module_going(mod);
4205  bug_cleanup:
4206 	mod->state = MODULE_STATE_GOING;
4207 	/* module_bug_cleanup needs module_mutex protection */
4208 	mutex_lock(&module_mutex);
4209 	module_bug_cleanup(mod);
4210 	mutex_unlock(&module_mutex);
4211 
4212  ddebug_cleanup:
4213 	ftrace_release_mod(mod);
4214 	dynamic_debug_remove(mod, info->debug);
4215 	synchronize_rcu();
4216 	kfree(mod->args);
4217  free_arch_cleanup:
4218 	cfi_cleanup(mod);
4219 	module_arch_cleanup(mod);
4220  free_modinfo:
4221 	free_modinfo(mod);
4222  free_unload:
4223 	module_unload_free(mod);
4224  unlink_mod:
4225 	mutex_lock(&module_mutex);
4226 	/* Unlink carefully: kallsyms could be walking list. */
4227 	list_del_rcu(&mod->list);
4228 	mod_tree_remove(mod);
4229 	wake_up_all(&module_wq);
4230 	/* Wait for RCU-sched synchronizing before releasing mod->list. */
4231 	synchronize_rcu();
4232 	mutex_unlock(&module_mutex);
4233  free_module:
4234 	/* Free lock-classes; relies on the preceding sync_rcu() */
4235 	lockdep_free_key_range(mod->core_layout.base, mod->core_layout.size);
4236 
4237 	module_deallocate(mod, info);
4238  free_copy:
4239 	free_copy(info);
4240 	return err;
4241 }
4242 
SYSCALL_DEFINE3(init_module,void __user *,umod,unsigned long,len,const char __user *,uargs)4243 SYSCALL_DEFINE3(init_module, void __user *, umod,
4244 		unsigned long, len, const char __user *, uargs)
4245 {
4246 	int err;
4247 	struct load_info info = { };
4248 
4249 	err = may_init_module();
4250 	if (err)
4251 		return err;
4252 
4253 	pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
4254 	       umod, len, uargs);
4255 
4256 	err = copy_module_from_user(umod, len, &info);
4257 	if (err)
4258 		return err;
4259 
4260 	return load_module(&info, uargs, 0);
4261 }
4262 
SYSCALL_DEFINE3(finit_module,int,fd,const char __user *,uargs,int,flags)4263 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
4264 {
4265 	struct load_info info = { };
4266 	void *hdr = NULL;
4267 	int err;
4268 
4269 	err = may_init_module();
4270 	if (err)
4271 		return err;
4272 
4273 	pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
4274 
4275 	if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
4276 		      |MODULE_INIT_IGNORE_VERMAGIC))
4277 		return -EINVAL;
4278 
4279 	err = kernel_read_file_from_fd(fd, 0, &hdr, INT_MAX, NULL,
4280 				       READING_MODULE);
4281 	if (err < 0)
4282 		return err;
4283 	info.hdr = hdr;
4284 	info.len = err;
4285 
4286 	return load_module(&info, uargs, flags);
4287 }
4288 
within(unsigned long addr,void * start,unsigned long size)4289 static inline int within(unsigned long addr, void *start, unsigned long size)
4290 {
4291 	return ((void *)addr >= start && (void *)addr < start + size);
4292 }
4293 
4294 #ifdef CONFIG_KALLSYMS
4295 /*
4296  * This ignores the intensely annoying "mapping symbols" found
4297  * in ARM ELF files: $a, $t and $d.
4298  */
is_arm_mapping_symbol(const char * str)4299 static inline int is_arm_mapping_symbol(const char *str)
4300 {
4301 	if (str[0] == '.' && str[1] == 'L')
4302 		return true;
4303 	return str[0] == '$' && strchr("axtd", str[1])
4304 	       && (str[2] == '\0' || str[2] == '.');
4305 }
4306 
kallsyms_symbol_name(struct mod_kallsyms * kallsyms,unsigned int symnum)4307 static const char *kallsyms_symbol_name(struct mod_kallsyms *kallsyms, unsigned int symnum)
4308 {
4309 	return kallsyms->strtab + kallsyms->symtab[symnum].st_name;
4310 }
4311 
4312 /*
4313  * Given a module and address, find the corresponding symbol and return its name
4314  * while providing its size and offset if needed.
4315  */
find_kallsyms_symbol(struct module * mod,unsigned long addr,unsigned long * size,unsigned long * offset)4316 static const char *find_kallsyms_symbol(struct module *mod,
4317 					unsigned long addr,
4318 					unsigned long *size,
4319 					unsigned long *offset)
4320 {
4321 	unsigned int i, best = 0;
4322 	unsigned long nextval, bestval;
4323 	struct mod_kallsyms *kallsyms = rcu_dereference_sched(mod->kallsyms);
4324 
4325 	/* At worse, next value is at end of module */
4326 	if (within_module_init(addr, mod))
4327 		nextval = (unsigned long)mod->init_layout.base+mod->init_layout.text_size;
4328 	else
4329 		nextval = (unsigned long)mod->core_layout.base+mod->core_layout.text_size;
4330 
4331 	bestval = kallsyms_symbol_value(&kallsyms->symtab[best]);
4332 
4333 	/*
4334 	 * Scan for closest preceding symbol, and next symbol. (ELF
4335 	 * starts real symbols at 1).
4336 	 */
4337 	for (i = 1; i < kallsyms->num_symtab; i++) {
4338 		const Elf_Sym *sym = &kallsyms->symtab[i];
4339 		unsigned long thisval = kallsyms_symbol_value(sym);
4340 
4341 		if (sym->st_shndx == SHN_UNDEF)
4342 			continue;
4343 
4344 		/*
4345 		 * We ignore unnamed symbols: they're uninformative
4346 		 * and inserted at a whim.
4347 		 */
4348 		if (*kallsyms_symbol_name(kallsyms, i) == '\0'
4349 		    || is_arm_mapping_symbol(kallsyms_symbol_name(kallsyms, i)))
4350 			continue;
4351 
4352 		if (thisval <= addr && thisval > bestval) {
4353 			best = i;
4354 			bestval = thisval;
4355 		}
4356 		if (thisval > addr && thisval < nextval)
4357 			nextval = thisval;
4358 	}
4359 
4360 	if (!best)
4361 		return NULL;
4362 
4363 	if (size)
4364 		*size = nextval - bestval;
4365 	if (offset)
4366 		*offset = addr - bestval;
4367 
4368 	return kallsyms_symbol_name(kallsyms, best);
4369 }
4370 
dereference_module_function_descriptor(struct module * mod,void * ptr)4371 void * __weak dereference_module_function_descriptor(struct module *mod,
4372 						     void *ptr)
4373 {
4374 	return ptr;
4375 }
4376 
4377 /*
4378  * For kallsyms to ask for address resolution.  NULL means not found.  Careful
4379  * not to lock to avoid deadlock on oopses, simply disable preemption.
4380  */
module_address_lookup(unsigned long addr,unsigned long * size,unsigned long * offset,char ** modname,const unsigned char ** modbuildid,char * namebuf)4381 const char *module_address_lookup(unsigned long addr,
4382 			    unsigned long *size,
4383 			    unsigned long *offset,
4384 			    char **modname,
4385 			    const unsigned char **modbuildid,
4386 			    char *namebuf)
4387 {
4388 	const char *ret = NULL;
4389 	struct module *mod;
4390 
4391 	preempt_disable();
4392 	mod = __module_address(addr);
4393 	if (mod) {
4394 		if (modname)
4395 			*modname = mod->name;
4396 		if (modbuildid) {
4397 #if IS_ENABLED(CONFIG_STACKTRACE_BUILD_ID)
4398 			*modbuildid = mod->build_id;
4399 #else
4400 			*modbuildid = NULL;
4401 #endif
4402 		}
4403 
4404 		ret = find_kallsyms_symbol(mod, addr, size, offset);
4405 	}
4406 	/* Make a copy in here where it's safe */
4407 	if (ret) {
4408 		strncpy(namebuf, ret, KSYM_NAME_LEN - 1);
4409 		ret = namebuf;
4410 	}
4411 	preempt_enable();
4412 
4413 	return ret;
4414 }
4415 
lookup_module_symbol_name(unsigned long addr,char * symname)4416 int lookup_module_symbol_name(unsigned long addr, char *symname)
4417 {
4418 	struct module *mod;
4419 
4420 	preempt_disable();
4421 	list_for_each_entry_rcu(mod, &modules, list) {
4422 		if (mod->state == MODULE_STATE_UNFORMED)
4423 			continue;
4424 		if (within_module(addr, mod)) {
4425 			const char *sym;
4426 
4427 			sym = find_kallsyms_symbol(mod, addr, NULL, NULL);
4428 			if (!sym)
4429 				goto out;
4430 
4431 			strlcpy(symname, sym, KSYM_NAME_LEN);
4432 			preempt_enable();
4433 			return 0;
4434 		}
4435 	}
4436 out:
4437 	preempt_enable();
4438 	return -ERANGE;
4439 }
4440 
lookup_module_symbol_attrs(unsigned long addr,unsigned long * size,unsigned long * offset,char * modname,char * name)4441 int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size,
4442 			unsigned long *offset, char *modname, char *name)
4443 {
4444 	struct module *mod;
4445 
4446 	preempt_disable();
4447 	list_for_each_entry_rcu(mod, &modules, list) {
4448 		if (mod->state == MODULE_STATE_UNFORMED)
4449 			continue;
4450 		if (within_module(addr, mod)) {
4451 			const char *sym;
4452 
4453 			sym = find_kallsyms_symbol(mod, addr, size, offset);
4454 			if (!sym)
4455 				goto out;
4456 			if (modname)
4457 				strlcpy(modname, mod->name, MODULE_NAME_LEN);
4458 			if (name)
4459 				strlcpy(name, sym, KSYM_NAME_LEN);
4460 			preempt_enable();
4461 			return 0;
4462 		}
4463 	}
4464 out:
4465 	preempt_enable();
4466 	return -ERANGE;
4467 }
4468 
module_get_kallsym(unsigned int symnum,unsigned long * value,char * type,char * name,char * module_name,int * exported)4469 int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
4470 			char *name, char *module_name, int *exported)
4471 {
4472 	struct module *mod;
4473 
4474 	preempt_disable();
4475 	list_for_each_entry_rcu(mod, &modules, list) {
4476 		struct mod_kallsyms *kallsyms;
4477 
4478 		if (mod->state == MODULE_STATE_UNFORMED)
4479 			continue;
4480 		kallsyms = rcu_dereference_sched(mod->kallsyms);
4481 		if (symnum < kallsyms->num_symtab) {
4482 			const Elf_Sym *sym = &kallsyms->symtab[symnum];
4483 
4484 			*value = kallsyms_symbol_value(sym);
4485 			*type = kallsyms->typetab[symnum];
4486 			strlcpy(name, kallsyms_symbol_name(kallsyms, symnum), KSYM_NAME_LEN);
4487 			strlcpy(module_name, mod->name, MODULE_NAME_LEN);
4488 			*exported = is_exported(name, *value, mod);
4489 			preempt_enable();
4490 			return 0;
4491 		}
4492 		symnum -= kallsyms->num_symtab;
4493 	}
4494 	preempt_enable();
4495 	return -ERANGE;
4496 }
4497 
4498 /* Given a module and name of symbol, find and return the symbol's value */
find_kallsyms_symbol_value(struct module * mod,const char * name)4499 static unsigned long find_kallsyms_symbol_value(struct module *mod, const char *name)
4500 {
4501 	unsigned int i;
4502 	struct mod_kallsyms *kallsyms = rcu_dereference_sched(mod->kallsyms);
4503 
4504 	for (i = 0; i < kallsyms->num_symtab; i++) {
4505 		const Elf_Sym *sym = &kallsyms->symtab[i];
4506 
4507 		if (strcmp(name, kallsyms_symbol_name(kallsyms, i)) == 0 &&
4508 		    sym->st_shndx != SHN_UNDEF)
4509 			return kallsyms_symbol_value(sym);
4510 	}
4511 	return 0;
4512 }
4513 
4514 /* Look for this name: can be of form module:name. */
module_kallsyms_lookup_name(const char * name)4515 unsigned long module_kallsyms_lookup_name(const char *name)
4516 {
4517 	struct module *mod;
4518 	char *colon;
4519 	unsigned long ret = 0;
4520 
4521 	/* Don't lock: we're in enough trouble already. */
4522 	preempt_disable();
4523 	if ((colon = strnchr(name, MODULE_NAME_LEN, ':')) != NULL) {
4524 		if ((mod = find_module_all(name, colon - name, false)) != NULL)
4525 			ret = find_kallsyms_symbol_value(mod, colon+1);
4526 	} else {
4527 		list_for_each_entry_rcu(mod, &modules, list) {
4528 			if (mod->state == MODULE_STATE_UNFORMED)
4529 				continue;
4530 			if ((ret = find_kallsyms_symbol_value(mod, name)) != 0)
4531 				break;
4532 		}
4533 	}
4534 	preempt_enable();
4535 	return ret;
4536 }
4537 
module_kallsyms_on_each_symbol(int (* fn)(void *,const char *,struct module *,unsigned long),void * data)4538 int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
4539 					     struct module *, unsigned long),
4540 				   void *data)
4541 {
4542 	struct module *mod;
4543 	unsigned int i;
4544 	int ret = 0;
4545 
4546 	mutex_lock(&module_mutex);
4547 	list_for_each_entry(mod, &modules, list) {
4548 		/* We hold module_mutex: no need for rcu_dereference_sched */
4549 		struct mod_kallsyms *kallsyms = mod->kallsyms;
4550 
4551 		if (mod->state == MODULE_STATE_UNFORMED)
4552 			continue;
4553 		for (i = 0; i < kallsyms->num_symtab; i++) {
4554 			const Elf_Sym *sym = &kallsyms->symtab[i];
4555 
4556 			if (sym->st_shndx == SHN_UNDEF)
4557 				continue;
4558 
4559 			ret = fn(data, kallsyms_symbol_name(kallsyms, i),
4560 				 mod, kallsyms_symbol_value(sym));
4561 			if (ret != 0)
4562 				goto out;
4563 		}
4564 	}
4565 out:
4566 	mutex_unlock(&module_mutex);
4567 	return ret;
4568 }
4569 #endif /* CONFIG_KALLSYMS */
4570 
cfi_init(struct module * mod)4571 static void cfi_init(struct module *mod)
4572 {
4573 #ifdef CONFIG_CFI_CLANG
4574 	initcall_t *init;
4575 	exitcall_t *exit;
4576 
4577 	rcu_read_lock_sched();
4578 	mod->cfi_check = (cfi_check_fn)
4579 		find_kallsyms_symbol_value(mod, "__cfi_check");
4580 	init = (initcall_t *)
4581 		find_kallsyms_symbol_value(mod, "__cfi_jt_init_module");
4582 	exit = (exitcall_t *)
4583 		find_kallsyms_symbol_value(mod, "__cfi_jt_cleanup_module");
4584 	rcu_read_unlock_sched();
4585 
4586 	/* Fix init/exit functions to point to the CFI jump table */
4587 	if (init)
4588 		mod->init = *init;
4589 #ifdef CONFIG_MODULE_UNLOAD
4590 	if (exit)
4591 		mod->exit = *exit;
4592 #endif
4593 
4594 	cfi_module_add(mod, module_addr_min);
4595 #endif
4596 }
4597 
cfi_cleanup(struct module * mod)4598 static void cfi_cleanup(struct module *mod)
4599 {
4600 #ifdef CONFIG_CFI_CLANG
4601 	cfi_module_remove(mod, module_addr_min);
4602 #endif
4603 }
4604 
4605 /* Maximum number of characters written by module_flags() */
4606 #define MODULE_FLAGS_BUF_SIZE (TAINT_FLAGS_COUNT + 4)
4607 
4608 /* Keep in sync with MODULE_FLAGS_BUF_SIZE !!! */
module_flags(struct module * mod,char * buf)4609 static char *module_flags(struct module *mod, char *buf)
4610 {
4611 	int bx = 0;
4612 
4613 	BUG_ON(mod->state == MODULE_STATE_UNFORMED);
4614 	if (mod->taints ||
4615 	    mod->state == MODULE_STATE_GOING ||
4616 	    mod->state == MODULE_STATE_COMING) {
4617 		buf[bx++] = '(';
4618 		bx += module_flags_taint(mod, buf + bx);
4619 		/* Show a - for module-is-being-unloaded */
4620 		if (mod->state == MODULE_STATE_GOING)
4621 			buf[bx++] = '-';
4622 		/* Show a + for module-is-being-loaded */
4623 		if (mod->state == MODULE_STATE_COMING)
4624 			buf[bx++] = '+';
4625 		buf[bx++] = ')';
4626 	}
4627 	buf[bx] = '\0';
4628 
4629 	return buf;
4630 }
4631 
4632 #ifdef CONFIG_PROC_FS
4633 /* Called by the /proc file system to return a list of modules. */
m_start(struct seq_file * m,loff_t * pos)4634 static void *m_start(struct seq_file *m, loff_t *pos)
4635 {
4636 	mutex_lock(&module_mutex);
4637 	return seq_list_start(&modules, *pos);
4638 }
4639 
m_next(struct seq_file * m,void * p,loff_t * pos)4640 static void *m_next(struct seq_file *m, void *p, loff_t *pos)
4641 {
4642 	return seq_list_next(p, &modules, pos);
4643 }
4644 
m_stop(struct seq_file * m,void * p)4645 static void m_stop(struct seq_file *m, void *p)
4646 {
4647 	mutex_unlock(&module_mutex);
4648 }
4649 
m_show(struct seq_file * m,void * p)4650 static int m_show(struct seq_file *m, void *p)
4651 {
4652 	struct module *mod = list_entry(p, struct module, list);
4653 	char buf[MODULE_FLAGS_BUF_SIZE];
4654 	void *value;
4655 
4656 	/* We always ignore unformed modules. */
4657 	if (mod->state == MODULE_STATE_UNFORMED)
4658 		return 0;
4659 
4660 	seq_printf(m, "%s %u",
4661 		   mod->name, mod->init_layout.size + mod->core_layout.size);
4662 	print_unload_info(m, mod);
4663 
4664 	/* Informative for users. */
4665 	seq_printf(m, " %s",
4666 		   mod->state == MODULE_STATE_GOING ? "Unloading" :
4667 		   mod->state == MODULE_STATE_COMING ? "Loading" :
4668 		   "Live");
4669 	/* Used by oprofile and other similar tools. */
4670 	value = m->private ? NULL : mod->core_layout.base;
4671 	seq_printf(m, " 0x%px", value);
4672 
4673 	/* Taints info */
4674 	if (mod->taints)
4675 		seq_printf(m, " %s", module_flags(mod, buf));
4676 
4677 	seq_puts(m, "\n");
4678 	return 0;
4679 }
4680 
4681 /*
4682  * Format: modulename size refcount deps address
4683  *
4684  * Where refcount is a number or -, and deps is a comma-separated list
4685  * of depends or -.
4686  */
4687 static const struct seq_operations modules_op = {
4688 	.start	= m_start,
4689 	.next	= m_next,
4690 	.stop	= m_stop,
4691 	.show	= m_show
4692 };
4693 
4694 /*
4695  * This also sets the "private" pointer to non-NULL if the
4696  * kernel pointers should be hidden (so you can just test
4697  * "m->private" to see if you should keep the values private).
4698  *
4699  * We use the same logic as for /proc/kallsyms.
4700  */
modules_open(struct inode * inode,struct file * file)4701 static int modules_open(struct inode *inode, struct file *file)
4702 {
4703 	int err = seq_open(file, &modules_op);
4704 
4705 	if (!err) {
4706 		struct seq_file *m = file->private_data;
4707 		m->private = kallsyms_show_value(file->f_cred) ? NULL : (void *)8ul;
4708 	}
4709 
4710 	return err;
4711 }
4712 
4713 static const struct proc_ops modules_proc_ops = {
4714 	.proc_flags	= PROC_ENTRY_PERMANENT,
4715 	.proc_open	= modules_open,
4716 	.proc_read	= seq_read,
4717 	.proc_lseek	= seq_lseek,
4718 	.proc_release	= seq_release,
4719 };
4720 
proc_modules_init(void)4721 static int __init proc_modules_init(void)
4722 {
4723 	proc_create("modules", 0, NULL, &modules_proc_ops);
4724 	return 0;
4725 }
4726 module_init(proc_modules_init);
4727 #endif
4728 
4729 /* Given an address, look for it in the module exception tables. */
search_module_extables(unsigned long addr)4730 const struct exception_table_entry *search_module_extables(unsigned long addr)
4731 {
4732 	const struct exception_table_entry *e = NULL;
4733 	struct module *mod;
4734 
4735 	preempt_disable();
4736 	mod = __module_address(addr);
4737 	if (!mod)
4738 		goto out;
4739 
4740 	if (!mod->num_exentries)
4741 		goto out;
4742 
4743 	e = search_extable(mod->extable,
4744 			   mod->num_exentries,
4745 			   addr);
4746 out:
4747 	preempt_enable();
4748 
4749 	/*
4750 	 * Now, if we found one, we are running inside it now, hence
4751 	 * we cannot unload the module, hence no refcnt needed.
4752 	 */
4753 	return e;
4754 }
4755 
4756 /**
4757  * is_module_address() - is this address inside a module?
4758  * @addr: the address to check.
4759  *
4760  * See is_module_text_address() if you simply want to see if the address
4761  * is code (not data).
4762  */
is_module_address(unsigned long addr)4763 bool is_module_address(unsigned long addr)
4764 {
4765 	bool ret;
4766 
4767 	preempt_disable();
4768 	ret = __module_address(addr) != NULL;
4769 	preempt_enable();
4770 
4771 	return ret;
4772 }
4773 
4774 /**
4775  * __module_address() - get the module which contains an address.
4776  * @addr: the address.
4777  *
4778  * Must be called with preempt disabled or module mutex held so that
4779  * module doesn't get freed during this.
4780  */
__module_address(unsigned long addr)4781 struct module *__module_address(unsigned long addr)
4782 {
4783 	struct module *mod;
4784 
4785 	if (addr < module_addr_min || addr > module_addr_max)
4786 		return NULL;
4787 
4788 	module_assert_mutex_or_preempt();
4789 
4790 	mod = mod_find(addr);
4791 	if (mod) {
4792 		BUG_ON(!within_module(addr, mod));
4793 		if (mod->state == MODULE_STATE_UNFORMED)
4794 			mod = NULL;
4795 	}
4796 	return mod;
4797 }
4798 
4799 /**
4800  * is_module_text_address() - is this address inside module code?
4801  * @addr: the address to check.
4802  *
4803  * See is_module_address() if you simply want to see if the address is
4804  * anywhere in a module.  See kernel_text_address() for testing if an
4805  * address corresponds to kernel or module code.
4806  */
is_module_text_address(unsigned long addr)4807 bool is_module_text_address(unsigned long addr)
4808 {
4809 	bool ret;
4810 
4811 	preempt_disable();
4812 	ret = __module_text_address(addr) != NULL;
4813 	preempt_enable();
4814 
4815 	return ret;
4816 }
4817 
4818 /**
4819  * __module_text_address() - get the module whose code contains an address.
4820  * @addr: the address.
4821  *
4822  * Must be called with preempt disabled or module mutex held so that
4823  * module doesn't get freed during this.
4824  */
__module_text_address(unsigned long addr)4825 struct module *__module_text_address(unsigned long addr)
4826 {
4827 	struct module *mod = __module_address(addr);
4828 	if (mod) {
4829 		/* Make sure it's within the text section. */
4830 		if (!within(addr, mod->init_layout.base, mod->init_layout.text_size)
4831 		    && !within(addr, mod->core_layout.base, mod->core_layout.text_size))
4832 			mod = NULL;
4833 	}
4834 	return mod;
4835 }
4836 
4837 /* Don't grab lock, we're oopsing. */
print_modules(void)4838 void print_modules(void)
4839 {
4840 	struct module *mod;
4841 	char buf[MODULE_FLAGS_BUF_SIZE];
4842 
4843 	printk(KERN_DEFAULT "Modules linked in:");
4844 	/* Most callers should already have preempt disabled, but make sure */
4845 	preempt_disable();
4846 	list_for_each_entry_rcu(mod, &modules, list) {
4847 		if (mod->state == MODULE_STATE_UNFORMED)
4848 			continue;
4849 		pr_cont(" %s%s", mod->name, module_flags(mod, buf));
4850 	}
4851 	preempt_enable();
4852 	if (last_unloaded_module[0])
4853 		pr_cont(" [last unloaded: %s]", last_unloaded_module);
4854 	pr_cont("\n");
4855 }
4856 
4857 #ifdef CONFIG_ANDROID_DEBUG_SYMBOLS
android_debug_for_each_module(int (* fn)(const char * mod_name,void * mod_addr,void * data),void * data)4858 void android_debug_for_each_module(int (*fn)(const char *mod_name, void *mod_addr, void *data),
4859 	void *data)
4860 {
4861 	struct module *module;
4862 	preempt_disable();
4863 	list_for_each_entry_rcu(module, &modules, list) {
4864 		if (fn(module->name, module->core_layout.base, data))
4865 			goto out;
4866 	}
4867 out:
4868 	preempt_enable();
4869 }
4870 EXPORT_SYMBOL_NS_GPL(android_debug_for_each_module, MINIDUMP);
4871 #endif
4872 
4873 #ifdef CONFIG_MODVERSIONS
4874 /*
4875  * Generate the signature for all relevant module structures here.
4876  * If these change, we don't want to try to parse the module.
4877  */
module_layout(struct module * mod,struct modversion_info * ver,struct kernel_param * kp,struct kernel_symbol * ks,struct tracepoint * const * tp)4878 void module_layout(struct module *mod,
4879 		   struct modversion_info *ver,
4880 		   struct kernel_param *kp,
4881 		   struct kernel_symbol *ks,
4882 		   struct tracepoint * const *tp)
4883 {
4884 }
4885 EXPORT_SYMBOL(module_layout);
4886 #endif
4887