• 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/fs.h>
18 #include <linux/kernel.h>
19 #include <linux/kernel_read_file.h>
20 #include <linux/slab.h>
21 #include <linux/vmalloc.h>
22 #include <linux/elf.h>
23 #include <linux/seq_file.h>
24 #include <linux/syscalls.h>
25 #include <linux/fcntl.h>
26 #include <linux/rcupdate.h>
27 #include <linux/capability.h>
28 #include <linux/cpu.h>
29 #include <linux/moduleparam.h>
30 #include <linux/errno.h>
31 #include <linux/err.h>
32 #include <linux/vermagic.h>
33 #include <linux/notifier.h>
34 #include <linux/sched.h>
35 #include <linux/device.h>
36 #include <linux/string.h>
37 #include <linux/mutex.h>
38 #include <linux/rculist.h>
39 #include <linux/uaccess.h>
40 #include <asm/cacheflush.h>
41 #include <linux/set_memory.h>
42 #include <asm/mmu_context.h>
43 #include <linux/license.h>
44 #include <asm/sections.h>
45 #include <linux/tracepoint.h>
46 #include <linux/ftrace.h>
47 #include <linux/livepatch.h>
48 #include <linux/async.h>
49 #include <linux/percpu.h>
50 #include <linux/kmemleak.h>
51 #include <linux/jump_label.h>
52 #include <linux/pfn.h>
53 #include <linux/bsearch.h>
54 #include <linux/dynamic_debug.h>
55 #include <linux/audit.h>
56 #include <linux/cfi.h>
57 #include <uapi/linux/module.h>
58 #include "internal.h"
59 
60 #define CREATE_TRACE_POINTS
61 #include <trace/events/module.h>
62 
63 #undef CREATE_TRACE_POINTS
64 #include <trace/hooks/module.h>
65 
66 /*
67  * Mutex protects:
68  * 1) List of modules (also safely readable with preempt_disable),
69  * 2) module_use links,
70  * 3) mod_tree.addr_min/mod_tree.addr_max.
71  * (delete and add uses RCU list operations).
72  */
73 DEFINE_MUTEX(module_mutex);
74 LIST_HEAD(modules);
75 
76 /* Work queue for freeing init sections in success case */
77 static void do_free_init(struct work_struct *w);
78 static DECLARE_WORK(init_free_wq, do_free_init);
79 static LLIST_HEAD(init_free_list);
80 
81 struct mod_tree_root mod_tree __cacheline_aligned = {
82 	.addr_min = -1UL,
83 };
84 
85 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
86 struct mod_tree_root mod_data_tree __cacheline_aligned = {
87 	.addr_min = -1UL,
88 };
89 #endif
90 
91 #define module_addr_min mod_tree.addr_min
92 #define module_addr_max mod_tree.addr_max
93 
94 struct symsearch {
95 	const struct kernel_symbol *start, *stop;
96 	const s32 *crcs;
97 	enum mod_license license;
98 };
99 
100 /*
101  * Bounds of module text, for speeding up __module_address.
102  * Protected by module_mutex.
103  */
__mod_update_bounds(void * base,unsigned int size,struct mod_tree_root * tree)104 static void __mod_update_bounds(void *base, unsigned int size, struct mod_tree_root *tree)
105 {
106 	unsigned long min = (unsigned long)base;
107 	unsigned long max = min + size;
108 
109 	if (min < tree->addr_min)
110 		tree->addr_min = min;
111 	if (max > tree->addr_max)
112 		tree->addr_max = max;
113 }
114 
mod_update_bounds(struct module * mod)115 static void mod_update_bounds(struct module *mod)
116 {
117 	__mod_update_bounds(mod->core_layout.base, mod->core_layout.size, &mod_tree);
118 	if (mod->init_layout.size)
119 		__mod_update_bounds(mod->init_layout.base, mod->init_layout.size, &mod_tree);
120 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
121 	__mod_update_bounds(mod->data_layout.base, mod->data_layout.size, &mod_data_tree);
122 #endif
123 }
124 
125 /* Block module loading/unloading? */
126 int modules_disabled;
127 core_param(nomodule, modules_disabled, bint, 0);
128 
129 /* Waiting for a module to finish initializing? */
130 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
131 
132 static BLOCKING_NOTIFIER_HEAD(module_notify_list);
133 
register_module_notifier(struct notifier_block * nb)134 int register_module_notifier(struct notifier_block *nb)
135 {
136 	return blocking_notifier_chain_register(&module_notify_list, nb);
137 }
138 EXPORT_SYMBOL(register_module_notifier);
139 
unregister_module_notifier(struct notifier_block * nb)140 int unregister_module_notifier(struct notifier_block *nb)
141 {
142 	return blocking_notifier_chain_unregister(&module_notify_list, nb);
143 }
144 EXPORT_SYMBOL(unregister_module_notifier);
145 
146 /*
147  * We require a truly strong try_module_get(): 0 means success.
148  * Otherwise an error is returned due to ongoing or failed
149  * initialization etc.
150  */
strong_try_module_get(struct module * mod)151 static inline int strong_try_module_get(struct module *mod)
152 {
153 	BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED);
154 	if (mod && mod->state == MODULE_STATE_COMING)
155 		return -EBUSY;
156 	if (try_module_get(mod))
157 		return 0;
158 	else
159 		return -ENOENT;
160 }
161 
add_taint_module(struct module * mod,unsigned flag,enum lockdep_ok lockdep_ok)162 static inline void add_taint_module(struct module *mod, unsigned flag,
163 				    enum lockdep_ok lockdep_ok)
164 {
165 	add_taint(flag, lockdep_ok);
166 	set_bit(flag, &mod->taints);
167 }
168 
169 /*
170  * A thread that wants to hold a reference to a module only while it
171  * is running can call this to safely exit.
172  */
__module_put_and_kthread_exit(struct module * mod,long code)173 void __noreturn __module_put_and_kthread_exit(struct module *mod, long code)
174 {
175 	module_put(mod);
176 	kthread_exit(code);
177 }
178 EXPORT_SYMBOL(__module_put_and_kthread_exit);
179 
180 /* Find a module section: 0 means not found. */
find_sec(const struct load_info * info,const char * name)181 static unsigned int find_sec(const struct load_info *info, const char *name)
182 {
183 	unsigned int i;
184 
185 	for (i = 1; i < info->hdr->e_shnum; i++) {
186 		Elf_Shdr *shdr = &info->sechdrs[i];
187 		/* Alloc bit cleared means "ignore it." */
188 		if ((shdr->sh_flags & SHF_ALLOC)
189 		    && strcmp(info->secstrings + shdr->sh_name, name) == 0)
190 			return i;
191 	}
192 	return 0;
193 }
194 
195 /* Find a module section, or NULL. */
section_addr(const struct load_info * info,const char * name)196 static void *section_addr(const struct load_info *info, const char *name)
197 {
198 	/* Section 0 has sh_addr 0. */
199 	return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
200 }
201 
202 /* 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)203 static void *section_objs(const struct load_info *info,
204 			  const char *name,
205 			  size_t object_size,
206 			  unsigned int *num)
207 {
208 	unsigned int sec = find_sec(info, name);
209 
210 	/* Section 0 has sh_addr 0 and sh_size 0. */
211 	*num = info->sechdrs[sec].sh_size / object_size;
212 	return (void *)info->sechdrs[sec].sh_addr;
213 }
214 
215 /* Find a module section: 0 means not found. Ignores SHF_ALLOC flag. */
find_any_sec(const struct load_info * info,const char * name)216 static unsigned int find_any_sec(const struct load_info *info, const char *name)
217 {
218 	unsigned int i;
219 
220 	for (i = 1; i < info->hdr->e_shnum; i++) {
221 		Elf_Shdr *shdr = &info->sechdrs[i];
222 		if (strcmp(info->secstrings + shdr->sh_name, name) == 0)
223 			return i;
224 	}
225 	return 0;
226 }
227 
228 /*
229  * Find a module section, or NULL. Fill in number of "objects" in section.
230  * Ignores SHF_ALLOC flag.
231  */
any_section_objs(const struct load_info * info,const char * name,size_t object_size,unsigned int * num)232 static __maybe_unused void *any_section_objs(const struct load_info *info,
233 					     const char *name,
234 					     size_t object_size,
235 					     unsigned int *num)
236 {
237 	unsigned int sec = find_any_sec(info, name);
238 
239 	/* Section 0 has sh_addr 0 and sh_size 0. */
240 	*num = info->sechdrs[sec].sh_size / object_size;
241 	return (void *)info->sechdrs[sec].sh_addr;
242 }
243 
244 #ifndef CONFIG_MODVERSIONS
245 #define symversion(base, idx) NULL
246 #else
247 #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
248 #endif
249 
kernel_symbol_name(const struct kernel_symbol * sym)250 static const char *kernel_symbol_name(const struct kernel_symbol *sym)
251 {
252 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
253 	return offset_to_ptr(&sym->name_offset);
254 #else
255 	return sym->name;
256 #endif
257 }
258 
kernel_symbol_namespace(const struct kernel_symbol * sym)259 static const char *kernel_symbol_namespace(const struct kernel_symbol *sym)
260 {
261 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
262 	if (!sym->namespace_offset)
263 		return NULL;
264 	return offset_to_ptr(&sym->namespace_offset);
265 #else
266 	return sym->namespace;
267 #endif
268 }
269 
cmp_name(const void * name,const void * sym)270 int cmp_name(const void *name, const void *sym)
271 {
272 	return strcmp(name, kernel_symbol_name(sym));
273 }
274 
find_exported_symbol_in_section(const struct symsearch * syms,struct module * owner,struct find_symbol_arg * fsa)275 static bool find_exported_symbol_in_section(const struct symsearch *syms,
276 					    struct module *owner,
277 					    struct find_symbol_arg *fsa)
278 {
279 	struct kernel_symbol *sym;
280 
281 	if (!fsa->gplok && syms->license == GPL_ONLY)
282 		return false;
283 
284 	sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
285 			sizeof(struct kernel_symbol), cmp_name);
286 	if (!sym)
287 		return false;
288 
289 	fsa->owner = owner;
290 	fsa->crc = symversion(syms->crcs, sym - syms->start);
291 	fsa->sym = sym;
292 	fsa->license = syms->license;
293 
294 	return true;
295 }
296 
297 /*
298  * Find an exported symbol and return it, along with, (optional) crc and
299  * (optional) module which owns it.  Needs preempt disabled or module_mutex.
300  */
find_symbol(struct find_symbol_arg * fsa)301 bool find_symbol(struct find_symbol_arg *fsa)
302 {
303 	static const struct symsearch arr[] = {
304 		{ __start___ksymtab, __stop___ksymtab, __start___kcrctab,
305 		  NOT_GPL_ONLY },
306 		{ __start___ksymtab_gpl, __stop___ksymtab_gpl,
307 		  __start___kcrctab_gpl,
308 		  GPL_ONLY },
309 	};
310 	struct module *mod;
311 	unsigned int i;
312 
313 	module_assert_mutex_or_preempt();
314 
315 	for (i = 0; i < ARRAY_SIZE(arr); i++)
316 		if (find_exported_symbol_in_section(&arr[i], NULL, fsa))
317 			return true;
318 
319 	list_for_each_entry_rcu(mod, &modules, list,
320 				lockdep_is_held(&module_mutex)) {
321 		struct symsearch arr[] = {
322 			{ mod->syms, mod->syms + mod->num_syms, mod->crcs,
323 			  NOT_GPL_ONLY },
324 			{ mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
325 			  mod->gpl_crcs,
326 			  GPL_ONLY },
327 		};
328 
329 		if (mod->state == MODULE_STATE_UNFORMED)
330 			continue;
331 
332 		for (i = 0; i < ARRAY_SIZE(arr); i++)
333 			if (find_exported_symbol_in_section(&arr[i], mod, fsa))
334 				return true;
335 	}
336 
337 	pr_debug("Failed to find symbol %s\n", fsa->name);
338 	return false;
339 }
340 
341 /*
342  * Search for module by name: must hold module_mutex (or preempt disabled
343  * for read-only access).
344  */
find_module_all(const char * name,size_t len,bool even_unformed)345 struct module *find_module_all(const char *name, size_t len,
346 			       bool even_unformed)
347 {
348 	struct module *mod;
349 
350 	module_assert_mutex_or_preempt();
351 
352 	list_for_each_entry_rcu(mod, &modules, list,
353 				lockdep_is_held(&module_mutex)) {
354 		if (!even_unformed && mod->state == MODULE_STATE_UNFORMED)
355 			continue;
356 		if (strlen(mod->name) == len && !memcmp(mod->name, name, len))
357 			return mod;
358 	}
359 	return NULL;
360 }
361 
find_module(const char * name)362 struct module *find_module(const char *name)
363 {
364 	return find_module_all(name, strlen(name), false);
365 }
366 
367 #ifdef CONFIG_SMP
368 
mod_percpu(struct module * mod)369 static inline void __percpu *mod_percpu(struct module *mod)
370 {
371 	return mod->percpu;
372 }
373 
percpu_modalloc(struct module * mod,struct load_info * info)374 static int percpu_modalloc(struct module *mod, struct load_info *info)
375 {
376 	Elf_Shdr *pcpusec = &info->sechdrs[info->index.pcpu];
377 	unsigned long align = pcpusec->sh_addralign;
378 
379 	if (!pcpusec->sh_size)
380 		return 0;
381 
382 	if (align > PAGE_SIZE) {
383 		pr_warn("%s: per-cpu alignment %li > %li\n",
384 			mod->name, align, PAGE_SIZE);
385 		align = PAGE_SIZE;
386 	}
387 
388 	mod->percpu = __alloc_reserved_percpu(pcpusec->sh_size, align);
389 	if (!mod->percpu) {
390 		pr_warn("%s: Could not allocate %lu bytes percpu data\n",
391 			mod->name, (unsigned long)pcpusec->sh_size);
392 		return -ENOMEM;
393 	}
394 	mod->percpu_size = pcpusec->sh_size;
395 	return 0;
396 }
397 
percpu_modfree(struct module * mod)398 static void percpu_modfree(struct module *mod)
399 {
400 	free_percpu(mod->percpu);
401 }
402 
find_pcpusec(struct load_info * info)403 static unsigned int find_pcpusec(struct load_info *info)
404 {
405 	return find_sec(info, ".data..percpu");
406 }
407 
percpu_modcopy(struct module * mod,const void * from,unsigned long size)408 static void percpu_modcopy(struct module *mod,
409 			   const void *from, unsigned long size)
410 {
411 	int cpu;
412 
413 	for_each_possible_cpu(cpu)
414 		memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
415 }
416 
__is_module_percpu_address(unsigned long addr,unsigned long * can_addr)417 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
418 {
419 	struct module *mod;
420 	unsigned int cpu;
421 
422 	preempt_disable();
423 
424 	list_for_each_entry_rcu(mod, &modules, list) {
425 		if (mod->state == MODULE_STATE_UNFORMED)
426 			continue;
427 		if (!mod->percpu_size)
428 			continue;
429 		for_each_possible_cpu(cpu) {
430 			void *start = per_cpu_ptr(mod->percpu, cpu);
431 			void *va = (void *)addr;
432 
433 			if (va >= start && va < start + mod->percpu_size) {
434 				if (can_addr) {
435 					*can_addr = (unsigned long) (va - start);
436 					*can_addr += (unsigned long)
437 						per_cpu_ptr(mod->percpu,
438 							    get_boot_cpu_id());
439 				}
440 				preempt_enable();
441 				return true;
442 			}
443 		}
444 	}
445 
446 	preempt_enable();
447 	return false;
448 }
449 
450 /**
451  * is_module_percpu_address() - test whether address is from module static percpu
452  * @addr: address to test
453  *
454  * Test whether @addr belongs to module static percpu area.
455  *
456  * Return: %true if @addr is from module static percpu area
457  */
is_module_percpu_address(unsigned long addr)458 bool is_module_percpu_address(unsigned long addr)
459 {
460 	return __is_module_percpu_address(addr, NULL);
461 }
462 
463 #else /* ... !CONFIG_SMP */
464 
mod_percpu(struct module * mod)465 static inline void __percpu *mod_percpu(struct module *mod)
466 {
467 	return NULL;
468 }
percpu_modalloc(struct module * mod,struct load_info * info)469 static int percpu_modalloc(struct module *mod, struct load_info *info)
470 {
471 	/* UP modules shouldn't have this section: ENOMEM isn't quite right */
472 	if (info->sechdrs[info->index.pcpu].sh_size != 0)
473 		return -ENOMEM;
474 	return 0;
475 }
percpu_modfree(struct module * mod)476 static inline void percpu_modfree(struct module *mod)
477 {
478 }
find_pcpusec(struct load_info * info)479 static unsigned int find_pcpusec(struct load_info *info)
480 {
481 	return 0;
482 }
percpu_modcopy(struct module * mod,const void * from,unsigned long size)483 static inline void percpu_modcopy(struct module *mod,
484 				  const void *from, unsigned long size)
485 {
486 	/* pcpusec should be 0, and size of that section should be 0. */
487 	BUG_ON(size != 0);
488 }
is_module_percpu_address(unsigned long addr)489 bool is_module_percpu_address(unsigned long addr)
490 {
491 	return false;
492 }
493 
__is_module_percpu_address(unsigned long addr,unsigned long * can_addr)494 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
495 {
496 	return false;
497 }
498 
499 #endif /* CONFIG_SMP */
500 
501 #define MODINFO_ATTR(field)	\
502 static void setup_modinfo_##field(struct module *mod, const char *s)  \
503 {                                                                     \
504 	mod->field = kstrdup(s, GFP_KERNEL);                          \
505 }                                                                     \
506 static ssize_t show_modinfo_##field(struct module_attribute *mattr,   \
507 			struct module_kobject *mk, char *buffer)      \
508 {                                                                     \
509 	return scnprintf(buffer, PAGE_SIZE, "%s\n", mk->mod->field);  \
510 }                                                                     \
511 static int modinfo_##field##_exists(struct module *mod)               \
512 {                                                                     \
513 	return mod->field != NULL;                                    \
514 }                                                                     \
515 static void free_modinfo_##field(struct module *mod)                  \
516 {                                                                     \
517 	kfree(mod->field);                                            \
518 	mod->field = NULL;                                            \
519 }                                                                     \
520 static struct module_attribute modinfo_##field = {                    \
521 	.attr = { .name = __stringify(field), .mode = 0444 },         \
522 	.show = show_modinfo_##field,                                 \
523 	.setup = setup_modinfo_##field,                               \
524 	.test = modinfo_##field##_exists,                             \
525 	.free = free_modinfo_##field,                                 \
526 };
527 
528 MODINFO_ATTR(version);
529 MODINFO_ATTR(srcversion);
530 MODINFO_ATTR(scmversion);
531 
532 static struct {
533 	char name[MODULE_NAME_LEN + 1];
534 	char taints[MODULE_FLAGS_BUF_SIZE];
535 } last_unloaded_module;
536 
537 #ifdef CONFIG_MODULE_UNLOAD
538 
539 EXPORT_TRACEPOINT_SYMBOL(module_get);
540 
541 /* MODULE_REF_BASE is the base reference count by kmodule loader. */
542 #define MODULE_REF_BASE	1
543 
544 /* Init the unload section of the module. */
module_unload_init(struct module * mod)545 static int module_unload_init(struct module *mod)
546 {
547 	/*
548 	 * Initialize reference counter to MODULE_REF_BASE.
549 	 * refcnt == 0 means module is going.
550 	 */
551 	atomic_set(&mod->refcnt, MODULE_REF_BASE);
552 
553 	INIT_LIST_HEAD(&mod->source_list);
554 	INIT_LIST_HEAD(&mod->target_list);
555 
556 	/* Hold reference count during initialization. */
557 	atomic_inc(&mod->refcnt);
558 
559 	return 0;
560 }
561 
562 /* Does a already use b? */
already_uses(struct module * a,struct module * b)563 static int already_uses(struct module *a, struct module *b)
564 {
565 	struct module_use *use;
566 
567 	list_for_each_entry(use, &b->source_list, source_list) {
568 		if (use->source == a) {
569 			pr_debug("%s uses %s!\n", a->name, b->name);
570 			return 1;
571 		}
572 	}
573 	pr_debug("%s does not use %s!\n", a->name, b->name);
574 	return 0;
575 }
576 
577 /*
578  * Module a uses b
579  *  - we add 'a' as a "source", 'b' as a "target" of module use
580  *  - the module_use is added to the list of 'b' sources (so
581  *    'b' can walk the list to see who sourced them), and of 'a'
582  *    targets (so 'a' can see what modules it targets).
583  */
add_module_usage(struct module * a,struct module * b)584 static int add_module_usage(struct module *a, struct module *b)
585 {
586 	struct module_use *use;
587 
588 	pr_debug("Allocating new usage for %s.\n", a->name);
589 	use = kmalloc(sizeof(*use), GFP_ATOMIC);
590 	if (!use)
591 		return -ENOMEM;
592 
593 	use->source = a;
594 	use->target = b;
595 	list_add(&use->source_list, &b->source_list);
596 	list_add(&use->target_list, &a->target_list);
597 	return 0;
598 }
599 
600 /* Module a uses b: caller needs module_mutex() */
ref_module(struct module * a,struct module * b)601 static int ref_module(struct module *a, struct module *b)
602 {
603 	int err;
604 
605 	if (b == NULL || already_uses(a, b))
606 		return 0;
607 
608 	/* If module isn't available, we fail. */
609 	err = strong_try_module_get(b);
610 	if (err)
611 		return err;
612 
613 	err = add_module_usage(a, b);
614 	if (err) {
615 		module_put(b);
616 		return err;
617 	}
618 	return 0;
619 }
620 
621 /* Clear the unload stuff of the module. */
module_unload_free(struct module * mod)622 static void module_unload_free(struct module *mod)
623 {
624 	struct module_use *use, *tmp;
625 
626 	mutex_lock(&module_mutex);
627 	list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
628 		struct module *i = use->target;
629 		pr_debug("%s unusing %s\n", mod->name, i->name);
630 		module_put(i);
631 		list_del(&use->source_list);
632 		list_del(&use->target_list);
633 		kfree(use);
634 	}
635 	mutex_unlock(&module_mutex);
636 }
637 
638 #ifdef CONFIG_MODULE_FORCE_UNLOAD
try_force_unload(unsigned int flags)639 static inline int try_force_unload(unsigned int flags)
640 {
641 	int ret = (flags & O_TRUNC);
642 	if (ret)
643 		add_taint(TAINT_FORCED_RMMOD, LOCKDEP_NOW_UNRELIABLE);
644 	return ret;
645 }
646 #else
try_force_unload(unsigned int flags)647 static inline int try_force_unload(unsigned int flags)
648 {
649 	return 0;
650 }
651 #endif /* CONFIG_MODULE_FORCE_UNLOAD */
652 
653 /* Try to release refcount of module, 0 means success. */
try_release_module_ref(struct module * mod)654 static int try_release_module_ref(struct module *mod)
655 {
656 	int ret;
657 
658 	/* Try to decrement refcnt which we set at loading */
659 	ret = atomic_sub_return(MODULE_REF_BASE, &mod->refcnt);
660 	BUG_ON(ret < 0);
661 	if (ret)
662 		/* Someone can put this right now, recover with checking */
663 		ret = atomic_add_unless(&mod->refcnt, MODULE_REF_BASE, 0);
664 
665 	return ret;
666 }
667 
try_stop_module(struct module * mod,int flags,int * forced)668 static int try_stop_module(struct module *mod, int flags, int *forced)
669 {
670 	/* If it's not unused, quit unless we're forcing. */
671 	if (try_release_module_ref(mod) != 0) {
672 		*forced = try_force_unload(flags);
673 		if (!(*forced))
674 			return -EWOULDBLOCK;
675 	}
676 
677 	/* Mark it as dying. */
678 	mod->state = MODULE_STATE_GOING;
679 
680 	return 0;
681 }
682 
683 /**
684  * module_refcount() - return the refcount or -1 if unloading
685  * @mod:	the module we're checking
686  *
687  * Return:
688  *	-1 if the module is in the process of unloading
689  *	otherwise the number of references in the kernel to the module
690  */
module_refcount(struct module * mod)691 int module_refcount(struct module *mod)
692 {
693 	return atomic_read(&mod->refcnt) - MODULE_REF_BASE;
694 }
695 EXPORT_SYMBOL(module_refcount);
696 
697 /* This exists whether we can unload or not */
698 static void free_module(struct module *mod);
699 
SYSCALL_DEFINE2(delete_module,const char __user *,name_user,unsigned int,flags)700 SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
701 		unsigned int, flags)
702 {
703 	struct module *mod;
704 	char name[MODULE_NAME_LEN];
705 	char buf[MODULE_FLAGS_BUF_SIZE];
706 	int ret, forced = 0;
707 
708 	if (!capable(CAP_SYS_MODULE) || modules_disabled)
709 		return -EPERM;
710 
711 	if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
712 		return -EFAULT;
713 	name[MODULE_NAME_LEN-1] = '\0';
714 
715 	audit_log_kern_module(name);
716 
717 	if (mutex_lock_interruptible(&module_mutex) != 0)
718 		return -EINTR;
719 
720 	mod = find_module(name);
721 	if (!mod) {
722 		ret = -ENOENT;
723 		goto out;
724 	}
725 
726 	if (!list_empty(&mod->source_list)) {
727 		/* Other modules depend on us: get rid of them first. */
728 		ret = -EWOULDBLOCK;
729 		goto out;
730 	}
731 
732 	/* Doing init or already dying? */
733 	if (mod->state != MODULE_STATE_LIVE) {
734 		/* FIXME: if (force), slam module count damn the torpedoes */
735 		pr_debug("%s already dying\n", mod->name);
736 		ret = -EBUSY;
737 		goto out;
738 	}
739 
740 	/* If it has an init func, it must have an exit func to unload */
741 	if (mod->init && !mod->exit) {
742 		forced = try_force_unload(flags);
743 		if (!forced) {
744 			/* This module can't be removed */
745 			ret = -EBUSY;
746 			goto out;
747 		}
748 	}
749 
750 	ret = try_stop_module(mod, flags, &forced);
751 	if (ret != 0)
752 		goto out;
753 
754 	mutex_unlock(&module_mutex);
755 	/* Final destruction now no one is using it. */
756 	if (mod->exit != NULL)
757 		mod->exit();
758 	blocking_notifier_call_chain(&module_notify_list,
759 				     MODULE_STATE_GOING, mod);
760 	klp_module_going(mod);
761 	ftrace_release_mod(mod);
762 
763 	async_synchronize_full();
764 
765 	/* Store the name and taints of the last unloaded module for diagnostic purposes */
766 	strscpy(last_unloaded_module.name, mod->name, sizeof(last_unloaded_module.name));
767 	strscpy(last_unloaded_module.taints, module_flags(mod, buf, false), sizeof(last_unloaded_module.taints));
768 
769 	free_module(mod);
770 	/* someone could wait for the module in add_unformed_module() */
771 	wake_up_all(&module_wq);
772 	return 0;
773 out:
774 	mutex_unlock(&module_mutex);
775 	return ret;
776 }
777 
__symbol_put(const char * symbol)778 void __symbol_put(const char *symbol)
779 {
780 	struct find_symbol_arg fsa = {
781 		.name	= symbol,
782 		.gplok	= true,
783 	};
784 
785 	preempt_disable();
786 	BUG_ON(!find_symbol(&fsa));
787 	module_put(fsa.owner);
788 	preempt_enable();
789 }
790 EXPORT_SYMBOL(__symbol_put);
791 
792 /* Note this assumes addr is a function, which it currently always is. */
symbol_put_addr(void * addr)793 void symbol_put_addr(void *addr)
794 {
795 	struct module *modaddr;
796 	unsigned long a = (unsigned long)dereference_function_descriptor(addr);
797 
798 	if (core_kernel_text(a))
799 		return;
800 
801 	/*
802 	 * Even though we hold a reference on the module; we still need to
803 	 * disable preemption in order to safely traverse the data structure.
804 	 */
805 	preempt_disable();
806 	modaddr = __module_text_address(a);
807 	BUG_ON(!modaddr);
808 	module_put(modaddr);
809 	preempt_enable();
810 }
811 EXPORT_SYMBOL_GPL(symbol_put_addr);
812 
show_refcnt(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)813 static ssize_t show_refcnt(struct module_attribute *mattr,
814 			   struct module_kobject *mk, char *buffer)
815 {
816 	return sprintf(buffer, "%i\n", module_refcount(mk->mod));
817 }
818 
819 static struct module_attribute modinfo_refcnt =
820 	__ATTR(refcnt, 0444, show_refcnt, NULL);
821 
__module_get(struct module * module)822 void __module_get(struct module *module)
823 {
824 	if (module) {
825 		preempt_disable();
826 		atomic_inc(&module->refcnt);
827 		trace_module_get(module, _RET_IP_);
828 		preempt_enable();
829 	}
830 }
831 EXPORT_SYMBOL(__module_get);
832 
try_module_get(struct module * module)833 bool try_module_get(struct module *module)
834 {
835 	bool ret = true;
836 
837 	if (module) {
838 		preempt_disable();
839 		/* Note: here, we can fail to get a reference */
840 		if (likely(module_is_live(module) &&
841 			   atomic_inc_not_zero(&module->refcnt) != 0))
842 			trace_module_get(module, _RET_IP_);
843 		else
844 			ret = false;
845 
846 		preempt_enable();
847 	}
848 	return ret;
849 }
850 EXPORT_SYMBOL(try_module_get);
851 
module_put(struct module * module)852 void module_put(struct module *module)
853 {
854 	int ret;
855 
856 	if (module) {
857 		preempt_disable();
858 		ret = atomic_dec_if_positive(&module->refcnt);
859 		WARN_ON(ret < 0);	/* Failed to put refcount */
860 		trace_module_put(module, _RET_IP_);
861 		preempt_enable();
862 	}
863 }
864 EXPORT_SYMBOL(module_put);
865 
866 #else /* !CONFIG_MODULE_UNLOAD */
module_unload_free(struct module * mod)867 static inline void module_unload_free(struct module *mod)
868 {
869 }
870 
ref_module(struct module * a,struct module * b)871 static int ref_module(struct module *a, struct module *b)
872 {
873 	return strong_try_module_get(b);
874 }
875 
module_unload_init(struct module * mod)876 static inline int module_unload_init(struct module *mod)
877 {
878 	return 0;
879 }
880 #endif /* CONFIG_MODULE_UNLOAD */
881 
module_flags_taint(unsigned long taints,char * buf)882 size_t module_flags_taint(unsigned long taints, char *buf)
883 {
884 	size_t l = 0;
885 	int i;
886 
887 	for (i = 0; i < TAINT_FLAGS_COUNT; i++) {
888 		if (taint_flags[i].module && test_bit(i, &taints))
889 			buf[l++] = taint_flags[i].c_true;
890 	}
891 
892 	return l;
893 }
894 
show_initstate(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)895 static ssize_t show_initstate(struct module_attribute *mattr,
896 			      struct module_kobject *mk, char *buffer)
897 {
898 	const char *state = "unknown";
899 
900 	switch (mk->mod->state) {
901 	case MODULE_STATE_LIVE:
902 		state = "live";
903 		break;
904 	case MODULE_STATE_COMING:
905 		state = "coming";
906 		break;
907 	case MODULE_STATE_GOING:
908 		state = "going";
909 		break;
910 	default:
911 		BUG();
912 	}
913 	return sprintf(buffer, "%s\n", state);
914 }
915 
916 static struct module_attribute modinfo_initstate =
917 	__ATTR(initstate, 0444, show_initstate, NULL);
918 
store_uevent(struct module_attribute * mattr,struct module_kobject * mk,const char * buffer,size_t count)919 static ssize_t store_uevent(struct module_attribute *mattr,
920 			    struct module_kobject *mk,
921 			    const char *buffer, size_t count)
922 {
923 	int rc;
924 
925 	rc = kobject_synth_uevent(&mk->kobj, buffer, count);
926 	return rc ? rc : count;
927 }
928 
929 struct module_attribute module_uevent =
930 	__ATTR(uevent, 0200, NULL, store_uevent);
931 
show_coresize(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)932 static ssize_t show_coresize(struct module_attribute *mattr,
933 			     struct module_kobject *mk, char *buffer)
934 {
935 	return sprintf(buffer, "%u\n", mk->mod->core_layout.size);
936 }
937 
938 static struct module_attribute modinfo_coresize =
939 	__ATTR(coresize, 0444, show_coresize, NULL);
940 
941 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
show_datasize(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)942 static ssize_t show_datasize(struct module_attribute *mattr,
943 			     struct module_kobject *mk, char *buffer)
944 {
945 	return sprintf(buffer, "%u\n", mk->mod->data_layout.size);
946 }
947 
948 static struct module_attribute modinfo_datasize =
949 	__ATTR(datasize, 0444, show_datasize, NULL);
950 #endif
951 
show_initsize(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)952 static ssize_t show_initsize(struct module_attribute *mattr,
953 			     struct module_kobject *mk, char *buffer)
954 {
955 	return sprintf(buffer, "%u\n", mk->mod->init_layout.size);
956 }
957 
958 static struct module_attribute modinfo_initsize =
959 	__ATTR(initsize, 0444, show_initsize, NULL);
960 
show_taint(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)961 static ssize_t show_taint(struct module_attribute *mattr,
962 			  struct module_kobject *mk, char *buffer)
963 {
964 	size_t l;
965 
966 	l = module_flags_taint(mk->mod->taints, buffer);
967 	buffer[l++] = '\n';
968 	return l;
969 }
970 
971 static struct module_attribute modinfo_taint =
972 	__ATTR(taint, 0444, show_taint, NULL);
973 
974 struct module_attribute *modinfo_attrs[] = {
975 	&module_uevent,
976 	&modinfo_version,
977 	&modinfo_srcversion,
978 	&modinfo_scmversion,
979 	&modinfo_initstate,
980 	&modinfo_coresize,
981 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
982 	&modinfo_datasize,
983 #endif
984 	&modinfo_initsize,
985 	&modinfo_taint,
986 #ifdef CONFIG_MODULE_UNLOAD
987 	&modinfo_refcnt,
988 #endif
989 	NULL,
990 };
991 
992 size_t modinfo_attrs_count = ARRAY_SIZE(modinfo_attrs);
993 
994 static const char vermagic[] = VERMAGIC_STRING;
995 
try_to_force_load(struct module * mod,const char * reason)996 int try_to_force_load(struct module *mod, const char *reason)
997 {
998 #ifdef CONFIG_MODULE_FORCE_LOAD
999 	if (!test_taint(TAINT_FORCED_MODULE))
1000 		pr_warn("%s: %s: kernel tainted.\n", mod->name, reason);
1001 	add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE);
1002 	return 0;
1003 #else
1004 	return -ENOEXEC;
1005 #endif
1006 }
1007 
1008 static char *get_modinfo(const struct load_info *info, const char *tag);
1009 static char *get_next_modinfo(const struct load_info *info, const char *tag,
1010 			      char *prev);
1011 
verify_namespace_is_imported(const struct load_info * info,const struct kernel_symbol * sym,struct module * mod)1012 static int verify_namespace_is_imported(const struct load_info *info,
1013 					const struct kernel_symbol *sym,
1014 					struct module *mod)
1015 {
1016 	const char *namespace;
1017 	char *imported_namespace;
1018 
1019 	namespace = kernel_symbol_namespace(sym);
1020 	if (namespace && namespace[0]) {
1021 		imported_namespace = get_modinfo(info, "import_ns");
1022 		while (imported_namespace) {
1023 			if (strcmp(namespace, imported_namespace) == 0)
1024 				return 0;
1025 			imported_namespace = get_next_modinfo(
1026 				info, "import_ns", imported_namespace);
1027 		}
1028 #ifdef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1029 		pr_warn(
1030 #else
1031 		pr_err(
1032 #endif
1033 			"%s: module uses symbol (%s) from namespace %s, but does not import it.\n",
1034 			mod->name, kernel_symbol_name(sym), namespace);
1035 #ifndef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1036 		return -EINVAL;
1037 #endif
1038 	}
1039 	return 0;
1040 }
1041 
inherit_taint(struct module * mod,struct module * owner,const char * name)1042 static bool inherit_taint(struct module *mod, struct module *owner, const char *name)
1043 {
1044 	if (!owner || !test_bit(TAINT_PROPRIETARY_MODULE, &owner->taints))
1045 		return true;
1046 
1047 	if (mod->using_gplonly_symbols) {
1048 		pr_err("%s: module using GPL-only symbols uses symbols %s from proprietary module %s.\n",
1049 			mod->name, name, owner->name);
1050 		return false;
1051 	}
1052 
1053 	if (!test_bit(TAINT_PROPRIETARY_MODULE, &mod->taints)) {
1054 		pr_warn("%s: module uses symbols %s from proprietary module %s, inheriting taint.\n",
1055 			mod->name, name, owner->name);
1056 		set_bit(TAINT_PROPRIETARY_MODULE, &mod->taints);
1057 	}
1058 	return true;
1059 }
1060 
1061 /* 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[])1062 static const struct kernel_symbol *resolve_symbol(struct module *mod,
1063 						  const struct load_info *info,
1064 						  const char *name,
1065 						  char ownername[])
1066 {
1067 	struct find_symbol_arg fsa = {
1068 		.name	= name,
1069 		.gplok	= !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)),
1070 		.warn	= true,
1071 	};
1072 	int err;
1073 
1074 	/*
1075 	 * The module_mutex should not be a heavily contended lock;
1076 	 * if we get the occasional sleep here, we'll go an extra iteration
1077 	 * in the wait_event_interruptible(), which is harmless.
1078 	 */
1079 	sched_annotate_sleep();
1080 	mutex_lock(&module_mutex);
1081 	if (!find_symbol(&fsa))
1082 		goto unlock;
1083 
1084 	if (fsa.license == GPL_ONLY)
1085 		mod->using_gplonly_symbols = true;
1086 
1087 	if (!inherit_taint(mod, fsa.owner, name)) {
1088 		fsa.sym = NULL;
1089 		goto getname;
1090 	}
1091 
1092 	if (!check_version(info, name, mod, fsa.crc)) {
1093 		fsa.sym = ERR_PTR(-EINVAL);
1094 		goto getname;
1095 	}
1096 
1097 	err = verify_namespace_is_imported(info, fsa.sym, mod);
1098 	if (err) {
1099 		fsa.sym = ERR_PTR(err);
1100 		goto getname;
1101 	}
1102 
1103 	/*
1104 	 * ANDROID: GKI:
1105 	 * In case of an unsigned module symbol resolves only if:
1106 	 * 1. Symbol is in the list of unprotected symbol list OR
1107 	 * 2. If symbol owner is not NULL i.e. owner is another module;
1108 	 *    it has to be an unsigned module and not signed GKI module
1109 	 *    to protect symbols exported by signed GKI modules.
1110 	 */
1111 	if (!mod->sig_ok &&
1112 	    !gki_is_module_unprotected_symbol(name) &&
1113 	    fsa.owner && fsa.owner->sig_ok) {
1114 		fsa.sym = ERR_PTR(-EACCES);
1115 		goto getname;
1116 	}
1117 
1118 	err = ref_module(mod, fsa.owner);
1119 	if (err) {
1120 		fsa.sym = ERR_PTR(err);
1121 		goto getname;
1122 	}
1123 
1124 getname:
1125 	/* We must make copy under the lock if we failed to get ref. */
1126 	strncpy(ownername, module_name(fsa.owner), MODULE_NAME_LEN);
1127 unlock:
1128 	mutex_unlock(&module_mutex);
1129 	return fsa.sym;
1130 }
1131 
1132 static const struct kernel_symbol *
resolve_symbol_wait(struct module * mod,const struct load_info * info,const char * name)1133 resolve_symbol_wait(struct module *mod,
1134 		    const struct load_info *info,
1135 		    const char *name)
1136 {
1137 	const struct kernel_symbol *ksym;
1138 	char owner[MODULE_NAME_LEN];
1139 
1140 	if (wait_event_interruptible_timeout(module_wq,
1141 			!IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1142 			|| PTR_ERR(ksym) != -EBUSY,
1143 					     30 * HZ) <= 0) {
1144 		pr_warn("%s: gave up waiting for init of module %s.\n",
1145 			mod->name, owner);
1146 	}
1147 	return ksym;
1148 }
1149 
module_memfree(void * module_region)1150 void __weak module_memfree(void *module_region)
1151 {
1152 	/*
1153 	 * This memory may be RO, and freeing RO memory in an interrupt is not
1154 	 * supported by vmalloc.
1155 	 */
1156 	WARN_ON(in_interrupt());
1157 	vfree(module_region);
1158 }
1159 
module_arch_cleanup(struct module * mod)1160 void __weak module_arch_cleanup(struct module *mod)
1161 {
1162 }
1163 
module_arch_freeing_init(struct module * mod)1164 void __weak module_arch_freeing_init(struct module *mod)
1165 {
1166 }
1167 
1168 /* Free a module, remove from lists, etc. */
free_module(struct module * mod)1169 static void free_module(struct module *mod)
1170 {
1171 	trace_module_free(mod);
1172 
1173 	mod_sysfs_teardown(mod);
1174 
1175 	/*
1176 	 * We leave it in list to prevent duplicate loads, but make sure
1177 	 * that noone uses it while it's being deconstructed.
1178 	 */
1179 	mutex_lock(&module_mutex);
1180 	mod->state = MODULE_STATE_UNFORMED;
1181 	mutex_unlock(&module_mutex);
1182 
1183 	/* Remove dynamic debug info */
1184 	ddebug_remove_module(mod->name);
1185 
1186 	/* Arch-specific cleanup. */
1187 	module_arch_cleanup(mod);
1188 
1189 	/* Module unload stuff */
1190 	module_unload_free(mod);
1191 
1192 	/* Free any allocated parameters. */
1193 	destroy_params(mod->kp, mod->num_kp);
1194 
1195 	if (is_livepatch_module(mod))
1196 		free_module_elf(mod);
1197 
1198 	/* Now we can delete it from the lists */
1199 	mutex_lock(&module_mutex);
1200 	/* Unlink carefully: kallsyms could be walking list. */
1201 	list_del_rcu(&mod->list);
1202 	mod_tree_remove(mod);
1203 	/* Remove this module from bug list, this uses list_del_rcu */
1204 	module_bug_cleanup(mod);
1205 	/* Wait for RCU-sched synchronizing before releasing mod->list and buglist. */
1206 	synchronize_rcu();
1207 	if (try_add_tainted_module(mod))
1208 		pr_err("%s: adding tainted module to the unloaded tainted modules list failed.\n",
1209 		       mod->name);
1210 	mutex_unlock(&module_mutex);
1211 
1212 	/* This may be empty, but that's OK */
1213 	module_arch_freeing_init(mod);
1214 	trace_android_rvh_set_module_init_rw_nx(mod);
1215 	module_memfree(mod->init_layout.base);
1216 	kfree(mod->args);
1217 	percpu_modfree(mod);
1218 
1219 	/* Free lock-classes; relies on the preceding sync_rcu(). */
1220 	lockdep_free_key_range(mod->data_layout.base, mod->data_layout.size);
1221 
1222 	/* Finally, free the core (containing the module structure) */
1223 	trace_android_rvh_set_module_core_rw_nx(mod);
1224 	module_memfree(mod->core_layout.base);
1225 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
1226 	vfree(mod->data_layout.base);
1227 #endif
1228 }
1229 
__symbol_get(const char * symbol)1230 void *__symbol_get(const char *symbol)
1231 {
1232 	struct find_symbol_arg fsa = {
1233 		.name	= symbol,
1234 		.gplok	= true,
1235 		.warn	= true,
1236 	};
1237 
1238 	preempt_disable();
1239 	if (!find_symbol(&fsa))
1240 		goto fail;
1241 	if (fsa.license != GPL_ONLY) {
1242 		pr_warn("failing symbol_get of non-GPLONLY symbol %s.\n",
1243 			symbol);
1244 		goto fail;
1245 	}
1246 	if (strong_try_module_get(fsa.owner))
1247 		goto fail;
1248 	preempt_enable();
1249 	return (void *)kernel_symbol_value(fsa.sym);
1250 fail:
1251 	preempt_enable();
1252 	return NULL;
1253 }
1254 EXPORT_SYMBOL_GPL(__symbol_get);
1255 
1256 /*
1257  * Ensure that an exported symbol [global namespace] does not already exist
1258  * in the kernel or in some other module's exported symbol table.
1259  *
1260  * You must hold the module_mutex.
1261  */
verify_exported_symbols(struct module * mod)1262 static int verify_exported_symbols(struct module *mod)
1263 {
1264 	unsigned int i;
1265 	const struct kernel_symbol *s;
1266 	struct {
1267 		const struct kernel_symbol *sym;
1268 		unsigned int num;
1269 	} arr[] = {
1270 		{ mod->syms, mod->num_syms },
1271 		{ mod->gpl_syms, mod->num_gpl_syms },
1272 	};
1273 
1274 	for (i = 0; i < ARRAY_SIZE(arr); i++) {
1275 		for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
1276 			struct find_symbol_arg fsa = {
1277 				.name	= kernel_symbol_name(s),
1278 				.gplok	= true,
1279 			};
1280 
1281 			if (!mod->sig_ok && gki_is_module_protected_export(
1282 						kernel_symbol_name(s))) {
1283 				pr_err("%s: exports protected symbol %s\n",
1284 				       mod->name, kernel_symbol_name(s));
1285 				return -EACCES;
1286 			}
1287 
1288 			if (find_symbol(&fsa)) {
1289 				pr_err("%s: exports duplicate symbol %s"
1290 				       " (owned by %s)\n",
1291 				       mod->name, kernel_symbol_name(s),
1292 				       module_name(fsa.owner));
1293 				return -ENOEXEC;
1294 			}
1295 		}
1296 	}
1297 	return 0;
1298 }
1299 
ignore_undef_symbol(Elf_Half emachine,const char * name)1300 static bool ignore_undef_symbol(Elf_Half emachine, const char *name)
1301 {
1302 	/*
1303 	 * On x86, PIC code and Clang non-PIC code may have call foo@PLT. GNU as
1304 	 * before 2.37 produces an unreferenced _GLOBAL_OFFSET_TABLE_ on x86-64.
1305 	 * i386 has a similar problem but may not deserve a fix.
1306 	 *
1307 	 * If we ever have to ignore many symbols, consider refactoring the code to
1308 	 * only warn if referenced by a relocation.
1309 	 */
1310 	if (emachine == EM_386 || emachine == EM_X86_64)
1311 		return !strcmp(name, "_GLOBAL_OFFSET_TABLE_");
1312 	return false;
1313 }
1314 
1315 /* Change all symbols so that st_value encodes the pointer directly. */
simplify_symbols(struct module * mod,const struct load_info * info)1316 static int simplify_symbols(struct module *mod, const struct load_info *info)
1317 {
1318 	Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
1319 	Elf_Sym *sym = (void *)symsec->sh_addr;
1320 	unsigned long secbase;
1321 	unsigned int i;
1322 	int ret = 0;
1323 	const struct kernel_symbol *ksym;
1324 
1325 	for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
1326 		const char *name = info->strtab + sym[i].st_name;
1327 
1328 		switch (sym[i].st_shndx) {
1329 		case SHN_COMMON:
1330 			/* Ignore common symbols */
1331 			if (!strncmp(name, "__gnu_lto", 9))
1332 				break;
1333 
1334 			/*
1335 			 * We compiled with -fno-common.  These are not
1336 			 * supposed to happen.
1337 			 */
1338 			pr_debug("Common symbol: %s\n", name);
1339 			pr_warn("%s: please compile with -fno-common\n",
1340 			       mod->name);
1341 			ret = -ENOEXEC;
1342 			break;
1343 
1344 		case SHN_ABS:
1345 			/* Don't need to do anything */
1346 			pr_debug("Absolute symbol: 0x%08lx\n",
1347 			       (long)sym[i].st_value);
1348 			break;
1349 
1350 		case SHN_LIVEPATCH:
1351 			/* Livepatch symbols are resolved by livepatch */
1352 			break;
1353 
1354 		case SHN_UNDEF:
1355 			ksym = resolve_symbol_wait(mod, info, name);
1356 			/* Ok if resolved.  */
1357 			if (ksym && !IS_ERR(ksym)) {
1358 				sym[i].st_value = kernel_symbol_value(ksym);
1359 				break;
1360 			}
1361 
1362 			/* Ok if weak or ignored.  */
1363 			if (!ksym &&
1364 			    (ELF_ST_BIND(sym[i].st_info) == STB_WEAK ||
1365 			     ignore_undef_symbol(info->hdr->e_machine, name)))
1366 				break;
1367 
1368 			if (PTR_ERR(ksym) == -EACCES) {
1369 				ret = -EACCES;
1370 				pr_warn("%s: Protected symbol: %s (err %d)\n",
1371 					mod->name, name, ret);
1372 			} else {
1373 				ret = PTR_ERR(ksym) ?: -ENOENT;
1374 				pr_warn("%s: Unknown symbol %s (err %d)\n",
1375 					mod->name, name, ret);
1376 			}
1377 			break;
1378 
1379 		default:
1380 			/* Divert to percpu allocation if a percpu var. */
1381 			if (sym[i].st_shndx == info->index.pcpu)
1382 				secbase = (unsigned long)mod_percpu(mod);
1383 			else
1384 				secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
1385 			sym[i].st_value += secbase;
1386 			break;
1387 		}
1388 	}
1389 
1390 	return ret;
1391 }
1392 
apply_relocations(struct module * mod,const struct load_info * info)1393 static int apply_relocations(struct module *mod, const struct load_info *info)
1394 {
1395 	unsigned int i;
1396 	int err = 0;
1397 
1398 	/* Now do relocations. */
1399 	for (i = 1; i < info->hdr->e_shnum; i++) {
1400 		unsigned int infosec = info->sechdrs[i].sh_info;
1401 
1402 		/* Not a valid relocation section? */
1403 		if (infosec >= info->hdr->e_shnum)
1404 			continue;
1405 
1406 		/* Don't bother with non-allocated sections */
1407 		if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
1408 			continue;
1409 
1410 		if (info->sechdrs[i].sh_flags & SHF_RELA_LIVEPATCH)
1411 			err = klp_apply_section_relocs(mod, info->sechdrs,
1412 						       info->secstrings,
1413 						       info->strtab,
1414 						       info->index.sym, i,
1415 						       NULL);
1416 		else if (info->sechdrs[i].sh_type == SHT_REL)
1417 			err = apply_relocate(info->sechdrs, info->strtab,
1418 					     info->index.sym, i, mod);
1419 		else if (info->sechdrs[i].sh_type == SHT_RELA)
1420 			err = apply_relocate_add(info->sechdrs, info->strtab,
1421 						 info->index.sym, i, mod);
1422 		if (err < 0)
1423 			break;
1424 	}
1425 	return err;
1426 }
1427 
1428 /* Additional bytes needed by arch in front of individual sections */
arch_mod_section_prepend(struct module * mod,unsigned int section)1429 unsigned int __weak arch_mod_section_prepend(struct module *mod,
1430 					     unsigned int section)
1431 {
1432 	/* default implementation just returns zero */
1433 	return 0;
1434 }
1435 
1436 /* Update size with this section: return offset. */
module_get_offset(struct module * mod,unsigned int * size,Elf_Shdr * sechdr,unsigned int section)1437 long module_get_offset(struct module *mod, unsigned int *size,
1438 		       Elf_Shdr *sechdr, unsigned int section)
1439 {
1440 	long ret;
1441 
1442 	*size += arch_mod_section_prepend(mod, section);
1443 	ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
1444 	*size = ret + sechdr->sh_size;
1445 	return ret;
1446 }
1447 
module_init_layout_section(const char * sname)1448 bool module_init_layout_section(const char *sname)
1449 {
1450 #ifndef CONFIG_MODULE_UNLOAD
1451 	if (module_exit_section(sname))
1452 		return true;
1453 #endif
1454 	return module_init_section(sname);
1455 }
1456 
1457 /*
1458  * Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
1459  * might -- code, read-only data, read-write data, small data.  Tally
1460  * sizes, and place the offsets into sh_entsize fields: high bit means it
1461  * belongs in init.
1462  */
layout_sections(struct module * mod,struct load_info * info)1463 static void layout_sections(struct module *mod, struct load_info *info)
1464 {
1465 	static unsigned long const masks[][2] = {
1466 		/*
1467 		 * NOTE: all executable code must be the first section
1468 		 * in this array; otherwise modify the text_size
1469 		 * finder in the two loops below
1470 		 */
1471 		{ SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
1472 		{ SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
1473 		{ SHF_RO_AFTER_INIT | SHF_ALLOC, ARCH_SHF_SMALL },
1474 		{ SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
1475 		{ ARCH_SHF_SMALL | SHF_ALLOC, 0 }
1476 	};
1477 	unsigned int m, i;
1478 
1479 	for (i = 0; i < info->hdr->e_shnum; i++)
1480 		info->sechdrs[i].sh_entsize = ~0UL;
1481 
1482 	pr_debug("Core section allocation order:\n");
1483 	for (m = 0; m < ARRAY_SIZE(masks); ++m) {
1484 		for (i = 0; i < info->hdr->e_shnum; ++i) {
1485 			Elf_Shdr *s = &info->sechdrs[i];
1486 			const char *sname = info->secstrings + s->sh_name;
1487 			unsigned int *sizep;
1488 
1489 			if ((s->sh_flags & masks[m][0]) != masks[m][0]
1490 			    || (s->sh_flags & masks[m][1])
1491 			    || s->sh_entsize != ~0UL
1492 			    || module_init_layout_section(sname))
1493 				continue;
1494 			sizep = m ? &mod->data_layout.size : &mod->core_layout.size;
1495 			s->sh_entsize = module_get_offset(mod, sizep, s, i);
1496 			pr_debug("\t%s\n", sname);
1497 		}
1498 		switch (m) {
1499 		case 0: /* executable */
1500 			mod->core_layout.size = strict_align(mod->core_layout.size);
1501 			mod->core_layout.text_size = mod->core_layout.size;
1502 			break;
1503 		case 1: /* RO: text and ro-data */
1504 			mod->data_layout.size = strict_align(mod->data_layout.size);
1505 			mod->data_layout.ro_size = mod->data_layout.size;
1506 			break;
1507 		case 2: /* RO after init */
1508 			mod->data_layout.size = strict_align(mod->data_layout.size);
1509 			mod->data_layout.ro_after_init_size = mod->data_layout.size;
1510 			break;
1511 		case 4: /* whole core */
1512 			mod->data_layout.size = strict_align(mod->data_layout.size);
1513 			break;
1514 		}
1515 	}
1516 
1517 	pr_debug("Init section allocation order:\n");
1518 	for (m = 0; m < ARRAY_SIZE(masks); ++m) {
1519 		for (i = 0; i < info->hdr->e_shnum; ++i) {
1520 			Elf_Shdr *s = &info->sechdrs[i];
1521 			const char *sname = info->secstrings + s->sh_name;
1522 
1523 			if ((s->sh_flags & masks[m][0]) != masks[m][0]
1524 			    || (s->sh_flags & masks[m][1])
1525 			    || s->sh_entsize != ~0UL
1526 			    || !module_init_layout_section(sname))
1527 				continue;
1528 			s->sh_entsize = (module_get_offset(mod, &mod->init_layout.size, s, i)
1529 					 | INIT_OFFSET_MASK);
1530 			pr_debug("\t%s\n", sname);
1531 		}
1532 		switch (m) {
1533 		case 0: /* executable */
1534 			mod->init_layout.size = strict_align(mod->init_layout.size);
1535 			mod->init_layout.text_size = mod->init_layout.size;
1536 			break;
1537 		case 1: /* RO: text and ro-data */
1538 			mod->init_layout.size = strict_align(mod->init_layout.size);
1539 			mod->init_layout.ro_size = mod->init_layout.size;
1540 			break;
1541 		case 2:
1542 			/*
1543 			 * RO after init doesn't apply to init_layout (only
1544 			 * core_layout), so it just takes the value of ro_size.
1545 			 */
1546 			mod->init_layout.ro_after_init_size = mod->init_layout.ro_size;
1547 			break;
1548 		case 4: /* whole init */
1549 			mod->init_layout.size = strict_align(mod->init_layout.size);
1550 			break;
1551 		}
1552 	}
1553 }
1554 
set_license(struct module * mod,const char * license)1555 static void set_license(struct module *mod, const char *license)
1556 {
1557 	if (!license)
1558 		license = "unspecified";
1559 
1560 	if (!license_is_gpl_compatible(license)) {
1561 		if (!test_taint(TAINT_PROPRIETARY_MODULE))
1562 			pr_warn("%s: module license '%s' taints kernel.\n",
1563 				mod->name, license);
1564 		add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
1565 				 LOCKDEP_NOW_UNRELIABLE);
1566 	}
1567 }
1568 
1569 /* Parse tag=value strings from .modinfo section */
next_string(char * string,unsigned long * secsize)1570 static char *next_string(char *string, unsigned long *secsize)
1571 {
1572 	/* Skip non-zero chars */
1573 	while (string[0]) {
1574 		string++;
1575 		if ((*secsize)-- <= 1)
1576 			return NULL;
1577 	}
1578 
1579 	/* Skip any zero padding. */
1580 	while (!string[0]) {
1581 		string++;
1582 		if ((*secsize)-- <= 1)
1583 			return NULL;
1584 	}
1585 	return string;
1586 }
1587 
get_next_modinfo(const struct load_info * info,const char * tag,char * prev)1588 static char *get_next_modinfo(const struct load_info *info, const char *tag,
1589 			      char *prev)
1590 {
1591 	char *p;
1592 	unsigned int taglen = strlen(tag);
1593 	Elf_Shdr *infosec = &info->sechdrs[info->index.info];
1594 	unsigned long size = infosec->sh_size;
1595 
1596 	/*
1597 	 * get_modinfo() calls made before rewrite_section_headers()
1598 	 * must use sh_offset, as sh_addr isn't set!
1599 	 */
1600 	char *modinfo = (char *)info->hdr + infosec->sh_offset;
1601 
1602 	if (prev) {
1603 		size -= prev - modinfo;
1604 		modinfo = next_string(prev, &size);
1605 	}
1606 
1607 	for (p = modinfo; p; p = next_string(p, &size)) {
1608 		if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
1609 			return p + taglen + 1;
1610 	}
1611 	return NULL;
1612 }
1613 
get_modinfo(const struct load_info * info,const char * tag)1614 static char *get_modinfo(const struct load_info *info, const char *tag)
1615 {
1616 	return get_next_modinfo(info, tag, NULL);
1617 }
1618 
setup_modinfo(struct module * mod,struct load_info * info)1619 static void setup_modinfo(struct module *mod, struct load_info *info)
1620 {
1621 	struct module_attribute *attr;
1622 	int i;
1623 
1624 	for (i = 0; (attr = modinfo_attrs[i]); i++) {
1625 		if (attr->setup)
1626 			attr->setup(mod, get_modinfo(info, attr->attr.name));
1627 	}
1628 }
1629 
free_modinfo(struct module * mod)1630 static void free_modinfo(struct module *mod)
1631 {
1632 	struct module_attribute *attr;
1633 	int i;
1634 
1635 	for (i = 0; (attr = modinfo_attrs[i]); i++) {
1636 		if (attr->free)
1637 			attr->free(mod);
1638 	}
1639 }
1640 
dynamic_debug_setup(struct module * mod,struct _ddebug_info * dyndbg)1641 static void dynamic_debug_setup(struct module *mod, struct _ddebug_info *dyndbg)
1642 {
1643 	if (!dyndbg->num_descs)
1644 		return;
1645 	ddebug_add_module(dyndbg, mod->name);
1646 }
1647 
dynamic_debug_remove(struct module * mod,struct _ddebug_info * dyndbg)1648 static void dynamic_debug_remove(struct module *mod, struct _ddebug_info *dyndbg)
1649 {
1650 	if (dyndbg->num_descs)
1651 		ddebug_remove_module(mod->name);
1652 }
1653 
module_alloc(unsigned long size)1654 void * __weak module_alloc(unsigned long size)
1655 {
1656 	return __vmalloc_node_range(size, 1, VMALLOC_START, VMALLOC_END,
1657 			GFP_KERNEL, PAGE_KERNEL_EXEC, VM_FLUSH_RESET_PERMS,
1658 			NUMA_NO_NODE, __builtin_return_address(0));
1659 }
1660 
module_init_section(const char * name)1661 bool __weak module_init_section(const char *name)
1662 {
1663 	return strstarts(name, ".init");
1664 }
1665 
module_exit_section(const char * name)1666 bool __weak module_exit_section(const char *name)
1667 {
1668 	return strstarts(name, ".exit");
1669 }
1670 
validate_section_offset(struct load_info * info,Elf_Shdr * shdr)1671 static int validate_section_offset(struct load_info *info, Elf_Shdr *shdr)
1672 {
1673 #if defined(CONFIG_64BIT)
1674 	unsigned long long secend;
1675 #else
1676 	unsigned long secend;
1677 #endif
1678 
1679 	/*
1680 	 * Check for both overflow and offset/size being
1681 	 * too large.
1682 	 */
1683 	secend = shdr->sh_offset + shdr->sh_size;
1684 	if (secend < shdr->sh_offset || secend > info->len)
1685 		return -ENOEXEC;
1686 
1687 	return 0;
1688 }
1689 
1690 /*
1691  * Sanity checks against invalid binaries, wrong arch, weird elf version.
1692  *
1693  * Also do basic validity checks against section offsets and sizes, the
1694  * section name string table, and the indices used for it (sh_name).
1695  */
elf_validity_check(struct load_info * info)1696 static int elf_validity_check(struct load_info *info)
1697 {
1698 	unsigned int i;
1699 	Elf_Shdr *shdr, *strhdr;
1700 	int err;
1701 
1702 	if (info->len < sizeof(*(info->hdr))) {
1703 		pr_err("Invalid ELF header len %lu\n", info->len);
1704 		goto no_exec;
1705 	}
1706 
1707 	if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0) {
1708 		pr_err("Invalid ELF header magic: != %s\n", ELFMAG);
1709 		goto no_exec;
1710 	}
1711 	if (info->hdr->e_type != ET_REL) {
1712 		pr_err("Invalid ELF header type: %u != %u\n",
1713 		       info->hdr->e_type, ET_REL);
1714 		goto no_exec;
1715 	}
1716 	if (!elf_check_arch(info->hdr)) {
1717 		pr_err("Invalid architecture in ELF header: %u\n",
1718 		       info->hdr->e_machine);
1719 		goto no_exec;
1720 	}
1721 	if (info->hdr->e_shentsize != sizeof(Elf_Shdr)) {
1722 		pr_err("Invalid ELF section header size\n");
1723 		goto no_exec;
1724 	}
1725 
1726 	/*
1727 	 * e_shnum is 16 bits, and sizeof(Elf_Shdr) is
1728 	 * known and small. So e_shnum * sizeof(Elf_Shdr)
1729 	 * will not overflow unsigned long on any platform.
1730 	 */
1731 	if (info->hdr->e_shoff >= info->len
1732 	    || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
1733 		info->len - info->hdr->e_shoff)) {
1734 		pr_err("Invalid ELF section header overflow\n");
1735 		goto no_exec;
1736 	}
1737 
1738 	info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
1739 
1740 	/*
1741 	 * Verify if the section name table index is valid.
1742 	 */
1743 	if (info->hdr->e_shstrndx == SHN_UNDEF
1744 	    || info->hdr->e_shstrndx >= info->hdr->e_shnum) {
1745 		pr_err("Invalid ELF section name index: %d || e_shstrndx (%d) >= e_shnum (%d)\n",
1746 		       info->hdr->e_shstrndx, info->hdr->e_shstrndx,
1747 		       info->hdr->e_shnum);
1748 		goto no_exec;
1749 	}
1750 
1751 	strhdr = &info->sechdrs[info->hdr->e_shstrndx];
1752 	err = validate_section_offset(info, strhdr);
1753 	if (err < 0) {
1754 		pr_err("Invalid ELF section hdr(type %u)\n", strhdr->sh_type);
1755 		return err;
1756 	}
1757 
1758 	/*
1759 	 * The section name table must be NUL-terminated, as required
1760 	 * by the spec. This makes strcmp and pr_* calls that access
1761 	 * strings in the section safe.
1762 	 */
1763 	info->secstrings = (void *)info->hdr + strhdr->sh_offset;
1764 	if (strhdr->sh_size == 0) {
1765 		pr_err("empty section name table\n");
1766 		goto no_exec;
1767 	}
1768 	if (info->secstrings[strhdr->sh_size - 1] != '\0') {
1769 		pr_err("ELF Spec violation: section name table isn't null terminated\n");
1770 		goto no_exec;
1771 	}
1772 
1773 	/*
1774 	 * The code assumes that section 0 has a length of zero and
1775 	 * an addr of zero, so check for it.
1776 	 */
1777 	if (info->sechdrs[0].sh_type != SHT_NULL
1778 	    || info->sechdrs[0].sh_size != 0
1779 	    || info->sechdrs[0].sh_addr != 0) {
1780 		pr_err("ELF Spec violation: section 0 type(%d)!=SH_NULL or non-zero len or addr\n",
1781 		       info->sechdrs[0].sh_type);
1782 		goto no_exec;
1783 	}
1784 
1785 	for (i = 1; i < info->hdr->e_shnum; i++) {
1786 		shdr = &info->sechdrs[i];
1787 		switch (shdr->sh_type) {
1788 		case SHT_NULL:
1789 		case SHT_NOBITS:
1790 			continue;
1791 		case SHT_SYMTAB:
1792 			if (shdr->sh_link == SHN_UNDEF
1793 			    || shdr->sh_link >= info->hdr->e_shnum) {
1794 				pr_err("Invalid ELF sh_link!=SHN_UNDEF(%d) or (sh_link(%d) >= hdr->e_shnum(%d)\n",
1795 				       shdr->sh_link, shdr->sh_link,
1796 				       info->hdr->e_shnum);
1797 				goto no_exec;
1798 			}
1799 			fallthrough;
1800 		default:
1801 			err = validate_section_offset(info, shdr);
1802 			if (err < 0) {
1803 				pr_err("Invalid ELF section in module (section %u type %u)\n",
1804 					i, shdr->sh_type);
1805 				return err;
1806 			}
1807 
1808 			if (shdr->sh_flags & SHF_ALLOC) {
1809 				if (shdr->sh_name >= strhdr->sh_size) {
1810 					pr_err("Invalid ELF section name in module (section %u type %u)\n",
1811 					       i, shdr->sh_type);
1812 					return -ENOEXEC;
1813 				}
1814 			}
1815 			break;
1816 		}
1817 	}
1818 
1819 	return 0;
1820 
1821 no_exec:
1822 	return -ENOEXEC;
1823 }
1824 
1825 #define COPY_CHUNK_SIZE (16*PAGE_SIZE)
1826 
copy_chunked_from_user(void * dst,const void __user * usrc,unsigned long len)1827 static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len)
1828 {
1829 	do {
1830 		unsigned long n = min(len, COPY_CHUNK_SIZE);
1831 
1832 		if (copy_from_user(dst, usrc, n) != 0)
1833 			return -EFAULT;
1834 		cond_resched();
1835 		dst += n;
1836 		usrc += n;
1837 		len -= n;
1838 	} while (len);
1839 	return 0;
1840 }
1841 
check_modinfo_livepatch(struct module * mod,struct load_info * info)1842 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
1843 {
1844 	if (!get_modinfo(info, "livepatch"))
1845 		/* Nothing more to do */
1846 		return 0;
1847 
1848 	if (set_livepatch_module(mod)) {
1849 		add_taint_module(mod, TAINT_LIVEPATCH, LOCKDEP_STILL_OK);
1850 		pr_notice_once("%s: tainting kernel with TAINT_LIVEPATCH\n",
1851 				mod->name);
1852 		return 0;
1853 	}
1854 
1855 	pr_err("%s: module is marked as livepatch module, but livepatch support is disabled",
1856 	       mod->name);
1857 	return -ENOEXEC;
1858 }
1859 
check_modinfo_retpoline(struct module * mod,struct load_info * info)1860 static void check_modinfo_retpoline(struct module *mod, struct load_info *info)
1861 {
1862 	if (retpoline_module_ok(get_modinfo(info, "retpoline")))
1863 		return;
1864 
1865 	pr_warn("%s: loading module not compiled with retpoline compiler.\n",
1866 		mod->name);
1867 }
1868 
1869 /* Sets info->hdr and info->len. */
copy_module_from_user(const void __user * umod,unsigned long len,struct load_info * info)1870 static int copy_module_from_user(const void __user *umod, unsigned long len,
1871 				  struct load_info *info)
1872 {
1873 	int err;
1874 
1875 	info->len = len;
1876 	if (info->len < sizeof(*(info->hdr)))
1877 		return -ENOEXEC;
1878 
1879 	err = security_kernel_load_data(LOADING_MODULE, true);
1880 	if (err)
1881 		return err;
1882 
1883 	/* Suck in entire file: we'll want most of it. */
1884 	info->hdr = __vmalloc(info->len, GFP_KERNEL | __GFP_NOWARN);
1885 	if (!info->hdr)
1886 		return -ENOMEM;
1887 
1888 	if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) {
1889 		err = -EFAULT;
1890 		goto out;
1891 	}
1892 
1893 	err = security_kernel_post_load_data((char *)info->hdr, info->len,
1894 					     LOADING_MODULE, "init_module");
1895 out:
1896 	if (err)
1897 		vfree(info->hdr);
1898 
1899 	return err;
1900 }
1901 
free_copy(struct load_info * info,int flags)1902 static void free_copy(struct load_info *info, int flags)
1903 {
1904 	if (flags & MODULE_INIT_COMPRESSED_FILE)
1905 		module_decompress_cleanup(info);
1906 	else
1907 		vfree(info->hdr);
1908 }
1909 
rewrite_section_headers(struct load_info * info,int flags)1910 static int rewrite_section_headers(struct load_info *info, int flags)
1911 {
1912 	unsigned int i;
1913 
1914 	/* This should always be true, but let's be sure. */
1915 	info->sechdrs[0].sh_addr = 0;
1916 
1917 	for (i = 1; i < info->hdr->e_shnum; i++) {
1918 		Elf_Shdr *shdr = &info->sechdrs[i];
1919 
1920 		/*
1921 		 * Mark all sections sh_addr with their address in the
1922 		 * temporary image.
1923 		 */
1924 		shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
1925 
1926 	}
1927 
1928 	/* Track but don't keep modinfo and version sections. */
1929 	info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
1930 	info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
1931 
1932 	return 0;
1933 }
1934 
1935 /*
1936  * Set up our basic convenience variables (pointers to section headers,
1937  * search for module section index etc), and do some basic section
1938  * verification.
1939  *
1940  * Set info->mod to the temporary copy of the module in info->hdr. The final one
1941  * will be allocated in move_module().
1942  */
setup_load_info(struct load_info * info,int flags)1943 static int setup_load_info(struct load_info *info, int flags)
1944 {
1945 	unsigned int i;
1946 
1947 	/* Try to find a name early so we can log errors with a module name */
1948 	info->index.info = find_sec(info, ".modinfo");
1949 	if (info->index.info)
1950 		info->name = get_modinfo(info, "name");
1951 
1952 	/* Find internal symbols and strings. */
1953 	for (i = 1; i < info->hdr->e_shnum; i++) {
1954 		if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
1955 			info->index.sym = i;
1956 			info->index.str = info->sechdrs[i].sh_link;
1957 			info->strtab = (char *)info->hdr
1958 				+ info->sechdrs[info->index.str].sh_offset;
1959 			break;
1960 		}
1961 	}
1962 
1963 	if (info->index.sym == 0) {
1964 		pr_warn("%s: module has no symbols (stripped?)\n",
1965 			info->name ?: "(missing .modinfo section or name field)");
1966 		return -ENOEXEC;
1967 	}
1968 
1969 	info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
1970 	if (!info->index.mod) {
1971 		pr_warn("%s: No module found in object\n",
1972 			info->name ?: "(missing .modinfo section or name field)");
1973 		return -ENOEXEC;
1974 	}
1975 	/* This is temporary: point mod into copy of data. */
1976 	info->mod = (void *)info->hdr + info->sechdrs[info->index.mod].sh_offset;
1977 
1978 	/*
1979 	 * If we didn't load the .modinfo 'name' field earlier, fall back to
1980 	 * on-disk struct mod 'name' field.
1981 	 */
1982 	if (!info->name)
1983 		info->name = info->mod->name;
1984 
1985 	if (flags & MODULE_INIT_IGNORE_MODVERSIONS)
1986 		info->index.vers = 0; /* Pretend no __versions section! */
1987 	else
1988 		info->index.vers = find_sec(info, "__versions");
1989 
1990 	info->index.pcpu = find_pcpusec(info);
1991 
1992 	return 0;
1993 }
1994 
check_modinfo(struct module * mod,struct load_info * info,int flags)1995 static int check_modinfo(struct module *mod, struct load_info *info, int flags)
1996 {
1997 	const char *modmagic = get_modinfo(info, "vermagic");
1998 	int err;
1999 
2000 	if (flags & MODULE_INIT_IGNORE_VERMAGIC)
2001 		modmagic = NULL;
2002 
2003 	/* This is allowed: modprobe --force will invalidate it. */
2004 	if (!modmagic) {
2005 		err = try_to_force_load(mod, "bad vermagic");
2006 		if (err)
2007 			return err;
2008 	} else if (!same_magic(modmagic, vermagic, info->index.vers)) {
2009 		pr_err("%s: version magic '%s' should be '%s'\n",
2010 		       info->name, modmagic, vermagic);
2011 		return -ENOEXEC;
2012 	}
2013 
2014 	if (!get_modinfo(info, "intree")) {
2015 		if (!test_taint(TAINT_OOT_MODULE))
2016 			pr_warn("%s: loading out-of-tree module taints kernel.\n",
2017 				mod->name);
2018 		add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
2019 	}
2020 
2021 	check_modinfo_retpoline(mod, info);
2022 
2023 	if (get_modinfo(info, "staging")) {
2024 		add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
2025 		pr_warn("%s: module is from the staging directory, the quality "
2026 			"is unknown, you have been warned.\n", mod->name);
2027 	}
2028 
2029 	err = check_modinfo_livepatch(mod, info);
2030 	if (err)
2031 		return err;
2032 
2033 	/* Set up license info based on the info section */
2034 	set_license(mod, get_modinfo(info, "license"));
2035 
2036 	if (get_modinfo(info, "test")) {
2037 		if (!test_taint(TAINT_TEST))
2038 			pr_warn("%s: loading test module taints kernel.\n",
2039 				mod->name);
2040 		add_taint_module(mod, TAINT_TEST, LOCKDEP_STILL_OK);
2041 	}
2042 
2043 	return 0;
2044 }
2045 
find_module_sections(struct module * mod,struct load_info * info)2046 static int find_module_sections(struct module *mod, struct load_info *info)
2047 {
2048 	mod->kp = section_objs(info, "__param",
2049 			       sizeof(*mod->kp), &mod->num_kp);
2050 	mod->syms = section_objs(info, "__ksymtab",
2051 				 sizeof(*mod->syms), &mod->num_syms);
2052 	mod->crcs = section_addr(info, "__kcrctab");
2053 	mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
2054 				     sizeof(*mod->gpl_syms),
2055 				     &mod->num_gpl_syms);
2056 	mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
2057 
2058 #ifdef CONFIG_CONSTRUCTORS
2059 	mod->ctors = section_objs(info, ".ctors",
2060 				  sizeof(*mod->ctors), &mod->num_ctors);
2061 	if (!mod->ctors)
2062 		mod->ctors = section_objs(info, ".init_array",
2063 				sizeof(*mod->ctors), &mod->num_ctors);
2064 	else if (find_sec(info, ".init_array")) {
2065 		/*
2066 		 * This shouldn't happen with same compiler and binutils
2067 		 * building all parts of the module.
2068 		 */
2069 		pr_warn("%s: has both .ctors and .init_array.\n",
2070 		       mod->name);
2071 		return -EINVAL;
2072 	}
2073 #endif
2074 
2075 	mod->noinstr_text_start = section_objs(info, ".noinstr.text", 1,
2076 						&mod->noinstr_text_size);
2077 
2078 #ifdef CONFIG_TRACEPOINTS
2079 	mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
2080 					     sizeof(*mod->tracepoints_ptrs),
2081 					     &mod->num_tracepoints);
2082 #endif
2083 #ifdef CONFIG_TREE_SRCU
2084 	mod->srcu_struct_ptrs = section_objs(info, "___srcu_struct_ptrs",
2085 					     sizeof(*mod->srcu_struct_ptrs),
2086 					     &mod->num_srcu_structs);
2087 #endif
2088 #ifdef CONFIG_BPF_EVENTS
2089 	mod->bpf_raw_events = section_objs(info, "__bpf_raw_tp_map",
2090 					   sizeof(*mod->bpf_raw_events),
2091 					   &mod->num_bpf_raw_events);
2092 #endif
2093 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
2094 	mod->btf_data = any_section_objs(info, ".BTF", 1, &mod->btf_data_size);
2095 #endif
2096 #ifdef CONFIG_JUMP_LABEL
2097 	mod->jump_entries = section_objs(info, "__jump_table",
2098 					sizeof(*mod->jump_entries),
2099 					&mod->num_jump_entries);
2100 #endif
2101 #ifdef CONFIG_EVENT_TRACING
2102 	mod->trace_events = section_objs(info, "_ftrace_events",
2103 					 sizeof(*mod->trace_events),
2104 					 &mod->num_trace_events);
2105 	mod->trace_evals = section_objs(info, "_ftrace_eval_map",
2106 					sizeof(*mod->trace_evals),
2107 					&mod->num_trace_evals);
2108 #endif
2109 #ifdef CONFIG_TRACING
2110 	mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
2111 					 sizeof(*mod->trace_bprintk_fmt_start),
2112 					 &mod->num_trace_bprintk_fmt);
2113 #endif
2114 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
2115 	/* sechdrs[0].sh_size is always zero */
2116 	mod->ftrace_callsites = section_objs(info, FTRACE_CALLSITE_SECTION,
2117 					     sizeof(*mod->ftrace_callsites),
2118 					     &mod->num_ftrace_callsites);
2119 #endif
2120 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
2121 	mod->ei_funcs = section_objs(info, "_error_injection_whitelist",
2122 					    sizeof(*mod->ei_funcs),
2123 					    &mod->num_ei_funcs);
2124 #endif
2125 #ifdef CONFIG_KPROBES
2126 	mod->kprobes_text_start = section_objs(info, ".kprobes.text", 1,
2127 						&mod->kprobes_text_size);
2128 	mod->kprobe_blacklist = section_objs(info, "_kprobe_blacklist",
2129 						sizeof(unsigned long),
2130 						&mod->num_kprobe_blacklist);
2131 #endif
2132 #ifdef CONFIG_PRINTK_INDEX
2133 	mod->printk_index_start = section_objs(info, ".printk_index",
2134 					       sizeof(*mod->printk_index_start),
2135 					       &mod->printk_index_size);
2136 #endif
2137 #ifdef CONFIG_HAVE_STATIC_CALL_INLINE
2138 	mod->static_call_sites = section_objs(info, ".static_call_sites",
2139 					      sizeof(*mod->static_call_sites),
2140 					      &mod->num_static_call_sites);
2141 #endif
2142 #if IS_ENABLED(CONFIG_KUNIT)
2143 	mod->kunit_suites = section_objs(info, ".kunit_test_suites",
2144 					      sizeof(*mod->kunit_suites),
2145 					      &mod->num_kunit_suites);
2146 #endif
2147 
2148 	mod->extable = section_objs(info, "__ex_table",
2149 				    sizeof(*mod->extable), &mod->num_exentries);
2150 
2151 	if (section_addr(info, "__obsparm"))
2152 		pr_warn("%s: Ignoring obsolete parameters\n", mod->name);
2153 
2154 	info->dyndbg.descs = section_objs(info, "__dyndbg",
2155 					sizeof(*info->dyndbg.descs), &info->dyndbg.num_descs);
2156 	info->dyndbg.classes = section_objs(info, "__dyndbg_classes",
2157 					sizeof(*info->dyndbg.classes), &info->dyndbg.num_classes);
2158 
2159 	return 0;
2160 }
2161 
move_module(struct module * mod,struct load_info * info)2162 static int move_module(struct module *mod, struct load_info *info)
2163 {
2164 	int i;
2165 	void *ptr;
2166 
2167 	/* Do the allocs. */
2168 	ptr = module_alloc(mod->core_layout.size);
2169 	/*
2170 	 * The pointer to this block is stored in the module structure
2171 	 * which is inside the block. Just mark it as not being a
2172 	 * leak.
2173 	 */
2174 	kmemleak_not_leak(ptr);
2175 	if (!ptr)
2176 		return -ENOMEM;
2177 
2178 	memset(ptr, 0, mod->core_layout.size);
2179 	mod->core_layout.base = ptr;
2180 
2181 	if (mod->init_layout.size) {
2182 		ptr = module_alloc(mod->init_layout.size);
2183 		/*
2184 		 * The pointer to this block is stored in the module structure
2185 		 * which is inside the block. This block doesn't need to be
2186 		 * scanned as it contains data and code that will be freed
2187 		 * after the module is initialized.
2188 		 */
2189 		kmemleak_ignore(ptr);
2190 		if (!ptr) {
2191 			module_memfree(mod->core_layout.base);
2192 			return -ENOMEM;
2193 		}
2194 		memset(ptr, 0, mod->init_layout.size);
2195 		mod->init_layout.base = ptr;
2196 	} else
2197 		mod->init_layout.base = NULL;
2198 
2199 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
2200 	/* Do the allocs. */
2201 	ptr = vzalloc(mod->data_layout.size);
2202 	/*
2203 	 * The pointer to this block is stored in the module structure
2204 	 * which is inside the block. Just mark it as not being a
2205 	 * leak.
2206 	 */
2207 	kmemleak_not_leak(ptr);
2208 	if (!ptr) {
2209 		module_memfree(mod->core_layout.base);
2210 		module_memfree(mod->init_layout.base);
2211 		return -ENOMEM;
2212 	}
2213 
2214 	mod->data_layout.base = ptr;
2215 #endif
2216 	/* Transfer each section which specifies SHF_ALLOC */
2217 	pr_debug("final section addresses:\n");
2218 	for (i = 0; i < info->hdr->e_shnum; i++) {
2219 		void *dest;
2220 		Elf_Shdr *shdr = &info->sechdrs[i];
2221 
2222 		if (!(shdr->sh_flags & SHF_ALLOC))
2223 			continue;
2224 
2225 		if (shdr->sh_entsize & INIT_OFFSET_MASK)
2226 			dest = mod->init_layout.base
2227 				+ (shdr->sh_entsize & ~INIT_OFFSET_MASK);
2228 		else if (!(shdr->sh_flags & SHF_EXECINSTR))
2229 			dest = mod->data_layout.base + shdr->sh_entsize;
2230 		else
2231 			dest = mod->core_layout.base + shdr->sh_entsize;
2232 
2233 		if (shdr->sh_type != SHT_NOBITS)
2234 			memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
2235 		/* Update sh_addr to point to copy in image. */
2236 		shdr->sh_addr = (unsigned long)dest;
2237 		pr_debug("\t0x%lx %s\n",
2238 			 (long)shdr->sh_addr, info->secstrings + shdr->sh_name);
2239 	}
2240 
2241 	return 0;
2242 }
2243 
check_module_license_and_versions(struct module * mod)2244 static int check_module_license_and_versions(struct module *mod)
2245 {
2246 	int prev_taint = test_taint(TAINT_PROPRIETARY_MODULE);
2247 
2248 	/*
2249 	 * ndiswrapper is under GPL by itself, but loads proprietary modules.
2250 	 * Don't use add_taint_module(), as it would prevent ndiswrapper from
2251 	 * using GPL-only symbols it needs.
2252 	 */
2253 	if (strcmp(mod->name, "ndiswrapper") == 0)
2254 		add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
2255 
2256 	/* driverloader was caught wrongly pretending to be under GPL */
2257 	if (strcmp(mod->name, "driverloader") == 0)
2258 		add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2259 				 LOCKDEP_NOW_UNRELIABLE);
2260 
2261 	/* lve claims to be GPL but upstream won't provide source */
2262 	if (strcmp(mod->name, "lve") == 0)
2263 		add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2264 				 LOCKDEP_NOW_UNRELIABLE);
2265 
2266 	if (!prev_taint && test_taint(TAINT_PROPRIETARY_MODULE))
2267 		pr_warn("%s: module license taints kernel.\n", mod->name);
2268 
2269 #ifdef CONFIG_MODVERSIONS
2270 	if ((mod->num_syms && !mod->crcs) ||
2271 	    (mod->num_gpl_syms && !mod->gpl_crcs)) {
2272 		return try_to_force_load(mod,
2273 					 "no versions for exported symbols");
2274 	}
2275 #endif
2276 	return 0;
2277 }
2278 
flush_module_icache(const struct module * mod)2279 static void flush_module_icache(const struct module *mod)
2280 {
2281 	/*
2282 	 * Flush the instruction cache, since we've played with text.
2283 	 * Do it before processing of module parameters, so the module
2284 	 * can provide parameter accessor functions of its own.
2285 	 */
2286 	if (mod->init_layout.base)
2287 		flush_icache_range((unsigned long)mod->init_layout.base,
2288 				   (unsigned long)mod->init_layout.base
2289 				   + mod->init_layout.size);
2290 	flush_icache_range((unsigned long)mod->core_layout.base,
2291 			   (unsigned long)mod->core_layout.base + mod->core_layout.size);
2292 }
2293 
module_frob_arch_sections(Elf_Ehdr * hdr,Elf_Shdr * sechdrs,char * secstrings,struct module * mod)2294 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
2295 				     Elf_Shdr *sechdrs,
2296 				     char *secstrings,
2297 				     struct module *mod)
2298 {
2299 	return 0;
2300 }
2301 
2302 /* module_blacklist is a comma-separated list of module names */
2303 static char *module_blacklist;
blacklisted(const char * module_name)2304 static bool blacklisted(const char *module_name)
2305 {
2306 	const char *p;
2307 	size_t len;
2308 
2309 	if (!module_blacklist)
2310 		return false;
2311 
2312 	for (p = module_blacklist; *p; p += len) {
2313 		len = strcspn(p, ",");
2314 		if (strlen(module_name) == len && !memcmp(module_name, p, len))
2315 			return true;
2316 		if (p[len] == ',')
2317 			len++;
2318 	}
2319 	return false;
2320 }
2321 core_param(module_blacklist, module_blacklist, charp, 0400);
2322 
layout_and_allocate(struct load_info * info,int flags)2323 static struct module *layout_and_allocate(struct load_info *info, int flags)
2324 {
2325 	struct module *mod;
2326 	unsigned int ndx;
2327 	int err;
2328 
2329 	err = check_modinfo(info->mod, info, flags);
2330 	if (err)
2331 		return ERR_PTR(err);
2332 
2333 	/* Allow arches to frob section contents and sizes.  */
2334 	err = module_frob_arch_sections(info->hdr, info->sechdrs,
2335 					info->secstrings, info->mod);
2336 	if (err < 0)
2337 		return ERR_PTR(err);
2338 
2339 	err = module_enforce_rwx_sections(info->hdr, info->sechdrs,
2340 					  info->secstrings, info->mod);
2341 	if (err < 0)
2342 		return ERR_PTR(err);
2343 
2344 	/* We will do a special allocation for per-cpu sections later. */
2345 	info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
2346 
2347 	/*
2348 	 * Mark ro_after_init section with SHF_RO_AFTER_INIT so that
2349 	 * layout_sections() can put it in the right place.
2350 	 * Note: ro_after_init sections also have SHF_{WRITE,ALLOC} set.
2351 	 */
2352 	ndx = find_sec(info, ".data..ro_after_init");
2353 	if (ndx)
2354 		info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
2355 	/*
2356 	 * Mark the __jump_table section as ro_after_init as well: these data
2357 	 * structures are never modified, with the exception of entries that
2358 	 * refer to code in the __init section, which are annotated as such
2359 	 * at module load time.
2360 	 */
2361 	ndx = find_sec(info, "__jump_table");
2362 	if (ndx)
2363 		info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
2364 
2365 	/*
2366 	 * Determine total sizes, and put offsets in sh_entsize.  For now
2367 	 * this is done generically; there doesn't appear to be any
2368 	 * special cases for the architectures.
2369 	 */
2370 	layout_sections(info->mod, info);
2371 	layout_symtab(info->mod, info);
2372 
2373 	/* Allocate and move to the final place */
2374 	err = move_module(info->mod, info);
2375 	if (err)
2376 		return ERR_PTR(err);
2377 
2378 	/* Module has been copied to its final place now: return it. */
2379 	mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2380 	kmemleak_load_module(mod, info);
2381 	return mod;
2382 }
2383 
2384 /* mod is no longer valid after this! */
module_deallocate(struct module * mod,struct load_info * info)2385 static void module_deallocate(struct module *mod, struct load_info *info)
2386 {
2387 	percpu_modfree(mod);
2388 	module_arch_freeing_init(mod);
2389 	trace_android_rvh_set_module_init_rw_nx(mod);
2390 	module_memfree(mod->init_layout.base);
2391 	trace_android_rvh_set_module_core_rw_nx(mod);
2392 	module_memfree(mod->core_layout.base);
2393 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
2394 	vfree(mod->data_layout.base);
2395 #endif
2396 }
2397 
module_finalize(const Elf_Ehdr * hdr,const Elf_Shdr * sechdrs,struct module * me)2398 int __weak module_finalize(const Elf_Ehdr *hdr,
2399 			   const Elf_Shdr *sechdrs,
2400 			   struct module *me)
2401 {
2402 	return 0;
2403 }
2404 
post_relocation(struct module * mod,const struct load_info * info)2405 static int post_relocation(struct module *mod, const struct load_info *info)
2406 {
2407 	/* Sort exception table now relocations are done. */
2408 	sort_extable(mod->extable, mod->extable + mod->num_exentries);
2409 
2410 	/* Copy relocated percpu area over. */
2411 	percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
2412 		       info->sechdrs[info->index.pcpu].sh_size);
2413 
2414 	/* Setup kallsyms-specific fields. */
2415 	add_kallsyms(mod, info);
2416 
2417 	/* Arch-specific module finalizing. */
2418 	return module_finalize(info->hdr, info->sechdrs, mod);
2419 }
2420 
2421 /* Is this module of this name done loading?  No locks held. */
finished_loading(const char * name)2422 static bool finished_loading(const char *name)
2423 {
2424 	struct module *mod;
2425 	bool ret;
2426 
2427 	/*
2428 	 * The module_mutex should not be a heavily contended lock;
2429 	 * if we get the occasional sleep here, we'll go an extra iteration
2430 	 * in the wait_event_interruptible(), which is harmless.
2431 	 */
2432 	sched_annotate_sleep();
2433 	mutex_lock(&module_mutex);
2434 	mod = find_module_all(name, strlen(name), true);
2435 	ret = !mod || mod->state == MODULE_STATE_LIVE
2436 		|| mod->state == MODULE_STATE_GOING;
2437 	mutex_unlock(&module_mutex);
2438 
2439 	return ret;
2440 }
2441 
2442 /* Call module constructors. */
do_mod_ctors(struct module * mod)2443 static void do_mod_ctors(struct module *mod)
2444 {
2445 #ifdef CONFIG_CONSTRUCTORS
2446 	unsigned long i;
2447 
2448 	for (i = 0; i < mod->num_ctors; i++)
2449 		mod->ctors[i]();
2450 #endif
2451 }
2452 
2453 /* For freeing module_init on success, in case kallsyms traversing */
2454 struct mod_initfree {
2455 	struct llist_node node;
2456 	void *module_init;
2457 };
2458 
do_free_init(struct work_struct * w)2459 static void do_free_init(struct work_struct *w)
2460 {
2461 	struct llist_node *pos, *n, *list;
2462 	struct mod_initfree *initfree;
2463 
2464 	list = llist_del_all(&init_free_list);
2465 
2466 	synchronize_rcu();
2467 
2468 	llist_for_each_safe(pos, n, list) {
2469 		initfree = container_of(pos, struct mod_initfree, node);
2470 		module_memfree(initfree->module_init);
2471 		kfree(initfree);
2472 	}
2473 }
2474 
2475 #undef MODULE_PARAM_PREFIX
2476 #define MODULE_PARAM_PREFIX "module."
2477 /* Default value for module->async_probe_requested */
2478 static bool async_probe;
2479 module_param(async_probe, bool, 0644);
2480 
2481 /*
2482  * This is where the real work happens.
2483  *
2484  * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb
2485  * helper command 'lx-symbols'.
2486  */
do_init_module(struct module * mod)2487 static noinline int do_init_module(struct module *mod)
2488 {
2489 	int ret = 0;
2490 	struct mod_initfree *freeinit;
2491 
2492 	freeinit = kmalloc(sizeof(*freeinit), GFP_KERNEL);
2493 	if (!freeinit) {
2494 		ret = -ENOMEM;
2495 		goto fail;
2496 	}
2497 	freeinit->module_init = mod->init_layout.base;
2498 
2499 	do_mod_ctors(mod);
2500 	/* Start the module */
2501 	if (mod->init != NULL)
2502 		ret = do_one_initcall(mod->init);
2503 	if (ret < 0) {
2504 		goto fail_free_freeinit;
2505 	}
2506 	if (ret > 0) {
2507 		pr_warn("%s: '%s'->init suspiciously returned %d, it should "
2508 			"follow 0/-E convention\n"
2509 			"%s: loading module anyway...\n",
2510 			__func__, mod->name, ret, __func__);
2511 		dump_stack();
2512 	}
2513 
2514 	/* Now it's a first class citizen! */
2515 	mod->state = MODULE_STATE_LIVE;
2516 	blocking_notifier_call_chain(&module_notify_list,
2517 				     MODULE_STATE_LIVE, mod);
2518 
2519 	/* Delay uevent until module has finished its init routine */
2520 	kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
2521 
2522 	/*
2523 	 * We need to finish all async code before the module init sequence
2524 	 * is done. This has potential to deadlock if synchronous module
2525 	 * loading is requested from async (which is not allowed!).
2526 	 *
2527 	 * See commit 0fdff3ec6d87 ("async, kmod: warn on synchronous
2528 	 * request_module() from async workers") for more details.
2529 	 */
2530 	if (!mod->async_probe_requested)
2531 		async_synchronize_full();
2532 
2533 	ftrace_free_mem(mod, mod->init_layout.base, mod->init_layout.base +
2534 			mod->init_layout.size);
2535 	mutex_lock(&module_mutex);
2536 	/* Drop initial reference. */
2537 	module_put(mod);
2538 	trim_init_extable(mod);
2539 #ifdef CONFIG_KALLSYMS
2540 	/* Switch to core kallsyms now init is done: kallsyms may be walking! */
2541 	rcu_assign_pointer(mod->kallsyms, &mod->core_kallsyms);
2542 #endif
2543 	module_enable_ro(mod, true);
2544 	trace_android_rvh_set_module_permit_after_init(mod);
2545 	mod_tree_remove_init(mod);
2546 	module_arch_freeing_init(mod);
2547 	trace_android_rvh_set_module_init_rw_nx(mod);
2548 	mod->init_layout.base = NULL;
2549 	mod->init_layout.size = 0;
2550 	mod->init_layout.ro_size = 0;
2551 	mod->init_layout.ro_after_init_size = 0;
2552 	mod->init_layout.text_size = 0;
2553 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
2554 	/* .BTF is not SHF_ALLOC and will get removed, so sanitize pointer */
2555 	mod->btf_data = NULL;
2556 #endif
2557 	/*
2558 	 * We want to free module_init, but be aware that kallsyms may be
2559 	 * walking this with preempt disabled.  In all the failure paths, we
2560 	 * call synchronize_rcu(), but we don't want to slow down the success
2561 	 * path. module_memfree() cannot be called in an interrupt, so do the
2562 	 * work and call synchronize_rcu() in a work queue.
2563 	 *
2564 	 * Note that module_alloc() on most architectures creates W+X page
2565 	 * mappings which won't be cleaned up until do_free_init() runs.  Any
2566 	 * code such as mark_rodata_ro() which depends on those mappings to
2567 	 * be cleaned up needs to sync with the queued work - ie
2568 	 * rcu_barrier()
2569 	 */
2570 	if (llist_add(&freeinit->node, &init_free_list))
2571 		schedule_work(&init_free_wq);
2572 
2573 	mutex_unlock(&module_mutex);
2574 	wake_up_all(&module_wq);
2575 
2576 	return 0;
2577 
2578 fail_free_freeinit:
2579 	kfree(freeinit);
2580 fail:
2581 	/* Try to protect us from buggy refcounters. */
2582 	mod->state = MODULE_STATE_GOING;
2583 	synchronize_rcu();
2584 	module_put(mod);
2585 	blocking_notifier_call_chain(&module_notify_list,
2586 				     MODULE_STATE_GOING, mod);
2587 	klp_module_going(mod);
2588 	ftrace_release_mod(mod);
2589 	free_module(mod);
2590 	wake_up_all(&module_wq);
2591 	return ret;
2592 }
2593 
may_init_module(void)2594 static int may_init_module(void)
2595 {
2596 	if (!capable(CAP_SYS_MODULE) || modules_disabled)
2597 		return -EPERM;
2598 
2599 	return 0;
2600 }
2601 
2602 /*
2603  * We try to place it in the list now to make sure it's unique before
2604  * we dedicate too many resources.  In particular, temporary percpu
2605  * memory exhaustion.
2606  */
add_unformed_module(struct module * mod)2607 static int add_unformed_module(struct module *mod)
2608 {
2609 	int err;
2610 	struct module *old;
2611 
2612 	mod->state = MODULE_STATE_UNFORMED;
2613 
2614 	mutex_lock(&module_mutex);
2615 	old = find_module_all(mod->name, strlen(mod->name), true);
2616 	if (old != NULL) {
2617 		if (old->state == MODULE_STATE_COMING
2618 		    || old->state == MODULE_STATE_UNFORMED) {
2619 			/* Wait in case it fails to load. */
2620 			mutex_unlock(&module_mutex);
2621 			err = wait_event_interruptible(module_wq,
2622 					       finished_loading(mod->name));
2623 			if (err)
2624 				goto out_unlocked;
2625 
2626 			/* The module might have gone in the meantime. */
2627 			mutex_lock(&module_mutex);
2628 			old = find_module_all(mod->name, strlen(mod->name),
2629 					      true);
2630 		}
2631 
2632 		/*
2633 		 * We are here only when the same module was being loaded. Do
2634 		 * not try to load it again right now. It prevents long delays
2635 		 * caused by serialized module load failures. It might happen
2636 		 * when more devices of the same type trigger load of
2637 		 * a particular module.
2638 		 */
2639 		if (old && old->state == MODULE_STATE_LIVE)
2640 			err = -EEXIST;
2641 		else
2642 			err = -EBUSY;
2643 		goto out;
2644 	}
2645 	mod_update_bounds(mod);
2646 	list_add_rcu(&mod->list, &modules);
2647 	mod_tree_insert(mod);
2648 	err = 0;
2649 
2650 out:
2651 	mutex_unlock(&module_mutex);
2652 out_unlocked:
2653 	return err;
2654 }
2655 
complete_formation(struct module * mod,struct load_info * info)2656 static int complete_formation(struct module *mod, struct load_info *info)
2657 {
2658 	int err;
2659 
2660 	mutex_lock(&module_mutex);
2661 
2662 	/* Find duplicate symbols (must be called under lock). */
2663 	err = verify_exported_symbols(mod);
2664 	if (err < 0)
2665 		goto out;
2666 
2667 	/* These rely on module_mutex for list integrity. */
2668 	module_bug_finalize(info->hdr, info->sechdrs, mod);
2669 	module_cfi_finalize(info->hdr, info->sechdrs, mod);
2670 
2671 	if (module_check_misalignment(mod))
2672 		goto out_misaligned;
2673 
2674 	module_enable_ro(mod, false);
2675 	module_enable_nx(mod);
2676 	module_enable_x(mod);
2677 	trace_android_rvh_set_module_permit_before_init(mod);
2678 
2679 	/*
2680 	 * Mark state as coming so strong_try_module_get() ignores us,
2681 	 * but kallsyms etc. can see us.
2682 	 */
2683 	mod->state = MODULE_STATE_COMING;
2684 	mutex_unlock(&module_mutex);
2685 
2686 	return 0;
2687 
2688 out_misaligned:
2689 	err = -EINVAL;
2690 out:
2691 	mutex_unlock(&module_mutex);
2692 	return err;
2693 }
2694 
prepare_coming_module(struct module * mod)2695 static int prepare_coming_module(struct module *mod)
2696 {
2697 	int err;
2698 
2699 	ftrace_module_enable(mod);
2700 	err = klp_module_coming(mod);
2701 	if (err)
2702 		return err;
2703 
2704 	err = blocking_notifier_call_chain_robust(&module_notify_list,
2705 			MODULE_STATE_COMING, MODULE_STATE_GOING, mod);
2706 	err = notifier_to_errno(err);
2707 	if (err)
2708 		klp_module_going(mod);
2709 
2710 	return err;
2711 }
2712 
unknown_module_param_cb(char * param,char * val,const char * modname,void * arg)2713 static int unknown_module_param_cb(char *param, char *val, const char *modname,
2714 				   void *arg)
2715 {
2716 	struct module *mod = arg;
2717 	int ret;
2718 
2719 	if (strcmp(param, "async_probe") == 0) {
2720 		if (strtobool(val, &mod->async_probe_requested))
2721 			mod->async_probe_requested = true;
2722 		return 0;
2723 	}
2724 
2725 	/* Check for magic 'dyndbg' arg */
2726 	ret = ddebug_dyndbg_module_param_cb(param, val, modname);
2727 	if (ret != 0)
2728 		pr_warn("%s: unknown parameter '%s' ignored\n", modname, param);
2729 	return 0;
2730 }
2731 
2732 /*
2733  * Allocate and load the module: note that size of section 0 is always
2734  * zero, and we rely on this for optional sections.
2735  */
load_module(struct load_info * info,const char __user * uargs,int flags)2736 static int load_module(struct load_info *info, const char __user *uargs,
2737 		       int flags)
2738 {
2739 	struct module *mod;
2740 	long err = 0;
2741 	char *after_dashes;
2742 
2743 	/*
2744 	 * Do the signature check (if any) first. All that
2745 	 * the signature check needs is info->len, it does
2746 	 * not need any of the section info. That can be
2747 	 * set up later. This will minimize the chances
2748 	 * of a corrupt module causing problems before
2749 	 * we even get to the signature check.
2750 	 *
2751 	 * The check will also adjust info->len by stripping
2752 	 * off the sig length at the end of the module, making
2753 	 * checks against info->len more correct.
2754 	 */
2755 	err = module_sig_check(info, flags);
2756 	if (err)
2757 		goto free_copy;
2758 
2759 	/*
2760 	 * Do basic sanity checks against the ELF header and
2761 	 * sections.
2762 	 */
2763 	err = elf_validity_check(info);
2764 	if (err)
2765 		goto free_copy;
2766 
2767 	/*
2768 	 * Everything checks out, so set up the section info
2769 	 * in the info structure.
2770 	 */
2771 	err = setup_load_info(info, flags);
2772 	if (err)
2773 		goto free_copy;
2774 
2775 	/*
2776 	 * Now that we know we have the correct module name, check
2777 	 * if it's blacklisted.
2778 	 */
2779 	if (blacklisted(info->name)) {
2780 		err = -EPERM;
2781 		pr_err("Module %s is blacklisted\n", info->name);
2782 		goto free_copy;
2783 	}
2784 
2785 	err = rewrite_section_headers(info, flags);
2786 	if (err)
2787 		goto free_copy;
2788 
2789 	/* Check module struct version now, before we try to use module. */
2790 	if (!check_modstruct_version(info, info->mod)) {
2791 		err = -ENOEXEC;
2792 		goto free_copy;
2793 	}
2794 
2795 	/* Figure out module layout, and allocate all the memory. */
2796 	mod = layout_and_allocate(info, flags);
2797 	if (IS_ERR(mod)) {
2798 		err = PTR_ERR(mod);
2799 		goto free_copy;
2800 	}
2801 
2802 	audit_log_kern_module(mod->name);
2803 
2804 	/* Reserve our place in the list. */
2805 	err = add_unformed_module(mod);
2806 	if (err)
2807 		goto free_module;
2808 
2809 #ifdef CONFIG_MODULE_SIG
2810 	mod->sig_ok = info->sig_ok;
2811 	if (!mod->sig_ok) {
2812 		pr_notice_once("%s: module verification failed: signature "
2813 			       "and/or required key missing - tainting "
2814 			       "kernel\n", mod->name);
2815 		add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
2816 	}
2817 #else
2818 	mod->sig_ok = 0;
2819 #endif
2820 
2821 	/* To avoid stressing percpu allocator, do this once we're unique. */
2822 	err = percpu_modalloc(mod, info);
2823 	if (err)
2824 		goto unlink_mod;
2825 
2826 	/* Now module is in final location, initialize linked lists, etc. */
2827 	err = module_unload_init(mod);
2828 	if (err)
2829 		goto unlink_mod;
2830 
2831 	init_param_lock(mod);
2832 
2833 	/*
2834 	 * Now we've got everything in the final locations, we can
2835 	 * find optional sections.
2836 	 */
2837 	err = find_module_sections(mod, info);
2838 	if (err)
2839 		goto free_unload;
2840 
2841 	err = check_module_license_and_versions(mod);
2842 	if (err)
2843 		goto free_unload;
2844 
2845 	/* Set up MODINFO_ATTR fields */
2846 	setup_modinfo(mod, info);
2847 
2848 	/* Fix up syms, so that st_value is a pointer to location. */
2849 	err = simplify_symbols(mod, info);
2850 	if (err < 0)
2851 		goto free_modinfo;
2852 
2853 	err = apply_relocations(mod, info);
2854 	if (err < 0)
2855 		goto free_modinfo;
2856 
2857 	err = post_relocation(mod, info);
2858 	if (err < 0)
2859 		goto free_modinfo;
2860 
2861 	flush_module_icache(mod);
2862 
2863 	/* Now copy in args */
2864 	mod->args = strndup_user(uargs, ~0UL >> 1);
2865 	if (IS_ERR(mod->args)) {
2866 		err = PTR_ERR(mod->args);
2867 		goto free_arch_cleanup;
2868 	}
2869 
2870 	init_build_id(mod, info);
2871 	dynamic_debug_setup(mod, &info->dyndbg);
2872 
2873 	/* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
2874 	ftrace_module_init(mod);
2875 
2876 	/* Finally it's fully formed, ready to start executing. */
2877 	err = complete_formation(mod, info);
2878 	if (err)
2879 		goto ddebug_cleanup;
2880 
2881 	err = prepare_coming_module(mod);
2882 	if (err)
2883 		goto bug_cleanup;
2884 
2885 	mod->async_probe_requested = async_probe;
2886 
2887 	/* Module is ready to execute: parsing args may do that. */
2888 	after_dashes = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
2889 				  -32768, 32767, mod,
2890 				  unknown_module_param_cb);
2891 	if (IS_ERR(after_dashes)) {
2892 		err = PTR_ERR(after_dashes);
2893 		goto coming_cleanup;
2894 	} else if (after_dashes) {
2895 		pr_warn("%s: parameters '%s' after `--' ignored\n",
2896 		       mod->name, after_dashes);
2897 	}
2898 
2899 	/* Link in to sysfs. */
2900 	err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
2901 	if (err < 0)
2902 		goto coming_cleanup;
2903 
2904 	if (is_livepatch_module(mod)) {
2905 		err = copy_module_elf(mod, info);
2906 		if (err < 0)
2907 			goto sysfs_cleanup;
2908 	}
2909 
2910 	/* Get rid of temporary copy. */
2911 	free_copy(info, flags);
2912 
2913 	/* Done! */
2914 	trace_module_load(mod);
2915 
2916 	return do_init_module(mod);
2917 
2918  sysfs_cleanup:
2919 	mod_sysfs_teardown(mod);
2920  coming_cleanup:
2921 	mod->state = MODULE_STATE_GOING;
2922 	destroy_params(mod->kp, mod->num_kp);
2923 	blocking_notifier_call_chain(&module_notify_list,
2924 				     MODULE_STATE_GOING, mod);
2925 	klp_module_going(mod);
2926  bug_cleanup:
2927 	mod->state = MODULE_STATE_GOING;
2928 	/* module_bug_cleanup needs module_mutex protection */
2929 	mutex_lock(&module_mutex);
2930 	module_bug_cleanup(mod);
2931 	mutex_unlock(&module_mutex);
2932 
2933  ddebug_cleanup:
2934 	ftrace_release_mod(mod);
2935 	dynamic_debug_remove(mod, &info->dyndbg);
2936 	synchronize_rcu();
2937 	kfree(mod->args);
2938  free_arch_cleanup:
2939 	module_arch_cleanup(mod);
2940  free_modinfo:
2941 	free_modinfo(mod);
2942  free_unload:
2943 	module_unload_free(mod);
2944  unlink_mod:
2945 	mutex_lock(&module_mutex);
2946 	/* Unlink carefully: kallsyms could be walking list. */
2947 	list_del_rcu(&mod->list);
2948 	mod_tree_remove(mod);
2949 	wake_up_all(&module_wq);
2950 	/* Wait for RCU-sched synchronizing before releasing mod->list. */
2951 	synchronize_rcu();
2952 	mutex_unlock(&module_mutex);
2953  free_module:
2954 	/* Free lock-classes; relies on the preceding sync_rcu() */
2955 	lockdep_free_key_range(mod->data_layout.base, mod->data_layout.size);
2956 
2957 	module_deallocate(mod, info);
2958  free_copy:
2959 	free_copy(info, flags);
2960 	return err;
2961 }
2962 
SYSCALL_DEFINE3(init_module,void __user *,umod,unsigned long,len,const char __user *,uargs)2963 SYSCALL_DEFINE3(init_module, void __user *, umod,
2964 		unsigned long, len, const char __user *, uargs)
2965 {
2966 	int err;
2967 	struct load_info info = { };
2968 
2969 	err = may_init_module();
2970 	if (err)
2971 		return err;
2972 
2973 	pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
2974 	       umod, len, uargs);
2975 
2976 	err = copy_module_from_user(umod, len, &info);
2977 	if (err)
2978 		return err;
2979 
2980 	return load_module(&info, uargs, 0);
2981 }
2982 
SYSCALL_DEFINE3(finit_module,int,fd,const char __user *,uargs,int,flags)2983 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
2984 {
2985 	struct load_info info = { };
2986 	void *buf = NULL;
2987 	int len;
2988 	int err;
2989 
2990 	err = may_init_module();
2991 	if (err)
2992 		return err;
2993 
2994 	pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
2995 
2996 	if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
2997 		      |MODULE_INIT_IGNORE_VERMAGIC
2998 		      |MODULE_INIT_COMPRESSED_FILE))
2999 		return -EINVAL;
3000 
3001 	len = kernel_read_file_from_fd(fd, 0, &buf, INT_MAX, NULL,
3002 				       READING_MODULE);
3003 	if (len < 0)
3004 		return len;
3005 
3006 	if (flags & MODULE_INIT_COMPRESSED_FILE) {
3007 		err = module_decompress(&info, buf, len);
3008 		vfree(buf); /* compressed data is no longer needed */
3009 		if (err)
3010 			return err;
3011 	} else {
3012 		info.hdr = buf;
3013 		info.len = len;
3014 	}
3015 
3016 	return load_module(&info, uargs, flags);
3017 }
3018 
within(unsigned long addr,void * start,unsigned long size)3019 static inline int within(unsigned long addr, void *start, unsigned long size)
3020 {
3021 	return ((void *)addr >= start && (void *)addr < start + size);
3022 }
3023 
3024 /* Keep in sync with MODULE_FLAGS_BUF_SIZE !!! */
module_flags(struct module * mod,char * buf,bool show_state)3025 char *module_flags(struct module *mod, char *buf, bool show_state)
3026 {
3027 	int bx = 0;
3028 
3029 	BUG_ON(mod->state == MODULE_STATE_UNFORMED);
3030 	if (!mod->taints && !show_state)
3031 		goto out;
3032 	if (mod->taints ||
3033 	    mod->state == MODULE_STATE_GOING ||
3034 	    mod->state == MODULE_STATE_COMING) {
3035 		buf[bx++] = '(';
3036 		bx += module_flags_taint(mod->taints, buf + bx);
3037 		/* Show a - for module-is-being-unloaded */
3038 		if (mod->state == MODULE_STATE_GOING && show_state)
3039 			buf[bx++] = '-';
3040 		/* Show a + for module-is-being-loaded */
3041 		if (mod->state == MODULE_STATE_COMING && show_state)
3042 			buf[bx++] = '+';
3043 		buf[bx++] = ')';
3044 	}
3045 out:
3046 	buf[bx] = '\0';
3047 
3048 	return buf;
3049 }
3050 
3051 /* Given an address, look for it in the module exception tables. */
search_module_extables(unsigned long addr)3052 const struct exception_table_entry *search_module_extables(unsigned long addr)
3053 {
3054 	const struct exception_table_entry *e = NULL;
3055 	struct module *mod;
3056 
3057 	preempt_disable();
3058 	mod = __module_address(addr);
3059 	if (!mod)
3060 		goto out;
3061 
3062 	if (!mod->num_exentries)
3063 		goto out;
3064 
3065 	e = search_extable(mod->extable,
3066 			   mod->num_exentries,
3067 			   addr);
3068 out:
3069 	preempt_enable();
3070 
3071 	/*
3072 	 * Now, if we found one, we are running inside it now, hence
3073 	 * we cannot unload the module, hence no refcnt needed.
3074 	 */
3075 	return e;
3076 }
3077 
3078 /**
3079  * is_module_address() - is this address inside a module?
3080  * @addr: the address to check.
3081  *
3082  * See is_module_text_address() if you simply want to see if the address
3083  * is code (not data).
3084  */
is_module_address(unsigned long addr)3085 bool is_module_address(unsigned long addr)
3086 {
3087 	bool ret;
3088 
3089 	preempt_disable();
3090 	ret = __module_address(addr) != NULL;
3091 	preempt_enable();
3092 
3093 	return ret;
3094 }
3095 
3096 /**
3097  * __module_address() - get the module which contains an address.
3098  * @addr: the address.
3099  *
3100  * Must be called with preempt disabled or module mutex held so that
3101  * module doesn't get freed during this.
3102  */
__module_address(unsigned long addr)3103 struct module *__module_address(unsigned long addr)
3104 {
3105 	struct module *mod;
3106 	struct mod_tree_root *tree;
3107 
3108 	if (addr >= mod_tree.addr_min && addr <= mod_tree.addr_max)
3109 		tree = &mod_tree;
3110 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
3111 	else if (addr >= mod_data_tree.addr_min && addr <= mod_data_tree.addr_max)
3112 		tree = &mod_data_tree;
3113 #endif
3114 	else
3115 		return NULL;
3116 
3117 	module_assert_mutex_or_preempt();
3118 
3119 	mod = mod_find(addr, tree);
3120 	if (mod) {
3121 		BUG_ON(!within_module(addr, mod));
3122 		if (mod->state == MODULE_STATE_UNFORMED)
3123 			mod = NULL;
3124 	}
3125 	return mod;
3126 }
3127 
3128 /**
3129  * is_module_text_address() - is this address inside module code?
3130  * @addr: the address to check.
3131  *
3132  * See is_module_address() if you simply want to see if the address is
3133  * anywhere in a module.  See kernel_text_address() for testing if an
3134  * address corresponds to kernel or module code.
3135  */
is_module_text_address(unsigned long addr)3136 bool is_module_text_address(unsigned long addr)
3137 {
3138 	bool ret;
3139 
3140 	preempt_disable();
3141 	ret = __module_text_address(addr) != NULL;
3142 	preempt_enable();
3143 
3144 	return ret;
3145 }
3146 
3147 /**
3148  * __module_text_address() - get the module whose code contains an address.
3149  * @addr: the address.
3150  *
3151  * Must be called with preempt disabled or module mutex held so that
3152  * module doesn't get freed during this.
3153  */
__module_text_address(unsigned long addr)3154 struct module *__module_text_address(unsigned long addr)
3155 {
3156 	struct module *mod = __module_address(addr);
3157 	if (mod) {
3158 		/* Make sure it's within the text section. */
3159 		if (!within(addr, mod->init_layout.base, mod->init_layout.text_size)
3160 		    && !within(addr, mod->core_layout.base, mod->core_layout.text_size))
3161 			mod = NULL;
3162 	}
3163 	return mod;
3164 }
3165 
3166 /* Don't grab lock, we're oopsing. */
print_modules(void)3167 void print_modules(void)
3168 {
3169 	struct module *mod;
3170 	char buf[MODULE_FLAGS_BUF_SIZE];
3171 
3172 	printk(KERN_DEFAULT "Modules linked in:");
3173 	/* Most callers should already have preempt disabled, but make sure */
3174 	preempt_disable();
3175 	list_for_each_entry_rcu(mod, &modules, list) {
3176 		if (mod->state == MODULE_STATE_UNFORMED)
3177 			continue;
3178 		pr_cont(" %s%s", mod->name, module_flags(mod, buf, true));
3179 	}
3180 
3181 	print_unloaded_tainted_modules();
3182 	preempt_enable();
3183 	if (last_unloaded_module.name[0])
3184 		pr_cont(" [last unloaded: %s%s]", last_unloaded_module.name,
3185 			last_unloaded_module.taints);
3186 	pr_cont("\n");
3187 }
3188