xref: /linux/kernel/module/main.c (revision 55fbedcec622a943cb09a969aef1ddcba87ee40a)
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  * Copyright (C) 2023 Luis Chamberlain <mcgrof@kernel.org>
6  */
7 
8 #define INCLUDE_VERMAGIC
9 
10 #include <linux/export.h>
11 #include <linux/extable.h>
12 #include <linux/moduleloader.h>
13 #include <linux/module_signature.h>
14 #include <linux/module_symbol.h>
15 #include <linux/trace_events.h>
16 #include <linux/init.h>
17 #include <linux/kallsyms.h>
18 #include <linux/buildid.h>
19 #include <linux/fs.h>
20 #include <linux/kernel.h>
21 #include <linux/kernel_read_file.h>
22 #include <linux/kstrtox.h>
23 #include <linux/slab.h>
24 #include <linux/vmalloc.h>
25 #include <linux/elf.h>
26 #include <linux/seq_file.h>
27 #include <linux/syscalls.h>
28 #include <linux/fcntl.h>
29 #include <linux/rcupdate.h>
30 #include <linux/capability.h>
31 #include <linux/cpu.h>
32 #include <linux/moduleparam.h>
33 #include <linux/errno.h>
34 #include <linux/err.h>
35 #include <linux/vermagic.h>
36 #include <linux/notifier.h>
37 #include <linux/sched.h>
38 #include <linux/device.h>
39 #include <linux/string.h>
40 #include <linux/mutex.h>
41 #include <linux/rculist.h>
42 #include <linux/uaccess.h>
43 #include <asm/cacheflush.h>
44 #include <linux/set_memory.h>
45 #include <asm/mmu_context.h>
46 #include <linux/license.h>
47 #include <asm/sections.h>
48 #include <linux/tracepoint.h>
49 #include <linux/ftrace.h>
50 #include <linux/livepatch.h>
51 #include <linux/async.h>
52 #include <linux/percpu.h>
53 #include <linux/kmemleak.h>
54 #include <linux/jump_label.h>
55 #include <linux/pfn.h>
56 #include <linux/bsearch.h>
57 #include <linux/dynamic_debug.h>
58 #include <linux/audit.h>
59 #include <linux/cfi.h>
60 #include <linux/codetag.h>
61 #include <linux/debugfs.h>
62 #include <linux/execmem.h>
63 #include <linux/error-injection.h>
64 #include <uapi/linux/module.h>
65 #include "internal.h"
66 
67 #define CREATE_TRACE_POINTS
68 #include <trace/events/module.h>
69 
70 /*
71  * Mutex protects:
72  * 1) List of modules (also safely readable within RCU read section),
73  * 2) module_use links,
74  * 3) mod_tree.addr_min/mod_tree.addr_max.
75  * (delete and add uses RCU list operations).
76  */
77 DEFINE_MUTEX(module_mutex);
78 LIST_HEAD(modules);
79 
80 /* Work queue for freeing init sections in success case */
81 static void do_free_init(struct work_struct *w);
82 static DECLARE_WORK(init_free_wq, do_free_init);
83 static LLIST_HEAD(init_free_list);
84 
85 struct mod_tree_root mod_tree __cacheline_aligned = {
86 	.addr_min = -1UL,
87 };
88 
89 struct symsearch {
90 	const struct kernel_symbol *start, *stop;
91 	const u32 *crcs;
92 	const u8 *flagstab;
93 };
94 
95 /*
96  * Bounds of module memory, for speeding up __module_address.
97  * Protected by module_mutex.
98  */
99 static void __mod_update_bounds(enum mod_mem_type type __maybe_unused, void *base,
100 				unsigned int size, struct mod_tree_root *tree)
101 {
102 	unsigned long min = (unsigned long)base;
103 	unsigned long max = min + size;
104 
105 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
106 	if (mod_mem_type_is_core_data(type)) {
107 		if (min < tree->data_addr_min)
108 			tree->data_addr_min = min;
109 		if (max > tree->data_addr_max)
110 			tree->data_addr_max = max;
111 		return;
112 	}
113 #endif
114 	if (min < tree->addr_min)
115 		tree->addr_min = min;
116 	if (max > tree->addr_max)
117 		tree->addr_max = max;
118 }
119 
120 static void mod_update_bounds(struct module *mod)
121 {
122 	for_each_mod_mem_type(type) {
123 		struct module_memory *mod_mem = &mod->mem[type];
124 
125 		if (mod_mem->size)
126 			__mod_update_bounds(type, mod_mem->base, mod_mem->size, &mod_tree);
127 	}
128 }
129 
130 /* Block module loading/unloading? */
131 static int modules_disabled;
132 core_param(nomodule, modules_disabled, bint, 0);
133 
134 static const struct ctl_table module_sysctl_table[] = {
135 	{
136 		.procname	= "modprobe",
137 		.data		= &modprobe_path,
138 		.maxlen		= KMOD_PATH_LEN,
139 		.mode		= 0644,
140 		.proc_handler	= proc_dostring,
141 	},
142 	{
143 		.procname	= "modules_disabled",
144 		.data		= &modules_disabled,
145 		.maxlen		= sizeof(int),
146 		.mode		= 0644,
147 		/* only handle a transition from default "0" to "1" */
148 		.proc_handler	= proc_dointvec_minmax,
149 		.extra1		= SYSCTL_ONE,
150 		.extra2		= SYSCTL_ONE,
151 	},
152 };
153 
154 static int __init init_module_sysctl(void)
155 {
156 	register_sysctl_init("kernel", module_sysctl_table);
157 	return 0;
158 }
159 
160 subsys_initcall(init_module_sysctl);
161 
162 /* Waiting for a module to finish initializing? */
163 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
164 
165 static BLOCKING_NOTIFIER_HEAD(module_notify_list);
166 
167 int register_module_notifier(struct notifier_block *nb)
168 {
169 	return blocking_notifier_chain_register(&module_notify_list, nb);
170 }
171 EXPORT_SYMBOL(register_module_notifier);
172 
173 int unregister_module_notifier(struct notifier_block *nb)
174 {
175 	return blocking_notifier_chain_unregister(&module_notify_list, nb);
176 }
177 EXPORT_SYMBOL(unregister_module_notifier);
178 
179 /*
180  * We require a truly strong try_module_get(): 0 means success.
181  * Otherwise an error is returned due to ongoing or failed
182  * initialization etc.
183  */
184 static inline int strong_try_module_get(struct module *mod)
185 {
186 	BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED);
187 	if (mod && mod->state == MODULE_STATE_COMING)
188 		return -EBUSY;
189 	if (try_module_get(mod))
190 		return 0;
191 	else
192 		return -ENOENT;
193 }
194 
195 /**
196  * add_taint_module: add a taint flag if not already set for a specific module
197  * @mod: pointer to the module that caused the problem
198  * @flag: one of the TAINT_* constants.
199  * @lockdep_ok: whether lock debugging is still OK.
200  *
201  * If something bad has gone wrong, you'll want
202  * @lockdep_ok = LOCKDEP_NOW_UNRELIABLE, but for some
203  * noteworthy-but-not-corrupting cases, it can be set to LOCKDEP_STILL_OK.
204  */
205 void add_taint_module(struct module *mod, unsigned flag,
206 		      enum lockdep_ok lockdep_ok)
207 {
208 	add_taint(flag, lockdep_ok);
209 	if (mod)
210 		set_bit(flag, &mod->taints);
211 }
212 
213 /*
214  * Like strncmp(), except s/-/_/g as per scripts/Makefile.lib:name-fix-token rule.
215  */
216 static int mod_strncmp(const char *str_a, const char *str_b, size_t n)
217 {
218 	for (int i = 0; i < n; i++) {
219 		char a = str_a[i];
220 		char b = str_b[i];
221 		int d;
222 
223 		if (a == '-') a = '_';
224 		if (b == '-') b = '_';
225 
226 		d = a - b;
227 		if (d)
228 			return d;
229 
230 		if (!a)
231 			break;
232 	}
233 
234 	return 0;
235 }
236 
237 /*
238  * A thread that wants to hold a reference to a module only while it
239  * is running can call this to safely exit.
240  */
241 void __noreturn __module_put_and_kthread_exit(struct module *mod, long code)
242 {
243 	module_put(mod);
244 	kthread_exit(code);
245 }
246 EXPORT_SYMBOL(__module_put_and_kthread_exit);
247 
248 /* Find a module section: 0 means not found. */
249 static unsigned int find_sec(const struct load_info *info, const char *name)
250 {
251 	unsigned int i;
252 
253 	for (i = 1; i < info->hdr->e_shnum; i++) {
254 		Elf_Shdr *shdr = &info->sechdrs[i];
255 		/* Alloc bit cleared means "ignore it." */
256 		if ((shdr->sh_flags & SHF_ALLOC)
257 		    && strcmp(info->secstrings + shdr->sh_name, name) == 0)
258 			return i;
259 	}
260 	return 0;
261 }
262 
263 /**
264  * find_any_unique_sec() - Find a unique section index by name
265  * @info: Load info for the module to scan
266  * @name: Name of the section we're looking for
267  *
268  * Locates a unique section by name. Ignores SHF_ALLOC.
269  *
270  * Return: Section index if found uniquely, zero if absent, negative count
271  *         of total instances if multiple were found.
272  */
273 static int find_any_unique_sec(const struct load_info *info, const char *name)
274 {
275 	unsigned int idx;
276 	unsigned int count = 0;
277 	int i;
278 
279 	for (i = 1; i < info->hdr->e_shnum; i++) {
280 		if (strcmp(info->secstrings + info->sechdrs[i].sh_name,
281 			   name) == 0) {
282 			count++;
283 			idx = i;
284 		}
285 	}
286 	if (count == 1) {
287 		return idx;
288 	} else if (count == 0) {
289 		return 0;
290 	} else {
291 		return -count;
292 	}
293 }
294 
295 /* Find a module section, or NULL. */
296 static void *section_addr(const struct load_info *info, const char *name)
297 {
298 	/* Section 0 has sh_addr 0. */
299 	return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
300 }
301 
302 /* Find a module section, or NULL.  Fill in number of "objects" in section. */
303 static void *section_objs(const struct load_info *info,
304 			  const char *name,
305 			  size_t object_size,
306 			  unsigned int *num)
307 {
308 	unsigned int sec = find_sec(info, name);
309 
310 	/* Section 0 has sh_addr 0 and sh_size 0. */
311 	*num = info->sechdrs[sec].sh_size / object_size;
312 	return (void *)info->sechdrs[sec].sh_addr;
313 }
314 
315 /* Find a module section: 0 means not found. Ignores SHF_ALLOC flag. */
316 static unsigned int find_any_sec(const struct load_info *info, const char *name)
317 {
318 	unsigned int i;
319 
320 	for (i = 1; i < info->hdr->e_shnum; i++) {
321 		Elf_Shdr *shdr = &info->sechdrs[i];
322 		if (strcmp(info->secstrings + shdr->sh_name, name) == 0)
323 			return i;
324 	}
325 	return 0;
326 }
327 
328 /*
329  * Find a module section, or NULL. Fill in number of "objects" in section.
330  * Ignores SHF_ALLOC flag.
331  */
332 static __maybe_unused void *any_section_objs(const struct load_info *info,
333 					     const char *name,
334 					     size_t object_size,
335 					     unsigned int *num)
336 {
337 	unsigned int sec = find_any_sec(info, name);
338 
339 	/* Section 0 has sh_addr 0 and sh_size 0. */
340 	*num = info->sechdrs[sec].sh_size / object_size;
341 	return (void *)info->sechdrs[sec].sh_addr;
342 }
343 
344 #ifndef CONFIG_MODVERSIONS
345 #define symversion(base, idx) NULL
346 #else
347 #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
348 #endif
349 
350 static const char *kernel_symbol_name(const struct kernel_symbol *sym)
351 {
352 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
353 	return offset_to_ptr(&sym->name_offset);
354 #else
355 	return sym->name;
356 #endif
357 }
358 
359 static const char *kernel_symbol_namespace(const struct kernel_symbol *sym)
360 {
361 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
362 	if (!sym->namespace_offset)
363 		return NULL;
364 	return offset_to_ptr(&sym->namespace_offset);
365 #else
366 	return sym->namespace;
367 #endif
368 }
369 
370 int cmp_name(const void *name, const void *sym)
371 {
372 	return strcmp(name, kernel_symbol_name(sym));
373 }
374 
375 static bool find_exported_symbol_in_section(const struct symsearch *syms,
376 					    struct module *owner,
377 					    struct find_symbol_arg *fsa)
378 {
379 	struct kernel_symbol *sym;
380 	u8 sym_flags;
381 
382 	sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
383 			sizeof(struct kernel_symbol), cmp_name);
384 	if (!sym)
385 		return false;
386 
387 	sym_flags = *(syms->flagstab + (sym - syms->start));
388 	if (!fsa->gplok && (sym_flags & KSYM_FLAG_GPL_ONLY))
389 		return false;
390 
391 	fsa->owner = owner;
392 	fsa->crc = symversion(syms->crcs, sym - syms->start);
393 	fsa->sym = sym;
394 	fsa->license = (sym_flags & KSYM_FLAG_GPL_ONLY) ? GPL_ONLY : NOT_GPL_ONLY;
395 
396 	return true;
397 }
398 
399 /*
400  * Find an exported symbol and return it, along with, (optional) crc and
401  * (optional) module which owns it. Needs RCU or module_mutex.
402  */
403 bool find_symbol(struct find_symbol_arg *fsa)
404 {
405 	const struct symsearch syms = {
406 		.start		= __start___ksymtab,
407 		.stop		= __stop___ksymtab,
408 		.crcs		= __start___kcrctab,
409 		.flagstab	= __start___kflagstab,
410 	};
411 	struct module *mod;
412 
413 	if (find_exported_symbol_in_section(&syms, NULL, fsa))
414 		return true;
415 
416 	list_for_each_entry_rcu(mod, &modules, list,
417 				lockdep_is_held(&module_mutex)) {
418 		const struct symsearch syms = {
419 			.start		= mod->syms,
420 			.stop		= mod->syms + mod->num_syms,
421 			.crcs		= mod->crcs,
422 			.flagstab	= mod->flagstab,
423 		};
424 
425 		if (mod->state == MODULE_STATE_UNFORMED)
426 			continue;
427 
428 		if (find_exported_symbol_in_section(&syms, mod, fsa))
429 			return true;
430 	}
431 
432 	pr_debug("Failed to find symbol %s\n", fsa->name);
433 	return false;
434 }
435 
436 /*
437  * Search for module by name: must hold module_mutex (or RCU for read-only
438  * access).
439  */
440 struct module *find_module_all(const char *name, size_t len,
441 			       bool even_unformed)
442 {
443 	struct module *mod;
444 
445 	list_for_each_entry_rcu(mod, &modules, list,
446 				lockdep_is_held(&module_mutex)) {
447 		if (!even_unformed && mod->state == MODULE_STATE_UNFORMED)
448 			continue;
449 		if (strlen(mod->name) == len && !memcmp(mod->name, name, len))
450 			return mod;
451 	}
452 	return NULL;
453 }
454 
455 struct module *find_module(const char *name)
456 {
457 	return find_module_all(name, strlen(name), false);
458 }
459 
460 #ifdef CONFIG_SMP
461 
462 static inline void __percpu *mod_percpu(struct module *mod)
463 {
464 	return mod->percpu;
465 }
466 
467 static int percpu_modalloc(struct module *mod, struct load_info *info)
468 {
469 	Elf_Shdr *pcpusec = &info->sechdrs[info->index.pcpu];
470 	unsigned long align = pcpusec->sh_addralign;
471 
472 	if (!pcpusec->sh_size)
473 		return 0;
474 
475 	if (align > PAGE_SIZE) {
476 		pr_warn("%s: per-cpu alignment %li > %li\n",
477 			mod->name, align, PAGE_SIZE);
478 		align = PAGE_SIZE;
479 	}
480 
481 	mod->percpu = __alloc_reserved_percpu(pcpusec->sh_size, align);
482 	if (!mod->percpu) {
483 		pr_warn("%s: Could not allocate %lu bytes percpu data\n",
484 			mod->name, (unsigned long)pcpusec->sh_size);
485 		return -ENOMEM;
486 	}
487 	mod->percpu_size = pcpusec->sh_size;
488 	return 0;
489 }
490 
491 static void percpu_modfree(struct module *mod)
492 {
493 	free_percpu(mod->percpu);
494 }
495 
496 static unsigned int find_pcpusec(struct load_info *info)
497 {
498 	return find_sec(info, ".data..percpu");
499 }
500 
501 static void percpu_modcopy(struct module *mod,
502 			   const void *from, unsigned long size)
503 {
504 	int cpu;
505 
506 	for_each_possible_cpu(cpu)
507 		memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
508 }
509 
510 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
511 {
512 	struct module *mod;
513 	unsigned int cpu;
514 
515 	guard(rcu)();
516 	list_for_each_entry_rcu(mod, &modules, list) {
517 		if (mod->state == MODULE_STATE_UNFORMED)
518 			continue;
519 		if (!mod->percpu_size)
520 			continue;
521 		for_each_possible_cpu(cpu) {
522 			void *start = per_cpu_ptr(mod->percpu, cpu);
523 			void *va = (void *)addr;
524 
525 			if (va >= start && va < start + mod->percpu_size) {
526 				if (can_addr) {
527 					*can_addr = (unsigned long) (va - start);
528 					*can_addr += (unsigned long)
529 						per_cpu_ptr(mod->percpu,
530 							    get_boot_cpu_id());
531 				}
532 				return true;
533 			}
534 		}
535 	}
536 	return false;
537 }
538 
539 /**
540  * is_module_percpu_address() - test whether address is from module static percpu
541  * @addr: address to test
542  *
543  * Test whether @addr belongs to module static percpu area.
544  *
545  * Return: %true if @addr is from module static percpu area
546  */
547 bool is_module_percpu_address(unsigned long addr)
548 {
549 	return __is_module_percpu_address(addr, NULL);
550 }
551 
552 #else /* ... !CONFIG_SMP */
553 
554 static inline void __percpu *mod_percpu(struct module *mod)
555 {
556 	return NULL;
557 }
558 static int percpu_modalloc(struct module *mod, struct load_info *info)
559 {
560 	/* UP modules shouldn't have this section: ENOMEM isn't quite right */
561 	if (info->sechdrs[info->index.pcpu].sh_size != 0)
562 		return -ENOMEM;
563 	return 0;
564 }
565 static inline void percpu_modfree(struct module *mod)
566 {
567 }
568 static unsigned int find_pcpusec(struct load_info *info)
569 {
570 	return 0;
571 }
572 static inline void percpu_modcopy(struct module *mod,
573 				  const void *from, unsigned long size)
574 {
575 	/* pcpusec should be 0, and size of that section should be 0. */
576 	BUG_ON(size != 0);
577 }
578 bool is_module_percpu_address(unsigned long addr)
579 {
580 	return false;
581 }
582 
583 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
584 {
585 	return false;
586 }
587 
588 #endif /* CONFIG_SMP */
589 
590 #define MODINFO_ATTR(field)	\
591 static void setup_modinfo_##field(struct module *mod, const char *s)  \
592 {                                                                     \
593 	mod->field = kstrdup(s, GFP_KERNEL);                          \
594 }                                                                     \
595 static ssize_t show_modinfo_##field(const struct module_attribute *mattr, \
596 			struct module_kobject *mk, char *buffer)      \
597 {                                                                     \
598 	return scnprintf(buffer, PAGE_SIZE, "%s\n", mk->mod->field);  \
599 }                                                                     \
600 static int modinfo_##field##_exists(struct module *mod)               \
601 {                                                                     \
602 	return mod->field != NULL;                                    \
603 }                                                                     \
604 static void free_modinfo_##field(struct module *mod)                  \
605 {                                                                     \
606 	kfree(mod->field);                                            \
607 	mod->field = NULL;                                            \
608 }                                                                     \
609 static const struct module_attribute modinfo_##field = {              \
610 	.attr = { .name = __stringify(field), .mode = 0444 },         \
611 	.show = show_modinfo_##field,                                 \
612 	.setup = setup_modinfo_##field,                               \
613 	.test = modinfo_##field##_exists,                             \
614 	.free = free_modinfo_##field,                                 \
615 };
616 
617 MODINFO_ATTR(version);
618 MODINFO_ATTR(srcversion);
619 
620 static void setup_modinfo_import_ns(struct module *mod, const char *s)
621 {
622 	mod->imported_namespaces = NULL;
623 }
624 
625 static ssize_t show_modinfo_import_ns(const struct module_attribute *mattr,
626 				      struct module_kobject *mk, char *buffer)
627 {
628 	return sysfs_emit(buffer, "%s\n", mk->mod->imported_namespaces);
629 }
630 
631 static int modinfo_import_ns_exists(struct module *mod)
632 {
633 	return mod->imported_namespaces != NULL;
634 }
635 
636 static void free_modinfo_import_ns(struct module *mod)
637 {
638 	kfree(mod->imported_namespaces);
639 	mod->imported_namespaces = NULL;
640 }
641 
642 static const struct module_attribute modinfo_import_ns = {
643 	.attr = { .name = "import_ns", .mode = 0444 },
644 	.show = show_modinfo_import_ns,
645 	.setup = setup_modinfo_import_ns,
646 	.test = modinfo_import_ns_exists,
647 	.free = free_modinfo_import_ns,
648 };
649 
650 static struct {
651 	char name[MODULE_NAME_LEN];
652 	char taints[MODULE_FLAGS_BUF_SIZE];
653 } last_unloaded_module;
654 
655 #ifdef CONFIG_MODULE_UNLOAD
656 
657 EXPORT_TRACEPOINT_SYMBOL(module_get);
658 
659 /* MODULE_REF_BASE is the base reference count by kmodule loader. */
660 #define MODULE_REF_BASE	1
661 
662 /* Init the unload section of the module. */
663 static int module_unload_init(struct module *mod)
664 {
665 	/*
666 	 * Initialize reference counter to MODULE_REF_BASE.
667 	 * refcnt == 0 means module is going.
668 	 */
669 	atomic_set(&mod->refcnt, MODULE_REF_BASE);
670 
671 	INIT_LIST_HEAD(&mod->source_list);
672 	INIT_LIST_HEAD(&mod->target_list);
673 
674 	/* Hold reference count during initialization. */
675 	atomic_inc(&mod->refcnt);
676 
677 	return 0;
678 }
679 
680 /* Does a already use b? */
681 static int already_uses(struct module *a, struct module *b)
682 {
683 	struct module_use *use;
684 
685 	list_for_each_entry(use, &b->source_list, source_list) {
686 		if (use->source == a)
687 			return 1;
688 	}
689 	pr_debug("%s does not use %s!\n", a->name, b->name);
690 	return 0;
691 }
692 
693 /*
694  * Module a uses b
695  *  - we add 'a' as a "source", 'b' as a "target" of module use
696  *  - the module_use is added to the list of 'b' sources (so
697  *    'b' can walk the list to see who sourced them), and of 'a'
698  *    targets (so 'a' can see what modules it targets).
699  */
700 static int add_module_usage(struct module *a, struct module *b)
701 {
702 	struct module_use *use;
703 
704 	pr_debug("Allocating new usage for %s.\n", a->name);
705 	use = kmalloc_obj(*use, GFP_ATOMIC);
706 	if (!use)
707 		return -ENOMEM;
708 
709 	use->source = a;
710 	use->target = b;
711 	list_add(&use->source_list, &b->source_list);
712 	list_add(&use->target_list, &a->target_list);
713 	return 0;
714 }
715 
716 /* Module a uses b: caller needs module_mutex() */
717 static int ref_module(struct module *a, struct module *b)
718 {
719 	int err;
720 
721 	if (b == NULL || already_uses(a, b))
722 		return 0;
723 
724 	/* If module isn't available, we fail. */
725 	err = strong_try_module_get(b);
726 	if (err)
727 		return err;
728 
729 	err = add_module_usage(a, b);
730 	if (err) {
731 		module_put(b);
732 		return err;
733 	}
734 	return 0;
735 }
736 
737 /* Clear the unload stuff of the module. */
738 static void module_unload_free(struct module *mod)
739 {
740 	struct module_use *use, *tmp;
741 
742 	mutex_lock(&module_mutex);
743 	list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
744 		struct module *i = use->target;
745 		pr_debug("%s unusing %s\n", mod->name, i->name);
746 		module_put(i);
747 		list_del(&use->source_list);
748 		list_del(&use->target_list);
749 		kfree(use);
750 	}
751 	mutex_unlock(&module_mutex);
752 }
753 
754 #ifdef CONFIG_MODULE_FORCE_UNLOAD
755 static inline int try_force_unload(unsigned int flags)
756 {
757 	int ret = (flags & O_TRUNC);
758 	if (ret)
759 		add_taint(TAINT_FORCED_RMMOD, LOCKDEP_NOW_UNRELIABLE);
760 	return ret;
761 }
762 #else
763 static inline int try_force_unload(unsigned int flags)
764 {
765 	return 0;
766 }
767 #endif /* CONFIG_MODULE_FORCE_UNLOAD */
768 
769 /* Try to release refcount of module, 0 means success. */
770 static int try_release_module_ref(struct module *mod)
771 {
772 	int ret;
773 
774 	/* Try to decrement refcnt which we set at loading */
775 	ret = atomic_sub_return(MODULE_REF_BASE, &mod->refcnt);
776 	BUG_ON(ret < 0);
777 	if (ret)
778 		/* Someone can put this right now, recover with checking */
779 		ret = atomic_add_unless(&mod->refcnt, MODULE_REF_BASE, 0);
780 
781 	return ret;
782 }
783 
784 static int try_stop_module(struct module *mod, int flags, int *forced)
785 {
786 	/* If it's not unused, quit unless we're forcing. */
787 	if (try_release_module_ref(mod) != 0) {
788 		*forced = try_force_unload(flags);
789 		if (!(*forced))
790 			return -EWOULDBLOCK;
791 	}
792 
793 	/* Mark it as dying. */
794 	mod->state = MODULE_STATE_GOING;
795 
796 	return 0;
797 }
798 
799 /**
800  * module_refcount() - return the refcount or -1 if unloading
801  * @mod:	the module we're checking
802  *
803  * Return:
804  *	-1 if the module is in the process of unloading
805  *	otherwise the number of references in the kernel to the module
806  */
807 int module_refcount(struct module *mod)
808 {
809 	return atomic_read(&mod->refcnt) - MODULE_REF_BASE;
810 }
811 EXPORT_SYMBOL(module_refcount);
812 
813 /* This exists whether we can unload or not */
814 static void free_module(struct module *mod);
815 
816 SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
817 		unsigned int, flags)
818 {
819 	struct module *mod;
820 	char name[MODULE_NAME_LEN];
821 	char buf[MODULE_FLAGS_BUF_SIZE];
822 	int ret, len, forced = 0;
823 
824 	if (!capable(CAP_SYS_MODULE) || modules_disabled)
825 		return -EPERM;
826 
827 	len = strncpy_from_user(name, name_user, MODULE_NAME_LEN);
828 	if (len == 0 || len == MODULE_NAME_LEN)
829 		return -ENOENT;
830 	if (len < 0)
831 		return len;
832 
833 	audit_log_kern_module(name);
834 
835 	if (mutex_lock_interruptible(&module_mutex) != 0)
836 		return -EINTR;
837 
838 	mod = find_module(name);
839 	if (!mod) {
840 		ret = -ENOENT;
841 		goto out;
842 	}
843 
844 	if (!list_empty(&mod->source_list)) {
845 		/* Other modules depend on us: get rid of them first. */
846 		ret = -EWOULDBLOCK;
847 		goto out;
848 	}
849 
850 	/* Doing init or already dying? */
851 	if (mod->state != MODULE_STATE_LIVE) {
852 		/* FIXME: if (force), slam module count damn the torpedoes */
853 		pr_debug("%s already dying\n", mod->name);
854 		ret = -EBUSY;
855 		goto out;
856 	}
857 
858 	/* If it has an init func, it must have an exit func to unload */
859 	if (mod->init && !mod->exit) {
860 		forced = try_force_unload(flags);
861 		if (!forced) {
862 			/* This module can't be removed */
863 			ret = -EBUSY;
864 			goto out;
865 		}
866 	}
867 
868 	ret = try_stop_module(mod, flags, &forced);
869 	if (ret != 0)
870 		goto out;
871 
872 	mutex_unlock(&module_mutex);
873 	/* Final destruction now no one is using it. */
874 	if (mod->exit != NULL)
875 		mod->exit();
876 	blocking_notifier_call_chain(&module_notify_list,
877 				     MODULE_STATE_GOING, mod);
878 	klp_module_going(mod);
879 	ftrace_release_mod(mod);
880 
881 	async_synchronize_full();
882 
883 	/* Store the name and taints of the last unloaded module for diagnostic purposes */
884 	strscpy(last_unloaded_module.name, mod->name);
885 	strscpy(last_unloaded_module.taints, module_flags(mod, buf, false));
886 
887 	free_module(mod);
888 	/* someone could wait for the module in add_unformed_module() */
889 	wake_up_all(&module_wq);
890 	return 0;
891 out:
892 	mutex_unlock(&module_mutex);
893 	return ret;
894 }
895 
896 void __symbol_put(const char *symbol)
897 {
898 	struct find_symbol_arg fsa = {
899 		.name	= symbol,
900 		.gplok	= true,
901 	};
902 
903 	guard(rcu)();
904 	BUG_ON(!find_symbol(&fsa));
905 	module_put(fsa.owner);
906 }
907 EXPORT_SYMBOL(__symbol_put);
908 
909 /* Note this assumes addr is a function, which it currently always is. */
910 void symbol_put_addr(void *addr)
911 {
912 	struct module *modaddr;
913 	unsigned long a = (unsigned long)dereference_function_descriptor(addr);
914 
915 	if (core_kernel_text(a))
916 		return;
917 
918 	/*
919 	 * Even though we hold a reference on the module; we still need to
920 	 * RCU read section in order to safely traverse the data structure.
921 	 */
922 	guard(rcu)();
923 	modaddr = __module_text_address(a);
924 	BUG_ON(!modaddr);
925 	module_put(modaddr);
926 }
927 EXPORT_SYMBOL_GPL(symbol_put_addr);
928 
929 static ssize_t show_refcnt(const struct module_attribute *mattr,
930 			   struct module_kobject *mk, char *buffer)
931 {
932 	return sprintf(buffer, "%i\n", module_refcount(mk->mod));
933 }
934 
935 static const struct module_attribute modinfo_refcnt =
936 	__ATTR(refcnt, 0444, show_refcnt, NULL);
937 
938 void __module_get(struct module *module)
939 {
940 	if (module) {
941 		atomic_inc(&module->refcnt);
942 		trace_module_get(module, _RET_IP_);
943 	}
944 }
945 EXPORT_SYMBOL(__module_get);
946 
947 bool try_module_get(struct module *module)
948 {
949 	bool ret = true;
950 
951 	if (module) {
952 		/* Note: here, we can fail to get a reference */
953 		if (likely(module_is_live(module) &&
954 			   atomic_inc_not_zero(&module->refcnt) != 0))
955 			trace_module_get(module, _RET_IP_);
956 		else
957 			ret = false;
958 	}
959 	return ret;
960 }
961 EXPORT_SYMBOL(try_module_get);
962 
963 void module_put(struct module *module)
964 {
965 	int ret;
966 
967 	if (module) {
968 		ret = atomic_dec_if_positive(&module->refcnt);
969 		WARN_ON(ret < 0);	/* Failed to put refcount */
970 		trace_module_put(module, _RET_IP_);
971 	}
972 }
973 EXPORT_SYMBOL(module_put);
974 
975 #else /* !CONFIG_MODULE_UNLOAD */
976 static inline void module_unload_free(struct module *mod)
977 {
978 }
979 
980 static int ref_module(struct module *a, struct module *b)
981 {
982 	return strong_try_module_get(b);
983 }
984 
985 static inline int module_unload_init(struct module *mod)
986 {
987 	return 0;
988 }
989 #endif /* CONFIG_MODULE_UNLOAD */
990 
991 size_t module_flags_taint(unsigned long taints, char *buf)
992 {
993 	size_t l = 0;
994 	int i;
995 
996 	for (i = 0; i < TAINT_FLAGS_COUNT; i++) {
997 		if (test_bit(i, &taints))
998 			buf[l++] = taint_flags[i].c_true;
999 	}
1000 
1001 	return l;
1002 }
1003 
1004 static ssize_t show_initstate(const struct module_attribute *mattr,
1005 			      struct module_kobject *mk, char *buffer)
1006 {
1007 	const char *state = "unknown";
1008 
1009 	switch (mk->mod->state) {
1010 	case MODULE_STATE_LIVE:
1011 		state = "live";
1012 		break;
1013 	case MODULE_STATE_COMING:
1014 		state = "coming";
1015 		break;
1016 	case MODULE_STATE_GOING:
1017 		state = "going";
1018 		break;
1019 	default:
1020 		BUG();
1021 	}
1022 	return sprintf(buffer, "%s\n", state);
1023 }
1024 
1025 static const struct module_attribute modinfo_initstate =
1026 	__ATTR(initstate, 0444, show_initstate, NULL);
1027 
1028 static ssize_t store_uevent(const struct module_attribute *mattr,
1029 			    struct module_kobject *mk,
1030 			    const char *buffer, size_t count)
1031 {
1032 	int rc;
1033 
1034 	rc = kobject_synth_uevent(&mk->kobj, buffer, count);
1035 	return rc ? rc : count;
1036 }
1037 
1038 const struct module_attribute module_uevent =
1039 	__ATTR(uevent, 0200, NULL, store_uevent);
1040 
1041 static ssize_t show_coresize(const struct module_attribute *mattr,
1042 			     struct module_kobject *mk, char *buffer)
1043 {
1044 	unsigned int size = mk->mod->mem[MOD_TEXT].size;
1045 
1046 	if (!IS_ENABLED(CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC)) {
1047 		for_class_mod_mem_type(type, core_data)
1048 			size += mk->mod->mem[type].size;
1049 	}
1050 	return sprintf(buffer, "%u\n", size);
1051 }
1052 
1053 static const struct module_attribute modinfo_coresize =
1054 	__ATTR(coresize, 0444, show_coresize, NULL);
1055 
1056 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
1057 static ssize_t show_datasize(const struct module_attribute *mattr,
1058 			     struct module_kobject *mk, char *buffer)
1059 {
1060 	unsigned int size = 0;
1061 
1062 	for_class_mod_mem_type(type, core_data)
1063 		size += mk->mod->mem[type].size;
1064 	return sprintf(buffer, "%u\n", size);
1065 }
1066 
1067 static const struct module_attribute modinfo_datasize =
1068 	__ATTR(datasize, 0444, show_datasize, NULL);
1069 #endif
1070 
1071 static ssize_t show_initsize(const struct module_attribute *mattr,
1072 			     struct module_kobject *mk, char *buffer)
1073 {
1074 	unsigned int size = 0;
1075 
1076 	for_class_mod_mem_type(type, init)
1077 		size += mk->mod->mem[type].size;
1078 	return sprintf(buffer, "%u\n", size);
1079 }
1080 
1081 static const struct module_attribute modinfo_initsize =
1082 	__ATTR(initsize, 0444, show_initsize, NULL);
1083 
1084 static ssize_t show_taint(const struct module_attribute *mattr,
1085 			  struct module_kobject *mk, char *buffer)
1086 {
1087 	size_t l;
1088 
1089 	l = module_flags_taint(mk->mod->taints, buffer);
1090 	buffer[l++] = '\n';
1091 	return l;
1092 }
1093 
1094 static const struct module_attribute modinfo_taint =
1095 	__ATTR(taint, 0444, show_taint, NULL);
1096 
1097 const struct module_attribute *const modinfo_attrs[] = {
1098 	&module_uevent,
1099 	&modinfo_version,
1100 	&modinfo_srcversion,
1101 	&modinfo_import_ns,
1102 	&modinfo_initstate,
1103 	&modinfo_coresize,
1104 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
1105 	&modinfo_datasize,
1106 #endif
1107 	&modinfo_initsize,
1108 	&modinfo_taint,
1109 #ifdef CONFIG_MODULE_UNLOAD
1110 	&modinfo_refcnt,
1111 #endif
1112 	NULL,
1113 };
1114 
1115 const size_t modinfo_attrs_count = ARRAY_SIZE(modinfo_attrs);
1116 
1117 static const char vermagic[] = VERMAGIC_STRING;
1118 
1119 int try_to_force_load(struct module *mod, const char *reason)
1120 {
1121 #ifdef CONFIG_MODULE_FORCE_LOAD
1122 	if (!test_taint(TAINT_FORCED_MODULE))
1123 		pr_warn("%s: %s: kernel tainted.\n", mod->name, reason);
1124 	add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE);
1125 	return 0;
1126 #else
1127 	return -ENOEXEC;
1128 #endif
1129 }
1130 
1131 /* Parse tag=value strings from .modinfo section */
1132 char *module_next_tag_pair(char *string, unsigned long *secsize)
1133 {
1134 	/* Skip non-zero chars */
1135 	while (string[0]) {
1136 		string++;
1137 		if ((*secsize)-- <= 1)
1138 			return NULL;
1139 	}
1140 
1141 	/* Skip any zero padding. */
1142 	while (!string[0]) {
1143 		string++;
1144 		if ((*secsize)-- <= 1)
1145 			return NULL;
1146 	}
1147 	return string;
1148 }
1149 
1150 static char *get_next_modinfo(const struct load_info *info, const char *tag,
1151 			      char *prev)
1152 {
1153 	char *p;
1154 	unsigned int taglen = strlen(tag);
1155 	Elf_Shdr *infosec = &info->sechdrs[info->index.info];
1156 	unsigned long size = infosec->sh_size;
1157 
1158 	/*
1159 	 * get_modinfo() calls made before rewrite_section_headers()
1160 	 * must use sh_offset, as sh_addr isn't set!
1161 	 */
1162 	char *modinfo = (char *)info->hdr + infosec->sh_offset;
1163 
1164 	if (prev) {
1165 		size -= prev - modinfo;
1166 		modinfo = module_next_tag_pair(prev, &size);
1167 	}
1168 
1169 	for (p = modinfo; p; p = module_next_tag_pair(p, &size)) {
1170 		if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
1171 			return p + taglen + 1;
1172 	}
1173 	return NULL;
1174 }
1175 
1176 static char *get_modinfo(const struct load_info *info, const char *tag)
1177 {
1178 	return get_next_modinfo(info, tag, NULL);
1179 }
1180 
1181 /**
1182  * verify_module_namespace() - does @modname have access to this symbol's @namespace
1183  * @namespace: export symbol namespace
1184  * @modname: module name
1185  *
1186  * If @namespace is prefixed with "module:" to indicate it is a module namespace
1187  * then test if @modname matches any of the comma separated patterns.
1188  *
1189  * The patterns only support tail-glob.
1190  */
1191 static bool verify_module_namespace(const char *namespace, const char *modname)
1192 {
1193 	size_t len, modlen = strlen(modname);
1194 	const char *prefix = "module:";
1195 	const char *sep;
1196 	bool glob;
1197 
1198 	if (!strstarts(namespace, prefix))
1199 		return false;
1200 
1201 	for (namespace += strlen(prefix); *namespace; namespace = sep) {
1202 		sep = strchrnul(namespace, ',');
1203 		len = sep - namespace;
1204 
1205 		glob = false;
1206 		if (sep[-1] == '*') {
1207 			len--;
1208 			glob = true;
1209 		}
1210 
1211 		if (*sep)
1212 			sep++;
1213 
1214 		if (mod_strncmp(namespace, modname, len) == 0 && (glob || len == modlen))
1215 			return true;
1216 	}
1217 
1218 	return false;
1219 }
1220 
1221 static int verify_namespace_is_imported(const struct load_info *info,
1222 					const struct kernel_symbol *sym,
1223 					struct module *mod)
1224 {
1225 	const char *namespace;
1226 	char *imported_namespace;
1227 
1228 	namespace = kernel_symbol_namespace(sym);
1229 	if (namespace && namespace[0]) {
1230 
1231 		if (verify_module_namespace(namespace, mod->name))
1232 			return 0;
1233 
1234 		for_each_modinfo_entry(imported_namespace, info, "import_ns") {
1235 			if (strcmp(namespace, imported_namespace) == 0)
1236 				return 0;
1237 		}
1238 #ifdef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1239 		pr_warn(
1240 #else
1241 		pr_err(
1242 #endif
1243 			"%s: module uses symbol (%s) from namespace %s, but does not import it.\n",
1244 			mod->name, kernel_symbol_name(sym), namespace);
1245 #ifndef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1246 		return -EINVAL;
1247 #endif
1248 	}
1249 	return 0;
1250 }
1251 
1252 static bool inherit_taint(struct module *mod, struct module *owner, const char *name)
1253 {
1254 	if (!owner || !test_bit(TAINT_PROPRIETARY_MODULE, &owner->taints))
1255 		return true;
1256 
1257 	if (mod->using_gplonly_symbols) {
1258 		pr_err("%s: module using GPL-only symbols uses symbols %s from proprietary module %s.\n",
1259 			mod->name, name, owner->name);
1260 		return false;
1261 	}
1262 
1263 	if (!test_bit(TAINT_PROPRIETARY_MODULE, &mod->taints)) {
1264 		pr_warn("%s: module uses symbols %s from proprietary module %s, inheriting taint.\n",
1265 			mod->name, name, owner->name);
1266 		set_bit(TAINT_PROPRIETARY_MODULE, &mod->taints);
1267 	}
1268 	return true;
1269 }
1270 
1271 /* Resolve a symbol for this module.  I.e. if we find one, record usage. */
1272 static const struct kernel_symbol *resolve_symbol(struct module *mod,
1273 						  const struct load_info *info,
1274 						  const char *name,
1275 						  char ownername[])
1276 {
1277 	struct find_symbol_arg fsa = {
1278 		.name	= name,
1279 		.gplok	= !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)),
1280 		.warn	= true,
1281 	};
1282 	int err;
1283 
1284 	/*
1285 	 * The module_mutex should not be a heavily contended lock;
1286 	 * if we get the occasional sleep here, we'll go an extra iteration
1287 	 * in the wait_event_interruptible(), which is harmless.
1288 	 */
1289 	sched_annotate_sleep();
1290 	mutex_lock(&module_mutex);
1291 	if (!find_symbol(&fsa))
1292 		goto unlock;
1293 
1294 	if (fsa.license == GPL_ONLY)
1295 		mod->using_gplonly_symbols = true;
1296 
1297 	if (!inherit_taint(mod, fsa.owner, name)) {
1298 		fsa.sym = NULL;
1299 		goto getname;
1300 	}
1301 
1302 	if (!check_version(info, name, mod, fsa.crc)) {
1303 		fsa.sym = ERR_PTR(-EINVAL);
1304 		goto getname;
1305 	}
1306 
1307 	err = verify_namespace_is_imported(info, fsa.sym, mod);
1308 	if (err) {
1309 		fsa.sym = ERR_PTR(err);
1310 		goto getname;
1311 	}
1312 
1313 	err = ref_module(mod, fsa.owner);
1314 	if (err) {
1315 		fsa.sym = ERR_PTR(err);
1316 		goto getname;
1317 	}
1318 
1319 getname:
1320 	/* We must make copy under the lock if we failed to get ref. */
1321 	strscpy(ownername, module_name(fsa.owner), MODULE_NAME_LEN);
1322 unlock:
1323 	mutex_unlock(&module_mutex);
1324 	return fsa.sym;
1325 }
1326 
1327 static const struct kernel_symbol *
1328 resolve_symbol_wait(struct module *mod,
1329 		    const struct load_info *info,
1330 		    const char *name)
1331 {
1332 	const struct kernel_symbol *ksym;
1333 	char owner[MODULE_NAME_LEN];
1334 
1335 	if (wait_event_interruptible_timeout(module_wq,
1336 			!IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1337 			|| PTR_ERR(ksym) != -EBUSY,
1338 					     30 * HZ) <= 0) {
1339 		pr_warn("%s: gave up waiting for init of module %s.\n",
1340 			mod->name, owner);
1341 	}
1342 	return ksym;
1343 }
1344 
1345 void __weak module_arch_cleanup(struct module *mod)
1346 {
1347 }
1348 
1349 void __weak module_arch_freeing_init(struct module *mod)
1350 {
1351 }
1352 
1353 static int module_memory_alloc(struct module *mod, enum mod_mem_type type)
1354 {
1355 	unsigned int size = PAGE_ALIGN(mod->mem[type].size);
1356 	enum execmem_type execmem_type;
1357 	void *ptr;
1358 
1359 	mod->mem[type].size = size;
1360 
1361 	if (mod_mem_type_is_data(type))
1362 		execmem_type = EXECMEM_MODULE_DATA;
1363 	else
1364 		execmem_type = EXECMEM_MODULE_TEXT;
1365 
1366 	ptr = execmem_alloc_rw(execmem_type, size);
1367 	if (!ptr)
1368 		return -ENOMEM;
1369 
1370 	mod->mem[type].is_rox = execmem_is_rox(execmem_type);
1371 
1372 	/*
1373 	 * The pointer to these blocks of memory are stored on the module
1374 	 * structure and we keep that around so long as the module is
1375 	 * around. We only free that memory when we unload the module.
1376 	 * Just mark them as not being a leak then. The .init* ELF
1377 	 * sections *do* get freed after boot so we *could* treat them
1378 	 * slightly differently with kmemleak_ignore() and only grey
1379 	 * them out as they work as typical memory allocations which
1380 	 * *do* eventually get freed, but let's just keep things simple
1381 	 * and avoid *any* false positives.
1382 	 */
1383 	if (!mod->mem[type].is_rox)
1384 		kmemleak_not_leak(ptr);
1385 
1386 	memset(ptr, 0, size);
1387 	mod->mem[type].base = ptr;
1388 
1389 	return 0;
1390 }
1391 
1392 static void module_memory_restore_rox(struct module *mod)
1393 {
1394 	for_class_mod_mem_type(type, text) {
1395 		struct module_memory *mem = &mod->mem[type];
1396 
1397 		if (mem->is_rox)
1398 			execmem_restore_rox(mem->base, mem->size);
1399 	}
1400 }
1401 
1402 static void module_memory_free(struct module *mod, enum mod_mem_type type)
1403 {
1404 	struct module_memory *mem = &mod->mem[type];
1405 
1406 	execmem_free(mem->base);
1407 }
1408 
1409 static void free_mod_mem(struct module *mod)
1410 {
1411 	for_each_mod_mem_type(type) {
1412 		struct module_memory *mod_mem = &mod->mem[type];
1413 
1414 		if (type == MOD_DATA)
1415 			continue;
1416 
1417 		/* Free lock-classes; relies on the preceding sync_rcu(). */
1418 		lockdep_free_key_range(mod_mem->base, mod_mem->size);
1419 		if (mod_mem->size)
1420 			module_memory_free(mod, type);
1421 	}
1422 
1423 	/* MOD_DATA hosts mod, so free it at last */
1424 	lockdep_free_key_range(mod->mem[MOD_DATA].base, mod->mem[MOD_DATA].size);
1425 	module_memory_free(mod, MOD_DATA);
1426 }
1427 
1428 /* Free a module, remove from lists, etc. */
1429 static void free_module(struct module *mod)
1430 {
1431 	trace_module_free(mod);
1432 
1433 	codetag_unload_module(mod);
1434 
1435 	mod_sysfs_teardown(mod);
1436 
1437 	/*
1438 	 * We leave it in list to prevent duplicate loads, but make sure
1439 	 * that noone uses it while it's being deconstructed.
1440 	 */
1441 	mutex_lock(&module_mutex);
1442 	mod->state = MODULE_STATE_UNFORMED;
1443 	mutex_unlock(&module_mutex);
1444 
1445 	/* Arch-specific cleanup. */
1446 	module_arch_cleanup(mod);
1447 
1448 	/* Module unload stuff */
1449 	module_unload_free(mod);
1450 
1451 	/* Free any allocated parameters. */
1452 	module_destroy_params(mod->kp, mod->num_kp);
1453 
1454 	if (is_livepatch_module(mod))
1455 		free_module_elf(mod);
1456 
1457 	/* Now we can delete it from the lists */
1458 	mutex_lock(&module_mutex);
1459 	/* Unlink carefully: kallsyms could be walking list. */
1460 	list_del_rcu(&mod->list);
1461 	mod_tree_remove(mod);
1462 	/* Remove this module from bug list, this uses list_del_rcu */
1463 	module_bug_cleanup(mod);
1464 	/* Wait for RCU synchronizing before releasing mod->list and buglist. */
1465 	synchronize_rcu();
1466 	if (try_add_tainted_module(mod))
1467 		pr_err("%s: adding tainted module to the unloaded tainted modules list failed.\n",
1468 		       mod->name);
1469 	mutex_unlock(&module_mutex);
1470 
1471 	/* This may be empty, but that's OK */
1472 	module_arch_freeing_init(mod);
1473 	percpu_modfree(mod);
1474 
1475 	free_mod_mem(mod);
1476 }
1477 
1478 void *__symbol_get(const char *symbol)
1479 {
1480 	struct find_symbol_arg fsa = {
1481 		.name	= symbol,
1482 		.gplok	= true,
1483 		.warn	= true,
1484 	};
1485 
1486 	scoped_guard(rcu) {
1487 		if (!find_symbol(&fsa))
1488 			return NULL;
1489 		if (fsa.license != GPL_ONLY) {
1490 			pr_warn("failing symbol_get of non-GPLONLY symbol %s.\n",
1491 				symbol);
1492 			return NULL;
1493 		}
1494 		if (strong_try_module_get(fsa.owner))
1495 			return NULL;
1496 	}
1497 	return (void *)kernel_symbol_value(fsa.sym);
1498 }
1499 EXPORT_SYMBOL_GPL(__symbol_get);
1500 
1501 /*
1502  * Ensure that an exported symbol [global namespace] does not already exist
1503  * in the kernel or in some other module's exported symbol table.
1504  *
1505  * You must hold the module_mutex.
1506  */
1507 static int verify_exported_symbols(struct module *mod)
1508 {
1509 	const struct kernel_symbol *s;
1510 	for (s = mod->syms; s < mod->syms + mod->num_syms; s++) {
1511 		struct find_symbol_arg fsa = {
1512 			.name	= kernel_symbol_name(s),
1513 			.gplok	= true,
1514 		};
1515 		if (find_symbol(&fsa)) {
1516 			pr_err("%s: exports duplicate symbol %s (owned by %s)\n",
1517 				mod->name, kernel_symbol_name(s),
1518 				module_name(fsa.owner));
1519 			return -ENOEXEC;
1520 		}
1521 	}
1522 	return 0;
1523 }
1524 
1525 static bool ignore_undef_symbol(Elf_Half emachine, const char *name)
1526 {
1527 	/*
1528 	 * On x86, PIC code and Clang non-PIC code may have call foo@PLT. GNU as
1529 	 * before 2.37 produces an unreferenced _GLOBAL_OFFSET_TABLE_ on x86-64.
1530 	 * i386 has a similar problem but may not deserve a fix.
1531 	 *
1532 	 * If we ever have to ignore many symbols, consider refactoring the code to
1533 	 * only warn if referenced by a relocation.
1534 	 */
1535 	if (emachine == EM_386 || emachine == EM_X86_64)
1536 		return !strcmp(name, "_GLOBAL_OFFSET_TABLE_");
1537 	return false;
1538 }
1539 
1540 /* Change all symbols so that st_value encodes the pointer directly. */
1541 static int simplify_symbols(struct module *mod, const struct load_info *info)
1542 {
1543 	Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
1544 	Elf_Sym *sym = (void *)symsec->sh_addr;
1545 	unsigned long secbase;
1546 	unsigned int i;
1547 	int ret = 0;
1548 	const struct kernel_symbol *ksym;
1549 
1550 	for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
1551 		const char *name = info->strtab + sym[i].st_name;
1552 
1553 		switch (sym[i].st_shndx) {
1554 		case SHN_COMMON:
1555 			/* Ignore common symbols */
1556 			if (!strncmp(name, "__gnu_lto", 9))
1557 				break;
1558 
1559 			/*
1560 			 * We compiled with -fno-common.  These are not
1561 			 * supposed to happen.
1562 			 */
1563 			pr_debug("Common symbol: %s\n", name);
1564 			pr_warn("%s: please compile with -fno-common\n",
1565 			       mod->name);
1566 			ret = -ENOEXEC;
1567 			break;
1568 
1569 		case SHN_ABS:
1570 			/* Don't need to do anything */
1571 			pr_debug("Absolute symbol: 0x%08lx %s\n",
1572 				 (long)sym[i].st_value, name);
1573 			break;
1574 
1575 		case SHN_LIVEPATCH:
1576 			/* Livepatch symbols are resolved by livepatch */
1577 			break;
1578 
1579 		case SHN_UNDEF:
1580 			ksym = resolve_symbol_wait(mod, info, name);
1581 			/* Ok if resolved.  */
1582 			if (ksym && !IS_ERR(ksym)) {
1583 				sym[i].st_value = kernel_symbol_value(ksym);
1584 				break;
1585 			}
1586 
1587 			/* Ok if weak or ignored.  */
1588 			if (!ksym &&
1589 			    (ELF_ST_BIND(sym[i].st_info) == STB_WEAK ||
1590 			     ignore_undef_symbol(info->hdr->e_machine, name)))
1591 				break;
1592 
1593 			ret = PTR_ERR(ksym) ?: -ENOENT;
1594 			pr_warn("%s: Unknown symbol %s (err %d)\n",
1595 				mod->name, name, ret);
1596 			break;
1597 
1598 		default:
1599 			if (sym[i].st_shndx >= info->hdr->e_shnum) {
1600 				pr_err("%s: Symbol %s has an invalid section index %u (max %u)\n",
1601 				       mod->name, name, sym[i].st_shndx, info->hdr->e_shnum - 1);
1602 				ret = -ENOEXEC;
1603 				break;
1604 			}
1605 
1606 			/* Divert to percpu allocation if a percpu var. */
1607 			if (sym[i].st_shndx == info->index.pcpu)
1608 				secbase = (unsigned long)mod_percpu(mod);
1609 			else
1610 				secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
1611 			sym[i].st_value += secbase;
1612 			break;
1613 		}
1614 	}
1615 
1616 	return ret;
1617 }
1618 
1619 static int apply_relocations(struct module *mod, const struct load_info *info)
1620 {
1621 	unsigned int i;
1622 	int err = 0;
1623 
1624 	/* Now do relocations. */
1625 	for (i = 1; i < info->hdr->e_shnum; i++) {
1626 		unsigned int infosec = info->sechdrs[i].sh_info;
1627 
1628 		/* Not a valid relocation section? */
1629 		if (infosec >= info->hdr->e_shnum)
1630 			continue;
1631 
1632 		/*
1633 		 * Don't bother with non-allocated sections.
1634 		 * An exception is the percpu section, which has separate allocations
1635 		 * for individual CPUs. We relocate the percpu section in the initial
1636 		 * ELF template and subsequently copy it to the per-CPU destinations.
1637 		 */
1638 		if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC) &&
1639 		    (!infosec || infosec != info->index.pcpu))
1640 			continue;
1641 
1642 		if (info->sechdrs[i].sh_flags & SHF_RELA_LIVEPATCH)
1643 			err = klp_apply_section_relocs(mod, info->sechdrs,
1644 						       info->secstrings,
1645 						       info->strtab,
1646 						       info->index.sym, i,
1647 						       NULL);
1648 		else if (info->sechdrs[i].sh_type == SHT_REL)
1649 			err = apply_relocate(info->sechdrs, info->strtab,
1650 					     info->index.sym, i, mod);
1651 		else if (info->sechdrs[i].sh_type == SHT_RELA)
1652 			err = apply_relocate_add(info->sechdrs, info->strtab,
1653 						 info->index.sym, i, mod);
1654 		if (err < 0)
1655 			break;
1656 	}
1657 	return err;
1658 }
1659 
1660 /* Additional bytes needed by arch in front of individual sections */
1661 unsigned int __weak arch_mod_section_prepend(struct module *mod,
1662 					     unsigned int section)
1663 {
1664 	/* default implementation just returns zero */
1665 	return 0;
1666 }
1667 
1668 long module_get_offset_and_type(struct module *mod, enum mod_mem_type type,
1669 				Elf_Shdr *sechdr, unsigned int section)
1670 {
1671 	long offset;
1672 	long mask = ((unsigned long)(type) & SH_ENTSIZE_TYPE_MASK) << SH_ENTSIZE_TYPE_SHIFT;
1673 
1674 	mod->mem[type].size += arch_mod_section_prepend(mod, section);
1675 	offset = ALIGN(mod->mem[type].size, sechdr->sh_addralign ?: 1);
1676 	mod->mem[type].size = offset + sechdr->sh_size;
1677 
1678 	WARN_ON_ONCE(offset & mask);
1679 	return offset | mask;
1680 }
1681 
1682 bool module_init_layout_section(const char *sname)
1683 {
1684 #ifndef CONFIG_MODULE_UNLOAD
1685 	if (module_exit_section(sname))
1686 		return true;
1687 #endif
1688 	return module_init_section(sname);
1689 }
1690 
1691 static void __layout_sections(struct module *mod, struct load_info *info, bool is_init)
1692 {
1693 	unsigned int m, i;
1694 
1695 	/*
1696 	 * { Mask of required section header flags,
1697 	 *   Mask of excluded section header flags }
1698 	 */
1699 	static const unsigned long masks[][2] = {
1700 		{ SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
1701 		{ SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
1702 		{ SHF_RO_AFTER_INIT | SHF_ALLOC, ARCH_SHF_SMALL },
1703 		{ SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
1704 		{ ARCH_SHF_SMALL | SHF_ALLOC, 0 }
1705 	};
1706 	static const int core_m_to_mem_type[] = {
1707 		MOD_TEXT,
1708 		MOD_RODATA,
1709 		MOD_RO_AFTER_INIT,
1710 		MOD_DATA,
1711 		MOD_DATA,
1712 	};
1713 	static const int init_m_to_mem_type[] = {
1714 		MOD_INIT_TEXT,
1715 		MOD_INIT_RODATA,
1716 		MOD_INVALID,
1717 		MOD_INIT_DATA,
1718 		MOD_INIT_DATA,
1719 	};
1720 
1721 	for (m = 0; m < ARRAY_SIZE(masks); ++m) {
1722 		enum mod_mem_type type = is_init ? init_m_to_mem_type[m] : core_m_to_mem_type[m];
1723 
1724 		for (i = 0; i < info->hdr->e_shnum; ++i) {
1725 			Elf_Shdr *s = &info->sechdrs[i];
1726 			const char *sname = info->secstrings + s->sh_name;
1727 
1728 			if ((s->sh_flags & masks[m][0]) != masks[m][0]
1729 			    || (s->sh_flags & masks[m][1])
1730 			    || s->sh_entsize != ~0UL
1731 			    || is_init != module_init_layout_section(sname))
1732 				continue;
1733 
1734 			if (WARN_ON_ONCE(type == MOD_INVALID))
1735 				continue;
1736 
1737 			/*
1738 			 * Do not allocate codetag memory as we load it into
1739 			 * preallocated contiguous memory.
1740 			 */
1741 			if (codetag_needs_module_section(mod, sname, s->sh_size)) {
1742 				/*
1743 				 * s->sh_entsize won't be used but populate the
1744 				 * type field to avoid confusion.
1745 				 */
1746 				s->sh_entsize = ((unsigned long)(type) & SH_ENTSIZE_TYPE_MASK)
1747 						<< SH_ENTSIZE_TYPE_SHIFT;
1748 				continue;
1749 			}
1750 
1751 			s->sh_entsize = module_get_offset_and_type(mod, type, s, i);
1752 			pr_debug("\t%s\n", sname);
1753 		}
1754 	}
1755 }
1756 
1757 /*
1758  * Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
1759  * might -- code, read-only data, read-write data, small data.  Tally
1760  * sizes, and place the offsets into sh_entsize fields: high bit means it
1761  * belongs in init.
1762  */
1763 static void layout_sections(struct module *mod, struct load_info *info)
1764 {
1765 	unsigned int i;
1766 
1767 	for (i = 0; i < info->hdr->e_shnum; i++)
1768 		info->sechdrs[i].sh_entsize = ~0UL;
1769 
1770 	pr_debug("Core section allocation order for %s:\n", mod->name);
1771 	__layout_sections(mod, info, false);
1772 
1773 	pr_debug("Init section allocation order for %s:\n", mod->name);
1774 	__layout_sections(mod, info, true);
1775 }
1776 
1777 static void module_license_taint_check(struct module *mod, const char *license)
1778 {
1779 	if (!license)
1780 		license = "unspecified";
1781 
1782 	if (!license_is_gpl_compatible(license)) {
1783 		if (!test_taint(TAINT_PROPRIETARY_MODULE))
1784 			pr_warn("%s: module license '%s' taints kernel.\n",
1785 				mod->name, license);
1786 		add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
1787 				 LOCKDEP_NOW_UNRELIABLE);
1788 	}
1789 }
1790 
1791 static int copy_modinfo_import_ns(struct module *mod, struct load_info *info)
1792 {
1793 	char *ns;
1794 	size_t len, total_len = 0;
1795 	char *buf, *p;
1796 
1797 	for_each_modinfo_entry(ns, info, "import_ns")
1798 		total_len += strlen(ns) + 1;
1799 
1800 	if (!total_len) {
1801 		mod->imported_namespaces = NULL;
1802 		return 0;
1803 	}
1804 
1805 	buf = kmalloc(total_len, GFP_KERNEL);
1806 	if (!buf)
1807 		return -ENOMEM;
1808 
1809 	p = buf;
1810 	for_each_modinfo_entry(ns, info, "import_ns") {
1811 		len = strlen(ns);
1812 		memcpy(p, ns, len);
1813 		p += len;
1814 		*p++ = '\n';
1815 	}
1816 	/* Replace trailing newline with null terminator. */
1817 	*(p - 1) = '\0';
1818 
1819 	mod->imported_namespaces = buf;
1820 	return 0;
1821 }
1822 
1823 static int setup_modinfo(struct module *mod, struct load_info *info)
1824 {
1825 	const struct module_attribute *attr;
1826 	char *imported_namespace;
1827 	int i, err;
1828 
1829 	for (i = 0; (attr = modinfo_attrs[i]); i++) {
1830 		if (attr->setup)
1831 			attr->setup(mod, get_modinfo(info, attr->attr.name));
1832 	}
1833 
1834 	for_each_modinfo_entry(imported_namespace, info, "import_ns") {
1835 		/*
1836 		 * 'module:' prefixed namespaces are implicit, disallow
1837 		 * explicit imports.
1838 		 */
1839 		if (strstarts(imported_namespace, "module:")) {
1840 			pr_err("%s: module tries to import module namespace: %s\n",
1841 			       mod->name, imported_namespace);
1842 			return -EPERM;
1843 		}
1844 	}
1845 
1846 	err = copy_modinfo_import_ns(mod, info);
1847 	if (err)
1848 		return err;
1849 
1850 	return 0;
1851 }
1852 
1853 static void free_modinfo(struct module *mod)
1854 {
1855 	const struct module_attribute *attr;
1856 	int i;
1857 
1858 	for (i = 0; (attr = modinfo_attrs[i]); i++) {
1859 		if (attr->free)
1860 			attr->free(mod);
1861 	}
1862 }
1863 
1864 bool __weak module_init_section(const char *name)
1865 {
1866 	return strstarts(name, ".init");
1867 }
1868 
1869 bool __weak module_exit_section(const char *name)
1870 {
1871 	return strstarts(name, ".exit");
1872 }
1873 
1874 static int validate_section_offset(const struct load_info *info, Elf_Shdr *shdr)
1875 {
1876 #if defined(CONFIG_64BIT)
1877 	unsigned long long secend;
1878 #else
1879 	unsigned long secend;
1880 #endif
1881 
1882 	/*
1883 	 * Check for both overflow and offset/size being
1884 	 * too large.
1885 	 */
1886 	secend = shdr->sh_offset + shdr->sh_size;
1887 	if (secend < shdr->sh_offset || secend > info->len)
1888 		return -ENOEXEC;
1889 
1890 	return 0;
1891 }
1892 
1893 /**
1894  * elf_validity_ehdr() - Checks an ELF header for module validity
1895  * @info: Load info containing the ELF header to check
1896  *
1897  * Checks whether an ELF header could belong to a valid module. Checks:
1898  *
1899  * * ELF header is within the data the user provided
1900  * * ELF magic is present
1901  * * It is relocatable (not final linked, not core file, etc.)
1902  * * The header's machine type matches what the architecture expects.
1903  * * Optional arch-specific hook for other properties
1904  *   - module_elf_check_arch() is currently only used by PPC to check
1905  *   ELF ABI version, but may be used by others in the future.
1906  *
1907  * Return: %0 if valid, %-ENOEXEC on failure.
1908  */
1909 static int elf_validity_ehdr(const struct load_info *info)
1910 {
1911 	if (info->len < sizeof(*(info->hdr))) {
1912 		pr_err("Invalid ELF header len %lu\n", info->len);
1913 		return -ENOEXEC;
1914 	}
1915 	if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0) {
1916 		pr_err("Invalid ELF header magic: != %s\n", ELFMAG);
1917 		return -ENOEXEC;
1918 	}
1919 	if (info->hdr->e_type != ET_REL) {
1920 		pr_err("Invalid ELF header type: %u != %u\n",
1921 		       info->hdr->e_type, ET_REL);
1922 		return -ENOEXEC;
1923 	}
1924 	if (!elf_check_arch(info->hdr)) {
1925 		pr_err("Invalid architecture in ELF header: %u\n",
1926 		       info->hdr->e_machine);
1927 		return -ENOEXEC;
1928 	}
1929 	if (!module_elf_check_arch(info->hdr)) {
1930 		pr_err("Invalid module architecture in ELF header: %u\n",
1931 		       info->hdr->e_machine);
1932 		return -ENOEXEC;
1933 	}
1934 	return 0;
1935 }
1936 
1937 /**
1938  * elf_validity_cache_sechdrs() - Cache section headers if valid
1939  * @info: Load info to compute section headers from
1940  *
1941  * Checks:
1942  *
1943  * * ELF header is valid (see elf_validity_ehdr())
1944  * * Section headers are the size we expect
1945  * * Section array fits in the user provided data
1946  * * Section index 0 is NULL
1947  * * Section contents are inbounds
1948  *
1949  * Then updates @info with a &load_info->sechdrs pointer if valid.
1950  *
1951  * Return: %0 if valid, negative error code if validation failed.
1952  */
1953 static int elf_validity_cache_sechdrs(struct load_info *info)
1954 {
1955 	Elf_Shdr *sechdrs;
1956 	Elf_Shdr *shdr;
1957 	int i;
1958 	int err;
1959 
1960 	err = elf_validity_ehdr(info);
1961 	if (err < 0)
1962 		return err;
1963 
1964 	if (info->hdr->e_shentsize != sizeof(Elf_Shdr)) {
1965 		pr_err("Invalid ELF section header size\n");
1966 		return -ENOEXEC;
1967 	}
1968 
1969 	/*
1970 	 * e_shnum is 16 bits, and sizeof(Elf_Shdr) is
1971 	 * known and small. So e_shnum * sizeof(Elf_Shdr)
1972 	 * will not overflow unsigned long on any platform.
1973 	 */
1974 	if (info->hdr->e_shoff >= info->len
1975 	    || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
1976 		info->len - info->hdr->e_shoff)) {
1977 		pr_err("Invalid ELF section header overflow\n");
1978 		return -ENOEXEC;
1979 	}
1980 
1981 	sechdrs = (void *)info->hdr + info->hdr->e_shoff;
1982 
1983 	/*
1984 	 * The code assumes that section 0 has a length of zero and
1985 	 * an addr of zero, so check for it.
1986 	 */
1987 	if (sechdrs[0].sh_type != SHT_NULL
1988 	    || sechdrs[0].sh_size != 0
1989 	    || sechdrs[0].sh_addr != 0) {
1990 		pr_err("ELF Spec violation: section 0 type(%d)!=SH_NULL or non-zero len or addr\n",
1991 		       sechdrs[0].sh_type);
1992 		return -ENOEXEC;
1993 	}
1994 
1995 	/* Validate contents are inbounds */
1996 	for (i = 1; i < info->hdr->e_shnum; i++) {
1997 		shdr = &sechdrs[i];
1998 		switch (shdr->sh_type) {
1999 		case SHT_NULL:
2000 		case SHT_NOBITS:
2001 			/* No contents, offset/size don't mean anything */
2002 			continue;
2003 		default:
2004 			err = validate_section_offset(info, shdr);
2005 			if (err < 0) {
2006 				pr_err("Invalid ELF section in module (section %u type %u)\n",
2007 				       i, shdr->sh_type);
2008 				return err;
2009 			}
2010 		}
2011 	}
2012 
2013 	info->sechdrs = sechdrs;
2014 
2015 	return 0;
2016 }
2017 
2018 /**
2019  * elf_validity_cache_secstrings() - Caches section names if valid
2020  * @info: Load info to cache section names from. Must have valid sechdrs.
2021  *
2022  * Specifically checks:
2023  *
2024  * * Section name table index is inbounds of section headers
2025  * * Section name table type is SHT_STRTAB
2026  * * Section name table is not empty
2027  * * Section name table is NUL terminated
2028  * * All section name offsets are inbounds of the section
2029  *
2030  * Then updates @info with a &load_info->secstrings pointer if valid.
2031  *
2032  * Return: %0 if valid, negative error code if validation failed.
2033  */
2034 static int elf_validity_cache_secstrings(struct load_info *info)
2035 {
2036 	Elf_Shdr *strhdr, *shdr;
2037 	char *secstrings;
2038 	int i;
2039 
2040 	/*
2041 	 * Verify if the section name table index is valid.
2042 	 */
2043 	if (info->hdr->e_shstrndx == SHN_UNDEF
2044 	    || info->hdr->e_shstrndx >= info->hdr->e_shnum) {
2045 		pr_err("Invalid ELF section name index: %d || e_shstrndx (%d) >= e_shnum (%d)\n",
2046 		       info->hdr->e_shstrndx, info->hdr->e_shstrndx,
2047 		       info->hdr->e_shnum);
2048 		return -ENOEXEC;
2049 	}
2050 
2051 	strhdr = &info->sechdrs[info->hdr->e_shstrndx];
2052 
2053 	if (strhdr->sh_type != SHT_STRTAB) {
2054 		pr_err("Invalid ELF section name table type: %u\n", strhdr->sh_type);
2055 		return -ENOEXEC;
2056 	}
2057 
2058 	/*
2059 	 * The section name table must be NUL-terminated, as required
2060 	 * by the spec. This makes strcmp and pr_* calls that access
2061 	 * strings in the section safe.
2062 	 */
2063 	secstrings = (void *)info->hdr + strhdr->sh_offset;
2064 	if (strhdr->sh_size == 0) {
2065 		pr_err("empty section name table\n");
2066 		return -ENOEXEC;
2067 	}
2068 	if (secstrings[strhdr->sh_size - 1] != '\0') {
2069 		pr_err("ELF Spec violation: section name table isn't null terminated\n");
2070 		return -ENOEXEC;
2071 	}
2072 
2073 	for (i = 0; i < info->hdr->e_shnum; i++) {
2074 		shdr = &info->sechdrs[i];
2075 		/* SHT_NULL means sh_name has an undefined value */
2076 		if (shdr->sh_type == SHT_NULL)
2077 			continue;
2078 		if (shdr->sh_name >= strhdr->sh_size) {
2079 			pr_err("Invalid ELF section name in module (section %u type %u)\n",
2080 			       i, shdr->sh_type);
2081 			return -ENOEXEC;
2082 		}
2083 	}
2084 
2085 	info->secstrings = secstrings;
2086 	return 0;
2087 }
2088 
2089 /**
2090  * elf_validity_cache_index_info() - Validate and cache modinfo section
2091  * @info: Load info to populate the modinfo index on.
2092  *        Must have &load_info->sechdrs and &load_info->secstrings populated
2093  *
2094  * Checks that if there is a .modinfo section, it is unique.
2095  * Then, it caches its index in &load_info->index.info.
2096  * Finally, it tries to populate the name to improve error messages.
2097  *
2098  * Return: %0 if valid, %-ENOEXEC if multiple modinfo sections were found.
2099  */
2100 static int elf_validity_cache_index_info(struct load_info *info)
2101 {
2102 	int info_idx;
2103 
2104 	info_idx = find_any_unique_sec(info, ".modinfo");
2105 
2106 	if (info_idx == 0)
2107 		/* Early return, no .modinfo */
2108 		return 0;
2109 
2110 	if (info_idx < 0) {
2111 		pr_err("Only one .modinfo section must exist.\n");
2112 		return -ENOEXEC;
2113 	}
2114 
2115 	info->index.info = info_idx;
2116 	/* Try to find a name early so we can log errors with a module name */
2117 	info->name = get_modinfo(info, "name");
2118 
2119 	return 0;
2120 }
2121 
2122 /**
2123  * elf_validity_cache_index_mod() - Validates and caches this_module section
2124  * @info: Load info to cache this_module on.
2125  *        Must have &load_info->sechdrs and &load_info->secstrings populated
2126  *
2127  * The ".gnu.linkonce.this_module" ELF section is special. It is what modpost
2128  * uses to refer to __this_module and let's use rely on THIS_MODULE to point
2129  * to &__this_module properly. The kernel's modpost declares it on each
2130  * modules's *.mod.c file. If the struct module of the kernel changes a full
2131  * kernel rebuild is required.
2132  *
2133  * We have a few expectations for this special section, this function
2134  * validates all this for us:
2135  *
2136  * * The section has contents
2137  * * The section is unique
2138  * * We expect the kernel to always have to allocate it: SHF_ALLOC
2139  * * The section size must match the kernel's run time's struct module
2140  *   size
2141  *
2142  * If all checks pass, the index will be cached in &load_info->index.mod
2143  *
2144  * Return: %0 on validation success, %-ENOEXEC on failure
2145  */
2146 static int elf_validity_cache_index_mod(struct load_info *info)
2147 {
2148 	Elf_Shdr *shdr;
2149 	int mod_idx;
2150 
2151 	mod_idx = find_any_unique_sec(info, ".gnu.linkonce.this_module");
2152 	if (mod_idx <= 0) {
2153 		pr_err("module %s: Exactly one .gnu.linkonce.this_module section must exist.\n",
2154 		       info->name ?: "(missing .modinfo section or name field)");
2155 		return -ENOEXEC;
2156 	}
2157 
2158 	shdr = &info->sechdrs[mod_idx];
2159 
2160 	if (shdr->sh_type == SHT_NOBITS) {
2161 		pr_err("module %s: .gnu.linkonce.this_module section must have a size set\n",
2162 		       info->name ?: "(missing .modinfo section or name field)");
2163 		return -ENOEXEC;
2164 	}
2165 
2166 	if (!(shdr->sh_flags & SHF_ALLOC)) {
2167 		pr_err("module %s: .gnu.linkonce.this_module must occupy memory during process execution\n",
2168 		       info->name ?: "(missing .modinfo section or name field)");
2169 		return -ENOEXEC;
2170 	}
2171 
2172 	if (shdr->sh_size != sizeof(struct module)) {
2173 		pr_err("module %s: .gnu.linkonce.this_module section size must match the kernel's built struct module size at run time\n",
2174 		       info->name ?: "(missing .modinfo section or name field)");
2175 		return -ENOEXEC;
2176 	}
2177 
2178 	info->index.mod = mod_idx;
2179 
2180 	return 0;
2181 }
2182 
2183 /**
2184  * elf_validity_cache_index_sym() - Validate and cache symtab index
2185  * @info: Load info to cache symtab index in.
2186  *        Must have &load_info->sechdrs and &load_info->secstrings populated.
2187  *
2188  * Checks that there is exactly one symbol table, then caches its index in
2189  * &load_info->index.sym.
2190  *
2191  * Return: %0 if valid, %-ENOEXEC on failure.
2192  */
2193 static int elf_validity_cache_index_sym(struct load_info *info)
2194 {
2195 	unsigned int sym_idx;
2196 	unsigned int num_sym_secs = 0;
2197 	int i;
2198 
2199 	for (i = 1; i < info->hdr->e_shnum; i++) {
2200 		if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
2201 			num_sym_secs++;
2202 			sym_idx = i;
2203 		}
2204 	}
2205 
2206 	if (num_sym_secs != 1) {
2207 		pr_warn("%s: module has no symbols (stripped?)\n",
2208 			info->name ?: "(missing .modinfo section or name field)");
2209 		return -ENOEXEC;
2210 	}
2211 
2212 	info->index.sym = sym_idx;
2213 
2214 	return 0;
2215 }
2216 
2217 /**
2218  * elf_validity_cache_index_str() - Validate and cache strtab index
2219  * @info: Load info to cache strtab index in.
2220  *        Must have &load_info->sechdrs and &load_info->secstrings populated.
2221  *        Must have &load_info->index.sym populated.
2222  *
2223  * Looks at the symbol table's associated string table, makes sure it is
2224  * in-bounds and of type SHT_STRTAB, and caches it.
2225  *
2226  * Return: %0 if valid, %-ENOEXEC on failure.
2227  */
2228 static int elf_validity_cache_index_str(struct load_info *info)
2229 {
2230 	unsigned int str_idx = info->sechdrs[info->index.sym].sh_link;
2231 
2232 	if (str_idx == SHN_UNDEF || str_idx >= info->hdr->e_shnum) {
2233 		pr_err("Invalid ELF sh_link!=SHN_UNDEF(%d) or (sh_link(%d) >= hdr->e_shnum(%d)\n",
2234 		       str_idx, str_idx, info->hdr->e_shnum);
2235 		return -ENOEXEC;
2236 	}
2237 
2238 	if (info->sechdrs[str_idx].sh_type != SHT_STRTAB) {
2239 		pr_err("Invalid ELF symbol string table type: %u\n",
2240 		       info->sechdrs[str_idx].sh_type);
2241 		return -ENOEXEC;
2242 	}
2243 
2244 	info->index.str = str_idx;
2245 	return 0;
2246 }
2247 
2248 /**
2249  * elf_validity_cache_index_versions() - Validate and cache version indices
2250  * @info:  Load info to cache version indices in.
2251  *         Must have &load_info->sechdrs and &load_info->secstrings populated.
2252  * @flags: Load flags, relevant to suppress version loading, see
2253  *         uapi/linux/module.h
2254  *
2255  * If we're ignoring modversions based on @flags, zero all version indices
2256  * and return validity. Othewrise check:
2257  *
2258  * * If "__version_ext_crcs" is present, "__version_ext_names" is present
2259  * * There is a name present for every crc
2260  *
2261  * Then populate:
2262  *
2263  * * &load_info->index.vers
2264  * * &load_info->index.vers_ext_crc
2265  * * &load_info->index.vers_ext_names
2266  *
2267  * if present.
2268  *
2269  * Return: %0 if valid, %-ENOEXEC on failure.
2270  */
2271 static int elf_validity_cache_index_versions(struct load_info *info, int flags)
2272 {
2273 	unsigned int vers_ext_crc;
2274 	unsigned int vers_ext_name;
2275 	size_t crc_count;
2276 	size_t remaining_len;
2277 	size_t name_size;
2278 	char *name;
2279 
2280 	/* If modversions were suppressed, pretend we didn't find any */
2281 	if (flags & MODULE_INIT_IGNORE_MODVERSIONS) {
2282 		info->index.vers = 0;
2283 		info->index.vers_ext_crc = 0;
2284 		info->index.vers_ext_name = 0;
2285 		return 0;
2286 	}
2287 
2288 	vers_ext_crc = find_sec(info, "__version_ext_crcs");
2289 	vers_ext_name = find_sec(info, "__version_ext_names");
2290 
2291 	/* If we have one field, we must have the other */
2292 	if (!!vers_ext_crc != !!vers_ext_name) {
2293 		pr_err("extended version crc+name presence does not match");
2294 		return -ENOEXEC;
2295 	}
2296 
2297 	/*
2298 	 * If we have extended version information, we should have the same
2299 	 * number of entries in every section.
2300 	 */
2301 	if (vers_ext_crc) {
2302 		crc_count = info->sechdrs[vers_ext_crc].sh_size / sizeof(u32);
2303 		name = (void *)info->hdr +
2304 			info->sechdrs[vers_ext_name].sh_offset;
2305 		remaining_len = info->sechdrs[vers_ext_name].sh_size;
2306 
2307 		while (crc_count--) {
2308 			name_size = strnlen(name, remaining_len) + 1;
2309 			if (name_size > remaining_len) {
2310 				pr_err("more extended version crcs than names");
2311 				return -ENOEXEC;
2312 			}
2313 			remaining_len -= name_size;
2314 			name += name_size;
2315 		}
2316 	}
2317 
2318 	info->index.vers = find_sec(info, "__versions");
2319 	info->index.vers_ext_crc = vers_ext_crc;
2320 	info->index.vers_ext_name = vers_ext_name;
2321 	return 0;
2322 }
2323 
2324 /**
2325  * elf_validity_cache_index() - Resolve, validate, cache section indices
2326  * @info:  Load info to read from and update.
2327  *         &load_info->sechdrs and &load_info->secstrings must be populated.
2328  * @flags: Load flags, relevant to suppress version loading, see
2329  *         uapi/linux/module.h
2330  *
2331  * Populates &load_info->index, validating as it goes.
2332  * See child functions for per-field validation:
2333  *
2334  * * elf_validity_cache_index_info()
2335  * * elf_validity_cache_index_mod()
2336  * * elf_validity_cache_index_sym()
2337  * * elf_validity_cache_index_str()
2338  * * elf_validity_cache_index_versions()
2339  *
2340  * If CONFIG_SMP is enabled, load the percpu section by name with no
2341  * validation.
2342  *
2343  * Return: 0 on success, negative error code if an index failed validation.
2344  */
2345 static int elf_validity_cache_index(struct load_info *info, int flags)
2346 {
2347 	int err;
2348 
2349 	err = elf_validity_cache_index_info(info);
2350 	if (err < 0)
2351 		return err;
2352 	err = elf_validity_cache_index_mod(info);
2353 	if (err < 0)
2354 		return err;
2355 	err = elf_validity_cache_index_sym(info);
2356 	if (err < 0)
2357 		return err;
2358 	err = elf_validity_cache_index_str(info);
2359 	if (err < 0)
2360 		return err;
2361 	err = elf_validity_cache_index_versions(info, flags);
2362 	if (err < 0)
2363 		return err;
2364 
2365 	info->index.pcpu = find_pcpusec(info);
2366 
2367 	return 0;
2368 }
2369 
2370 /**
2371  * elf_validity_cache_strtab() - Validate and cache symbol string table
2372  * @info: Load info to read from and update.
2373  *        Must have &load_info->sechdrs and &load_info->secstrings populated.
2374  *        Must have &load_info->index populated.
2375  *
2376  * Checks:
2377  *
2378  * * The string table is not empty.
2379  * * The string table starts and ends with NUL (required by ELF spec).
2380  * * Every &Elf_Sym->st_name offset in the symbol table is inbounds of the
2381  *   string table.
2382  *
2383  * And caches the pointer as &load_info->strtab in @info.
2384  *
2385  * Return: 0 on success, negative error code if a check failed.
2386  */
2387 static int elf_validity_cache_strtab(struct load_info *info)
2388 {
2389 	Elf_Shdr *str_shdr = &info->sechdrs[info->index.str];
2390 	Elf_Shdr *sym_shdr = &info->sechdrs[info->index.sym];
2391 	char *strtab = (char *)info->hdr + str_shdr->sh_offset;
2392 	Elf_Sym *syms = (void *)info->hdr + sym_shdr->sh_offset;
2393 	int i;
2394 
2395 	if (str_shdr->sh_size == 0) {
2396 		pr_err("empty symbol string table\n");
2397 		return -ENOEXEC;
2398 	}
2399 	if (strtab[0] != '\0') {
2400 		pr_err("symbol string table missing leading NUL\n");
2401 		return -ENOEXEC;
2402 	}
2403 	if (strtab[str_shdr->sh_size - 1] != '\0') {
2404 		pr_err("symbol string table isn't NUL terminated\n");
2405 		return -ENOEXEC;
2406 	}
2407 
2408 	/*
2409 	 * Now that we know strtab is correctly structured, check symbol
2410 	 * starts are inbounds before they're used later.
2411 	 */
2412 	for (i = 0; i < sym_shdr->sh_size / sizeof(*syms); i++) {
2413 		if (syms[i].st_name >= str_shdr->sh_size) {
2414 			pr_err("symbol name out of bounds in string table");
2415 			return -ENOEXEC;
2416 		}
2417 	}
2418 
2419 	info->strtab = strtab;
2420 	return 0;
2421 }
2422 
2423 /*
2424  * Check userspace passed ELF module against our expectations, and cache
2425  * useful variables for further processing as we go.
2426  *
2427  * This does basic validity checks against section offsets and sizes, the
2428  * section name string table, and the indices used for it (sh_name).
2429  *
2430  * As a last step, since we're already checking the ELF sections we cache
2431  * useful variables which will be used later for our convenience:
2432  *
2433  * 	o pointers to section headers
2434  * 	o cache the modinfo symbol section
2435  * 	o cache the string symbol section
2436  * 	o cache the module section
2437  *
2438  * As a last step we set info->mod to the temporary copy of the module in
2439  * info->hdr. The final one will be allocated in move_module(). Any
2440  * modifications we make to our copy of the module will be carried over
2441  * to the final minted module.
2442  */
2443 static int elf_validity_cache_copy(struct load_info *info, int flags)
2444 {
2445 	int err;
2446 
2447 	err = elf_validity_cache_sechdrs(info);
2448 	if (err < 0)
2449 		return err;
2450 	err = elf_validity_cache_secstrings(info);
2451 	if (err < 0)
2452 		return err;
2453 	err = elf_validity_cache_index(info, flags);
2454 	if (err < 0)
2455 		return err;
2456 	err = elf_validity_cache_strtab(info);
2457 	if (err < 0)
2458 		return err;
2459 
2460 	/* This is temporary: point mod into copy of data. */
2461 	info->mod = (void *)info->hdr + info->sechdrs[info->index.mod].sh_offset;
2462 
2463 	/*
2464 	 * If we didn't load the .modinfo 'name' field earlier, fall back to
2465 	 * on-disk struct mod 'name' field.
2466 	 */
2467 	if (!info->name)
2468 		info->name = info->mod->name;
2469 
2470 	return 0;
2471 }
2472 
2473 #define COPY_CHUNK_SIZE (16*PAGE_SIZE)
2474 
2475 static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len)
2476 {
2477 	do {
2478 		unsigned long n = min(len, COPY_CHUNK_SIZE);
2479 
2480 		if (copy_from_user(dst, usrc, n) != 0)
2481 			return -EFAULT;
2482 		cond_resched();
2483 		dst += n;
2484 		usrc += n;
2485 		len -= n;
2486 	} while (len);
2487 	return 0;
2488 }
2489 
2490 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
2491 {
2492 	if (!get_modinfo(info, "livepatch"))
2493 		/* Nothing more to do */
2494 		return 0;
2495 
2496 	if (set_livepatch_module(mod))
2497 		return 0;
2498 
2499 	pr_err("%s: module is marked as livepatch module, but livepatch support is disabled",
2500 	       mod->name);
2501 	return -ENOEXEC;
2502 }
2503 
2504 static void check_modinfo_retpoline(struct module *mod, struct load_info *info)
2505 {
2506 	if (retpoline_module_ok(get_modinfo(info, "retpoline")))
2507 		return;
2508 
2509 	pr_warn("%s: loading module not compiled with retpoline compiler.\n",
2510 		mod->name);
2511 }
2512 
2513 /* Sets info->hdr and info->len. */
2514 static int copy_module_from_user(const void __user *umod, unsigned long len,
2515 				  struct load_info *info)
2516 {
2517 	int err;
2518 
2519 	info->len = len;
2520 	if (info->len < sizeof(*(info->hdr)))
2521 		return -ENOEXEC;
2522 
2523 	err = security_kernel_load_data(LOADING_MODULE, true);
2524 	if (err)
2525 		return err;
2526 
2527 	/* Suck in entire file: we'll want most of it. */
2528 	info->hdr = __vmalloc(info->len, GFP_KERNEL | __GFP_NOWARN);
2529 	if (!info->hdr)
2530 		return -ENOMEM;
2531 
2532 	if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) {
2533 		err = -EFAULT;
2534 		goto out;
2535 	}
2536 
2537 	err = security_kernel_post_load_data((char *)info->hdr, info->len,
2538 					     LOADING_MODULE, "init_module");
2539 out:
2540 	if (err)
2541 		vfree(info->hdr);
2542 
2543 	return err;
2544 }
2545 
2546 static void free_copy(struct load_info *info, int flags)
2547 {
2548 	if (flags & MODULE_INIT_COMPRESSED_FILE)
2549 		module_decompress_cleanup(info);
2550 	else
2551 		vfree(info->hdr);
2552 }
2553 
2554 static int rewrite_section_headers(struct load_info *info, int flags)
2555 {
2556 	unsigned int i;
2557 
2558 	/* This should always be true, but let's be sure. */
2559 	info->sechdrs[0].sh_addr = 0;
2560 
2561 	for (i = 1; i < info->hdr->e_shnum; i++) {
2562 		Elf_Shdr *shdr = &info->sechdrs[i];
2563 
2564 		/*
2565 		 * Mark all sections sh_addr with their address in the
2566 		 * temporary image.
2567 		 */
2568 		shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
2569 
2570 	}
2571 
2572 	/* Track but don't keep modinfo and version sections. */
2573 	info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
2574 	info->sechdrs[info->index.vers_ext_crc].sh_flags &=
2575 		~(unsigned long)SHF_ALLOC;
2576 	info->sechdrs[info->index.vers_ext_name].sh_flags &=
2577 		~(unsigned long)SHF_ALLOC;
2578 	info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
2579 
2580 	return 0;
2581 }
2582 
2583 static const char *const module_license_offenders[] = {
2584 	/* driverloader was caught wrongly pretending to be under GPL */
2585 	"driverloader",
2586 
2587 	/* lve claims to be GPL but upstream won't provide source */
2588 	"lve",
2589 };
2590 
2591 /*
2592  * These calls taint the kernel depending certain module circumstances */
2593 static void module_augment_kernel_taints(struct module *mod, struct load_info *info)
2594 {
2595 	int prev_taint = test_taint(TAINT_PROPRIETARY_MODULE);
2596 	size_t i;
2597 
2598 	if (!get_modinfo(info, "intree")) {
2599 		if (!test_taint(TAINT_OOT_MODULE))
2600 			pr_warn("%s: loading out-of-tree module taints kernel.\n",
2601 				mod->name);
2602 		add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
2603 	}
2604 
2605 	check_modinfo_retpoline(mod, info);
2606 
2607 	if (get_modinfo(info, "staging")) {
2608 		add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
2609 		pr_warn("%s: module is from the staging directory, the quality "
2610 			"is unknown, you have been warned.\n", mod->name);
2611 	}
2612 
2613 	if (is_livepatch_module(mod)) {
2614 		add_taint_module(mod, TAINT_LIVEPATCH, LOCKDEP_STILL_OK);
2615 		pr_notice_once("%s: tainting kernel with TAINT_LIVEPATCH\n",
2616 				mod->name);
2617 	}
2618 
2619 	module_license_taint_check(mod, get_modinfo(info, "license"));
2620 
2621 	if (get_modinfo(info, "test")) {
2622 		if (!test_taint(TAINT_TEST))
2623 			pr_warn("%s: loading test module taints kernel.\n",
2624 				mod->name);
2625 		add_taint_module(mod, TAINT_TEST, LOCKDEP_STILL_OK);
2626 	}
2627 #ifdef CONFIG_MODULE_SIG
2628 	mod->sig_ok = info->sig_ok;
2629 	if (!mod->sig_ok) {
2630 		pr_notice_once("%s: module verification failed: signature "
2631 			       "and/or required key missing - tainting "
2632 			       "kernel\n", mod->name);
2633 		add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
2634 	}
2635 #endif
2636 
2637 	/*
2638 	 * ndiswrapper is under GPL by itself, but loads proprietary modules.
2639 	 * Don't use add_taint_module(), as it would prevent ndiswrapper from
2640 	 * using GPL-only symbols it needs.
2641 	 */
2642 	if (strcmp(mod->name, "ndiswrapper") == 0)
2643 		add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
2644 
2645 	for (i = 0; i < ARRAY_SIZE(module_license_offenders); ++i) {
2646 		if (strcmp(mod->name, module_license_offenders[i]) == 0)
2647 			add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2648 					 LOCKDEP_NOW_UNRELIABLE);
2649 	}
2650 
2651 	if (!prev_taint && test_taint(TAINT_PROPRIETARY_MODULE))
2652 		pr_warn("%s: module license taints kernel.\n", mod->name);
2653 
2654 }
2655 
2656 static int check_modinfo(struct module *mod, struct load_info *info, int flags)
2657 {
2658 	const char *modmagic = get_modinfo(info, "vermagic");
2659 	int err;
2660 
2661 	if (flags & MODULE_INIT_IGNORE_VERMAGIC)
2662 		modmagic = NULL;
2663 
2664 	/* This is allowed: modprobe --force will invalidate it. */
2665 	if (!modmagic) {
2666 		err = try_to_force_load(mod, "bad vermagic");
2667 		if (err)
2668 			return err;
2669 	} else if (!same_magic(modmagic, vermagic, info->index.vers)) {
2670 		pr_err("%s: version magic '%s' should be '%s'\n",
2671 		       info->name, modmagic, vermagic);
2672 		return -ENOEXEC;
2673 	}
2674 
2675 	err = check_modinfo_livepatch(mod, info);
2676 	if (err)
2677 		return err;
2678 
2679 	return 0;
2680 }
2681 
2682 static int find_module_sections(struct module *mod, struct load_info *info)
2683 {
2684 	mod->kp = section_objs(info, "__param",
2685 			       sizeof(*mod->kp), &mod->num_kp);
2686 	mod->syms = section_objs(info, "__ksymtab",
2687 				 sizeof(*mod->syms), &mod->num_syms);
2688 	mod->crcs = section_addr(info, "__kcrctab");
2689 	mod->flagstab = section_addr(info, "__kflagstab");
2690 
2691 	if (section_addr(info, "__ksymtab_gpl"))
2692 		pr_warn("%s: ignoring obsolete section __ksymtab_gpl\n",
2693 			mod->name);
2694 	if (section_addr(info, "__kcrctab_gpl"))
2695 		pr_warn("%s: ignoring obsolete section __kcrctab_gpl\n",
2696 			mod->name);
2697 
2698 #ifdef CONFIG_CONSTRUCTORS
2699 	mod->ctors = section_objs(info, ".ctors",
2700 				  sizeof(*mod->ctors), &mod->num_ctors);
2701 	if (!mod->ctors)
2702 		mod->ctors = section_objs(info, ".init_array",
2703 				sizeof(*mod->ctors), &mod->num_ctors);
2704 	else if (find_sec(info, ".init_array")) {
2705 		/*
2706 		 * This shouldn't happen with same compiler and binutils
2707 		 * building all parts of the module.
2708 		 */
2709 		pr_warn("%s: has both .ctors and .init_array.\n",
2710 		       mod->name);
2711 		return -EINVAL;
2712 	}
2713 #endif
2714 
2715 	mod->noinstr_text_start = section_objs(info, ".noinstr.text", 1,
2716 						&mod->noinstr_text_size);
2717 
2718 #ifdef CONFIG_TRACEPOINTS
2719 	mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
2720 					     sizeof(*mod->tracepoints_ptrs),
2721 					     &mod->num_tracepoints);
2722 #endif
2723 #ifdef CONFIG_TREE_SRCU
2724 	mod->srcu_struct_ptrs = section_objs(info, "___srcu_struct_ptrs",
2725 					     sizeof(*mod->srcu_struct_ptrs),
2726 					     &mod->num_srcu_structs);
2727 #endif
2728 #ifdef CONFIG_BPF_EVENTS
2729 	mod->bpf_raw_events = section_objs(info, "__bpf_raw_tp_map",
2730 					   sizeof(*mod->bpf_raw_events),
2731 					   &mod->num_bpf_raw_events);
2732 #endif
2733 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
2734 	mod->btf_data = any_section_objs(info, ".BTF", 1, &mod->btf_data_size);
2735 	mod->btf_base_data = any_section_objs(info, ".BTF.base", 1,
2736 					      &mod->btf_base_data_size);
2737 #endif
2738 #if IS_ENABLED(CONFIG_DEBUG_INFO_BTF_INLINE)
2739 	mod->btf_inline_data = any_section_objs(info, ".BTF.inline", 1,
2740 						&mod->btf_inline_data_size);
2741 #endif
2742 #ifdef CONFIG_JUMP_LABEL
2743 	mod->jump_entries = section_objs(info, "__jump_table",
2744 					sizeof(*mod->jump_entries),
2745 					&mod->num_jump_entries);
2746 #endif
2747 #ifdef CONFIG_EVENT_TRACING
2748 	mod->trace_events = section_objs(info, "_ftrace_events",
2749 					 sizeof(*mod->trace_events),
2750 					 &mod->num_trace_events);
2751 	mod->trace_evals = section_objs(info, "_ftrace_eval_map",
2752 					sizeof(*mod->trace_evals),
2753 					&mod->num_trace_evals);
2754 #endif
2755 #ifdef CONFIG_TRACING
2756 	mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
2757 					 sizeof(*mod->trace_bprintk_fmt_start),
2758 					 &mod->num_trace_bprintk_fmt);
2759 #endif
2760 #ifdef CONFIG_DYNAMIC_FTRACE
2761 	/* sechdrs[0].sh_size is always zero */
2762 	mod->ftrace_callsites = section_objs(info, FTRACE_CALLSITE_SECTION,
2763 					     sizeof(*mod->ftrace_callsites),
2764 					     &mod->num_ftrace_callsites);
2765 #endif
2766 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
2767 	mod->ei_funcs = section_objs(info, "_error_injection_whitelist",
2768 					    sizeof(*mod->ei_funcs),
2769 					    &mod->num_ei_funcs);
2770 #endif
2771 #ifdef CONFIG_KPROBES
2772 	mod->kprobes_text_start = section_objs(info, ".kprobes.text", 1,
2773 						&mod->kprobes_text_size);
2774 	mod->kprobe_blacklist = section_objs(info, "_kprobe_blacklist",
2775 						sizeof(unsigned long),
2776 						&mod->num_kprobe_blacklist);
2777 #endif
2778 #ifdef CONFIG_PRINTK_INDEX
2779 	mod->printk_index_start = section_objs(info, ".printk_index",
2780 					       sizeof(*mod->printk_index_start),
2781 					       &mod->printk_index_size);
2782 #endif
2783 #ifdef CONFIG_HAVE_STATIC_CALL_INLINE
2784 	mod->static_call_sites = section_objs(info, ".static_call_sites",
2785 					      sizeof(*mod->static_call_sites),
2786 					      &mod->num_static_call_sites);
2787 #endif
2788 #if IS_ENABLED(CONFIG_KUNIT)
2789 	mod->kunit_suites = section_objs(info, ".kunit_test_suites",
2790 					      sizeof(*mod->kunit_suites),
2791 					      &mod->num_kunit_suites);
2792 	mod->kunit_init_suites = section_objs(info, ".kunit_init_test_suites",
2793 					      sizeof(*mod->kunit_init_suites),
2794 					      &mod->num_kunit_init_suites);
2795 #endif
2796 
2797 	mod->extable = section_objs(info, "__ex_table",
2798 				    sizeof(*mod->extable), &mod->num_exentries);
2799 
2800 	if (section_addr(info, "__obsparm"))
2801 		pr_warn("%s: Ignoring obsolete parameters\n", mod->name);
2802 
2803 #ifdef CONFIG_DYNAMIC_DEBUG_CORE
2804 	mod->dyndbg_info.descs = section_objs(info, "__dyndbg",
2805 					      sizeof(*mod->dyndbg_info.descs),
2806 					      &mod->dyndbg_info.num_descs);
2807 	mod->dyndbg_info.classes = section_objs(info, "__dyndbg_classes",
2808 						sizeof(*mod->dyndbg_info.classes),
2809 						&mod->dyndbg_info.num_classes);
2810 #endif
2811 
2812 	return 0;
2813 }
2814 
2815 static int move_module(struct module *mod, struct load_info *info)
2816 {
2817 	int i, ret;
2818 	enum mod_mem_type t = MOD_MEM_NUM_TYPES;
2819 	bool codetag_section_found = false;
2820 
2821 	for_each_mod_mem_type(type) {
2822 		if (!mod->mem[type].size) {
2823 			mod->mem[type].base = NULL;
2824 			continue;
2825 		}
2826 
2827 		ret = module_memory_alloc(mod, type);
2828 		if (ret) {
2829 			t = type;
2830 			goto out_err;
2831 		}
2832 	}
2833 
2834 	/* Transfer each section which specifies SHF_ALLOC */
2835 	pr_debug("Final section addresses for %s:\n", mod->name);
2836 	for (i = 0; i < info->hdr->e_shnum; i++) {
2837 		void *dest;
2838 		Elf_Shdr *shdr = &info->sechdrs[i];
2839 		const char *sname;
2840 
2841 		if (!(shdr->sh_flags & SHF_ALLOC))
2842 			continue;
2843 
2844 		sname = info->secstrings + shdr->sh_name;
2845 		/*
2846 		 * Load codetag sections separately as they might still be used
2847 		 * after module unload.
2848 		 */
2849 		if (codetag_needs_module_section(mod, sname, shdr->sh_size)) {
2850 			dest = codetag_alloc_module_section(mod, sname, shdr->sh_size,
2851 					arch_mod_section_prepend(mod, i), shdr->sh_addralign);
2852 			if (WARN_ON(!dest)) {
2853 				ret = -EINVAL;
2854 				goto out_err;
2855 			}
2856 			if (IS_ERR(dest)) {
2857 				ret = PTR_ERR(dest);
2858 				goto out_err;
2859 			}
2860 			codetag_section_found = true;
2861 		} else {
2862 			enum mod_mem_type type = shdr->sh_entsize >> SH_ENTSIZE_TYPE_SHIFT;
2863 			unsigned long offset = shdr->sh_entsize & SH_ENTSIZE_OFFSET_MASK;
2864 
2865 			dest = mod->mem[type].base + offset;
2866 		}
2867 
2868 		if (shdr->sh_type != SHT_NOBITS) {
2869 			/*
2870 			 * Our ELF checker already validated this, but let's
2871 			 * be pedantic and make the goal clearer. We actually
2872 			 * end up copying over all modifications made to the
2873 			 * userspace copy of the entire struct module.
2874 			 */
2875 			if (i == info->index.mod &&
2876 			   (WARN_ON_ONCE(shdr->sh_size != sizeof(struct module)))) {
2877 				ret = -ENOEXEC;
2878 				goto out_err;
2879 			}
2880 			memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
2881 		}
2882 		/*
2883 		 * Update the userspace copy's ELF section address to point to
2884 		 * our newly allocated memory as a pure convenience so that
2885 		 * users of info can keep taking advantage and using the newly
2886 		 * minted official memory area.
2887 		 */
2888 		shdr->sh_addr = (unsigned long)dest;
2889 		pr_debug("\t0x%lx 0x%.8lx %s\n", (long)shdr->sh_addr,
2890 			 (long)shdr->sh_size, info->secstrings + shdr->sh_name);
2891 	}
2892 
2893 	return 0;
2894 out_err:
2895 	module_memory_restore_rox(mod);
2896 	while (t--)
2897 		module_memory_free(mod, t);
2898 	if (codetag_section_found)
2899 		codetag_free_module_sections(mod);
2900 
2901 	return ret;
2902 }
2903 
2904 static int check_export_symbol_sections(struct module *mod)
2905 {
2906 	if (mod->num_syms && !mod->flagstab) {
2907 		pr_err("%s: no flags for exported symbols\n", mod->name);
2908 		return -ENOEXEC;
2909 	}
2910 #ifdef CONFIG_MODVERSIONS
2911 	if (mod->num_syms && !mod->crcs) {
2912 		return try_to_force_load(mod,
2913 					 "no versions for exported symbols");
2914 	}
2915 #endif
2916 	return 0;
2917 }
2918 
2919 static void flush_module_icache(const struct module *mod)
2920 {
2921 	/*
2922 	 * Flush the instruction cache, since we've played with text.
2923 	 * Do it before processing of module parameters, so the module
2924 	 * can provide parameter accessor functions of its own.
2925 	 */
2926 	for_each_mod_mem_type(type) {
2927 		const struct module_memory *mod_mem = &mod->mem[type];
2928 
2929 		if (mod_mem->size) {
2930 			flush_icache_range((unsigned long)mod_mem->base,
2931 					   (unsigned long)mod_mem->base + mod_mem->size);
2932 		}
2933 	}
2934 }
2935 
2936 bool __weak module_elf_check_arch(Elf_Ehdr *hdr)
2937 {
2938 	return true;
2939 }
2940 
2941 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
2942 				     Elf_Shdr *sechdrs,
2943 				     char *secstrings,
2944 				     struct module *mod)
2945 {
2946 	return 0;
2947 }
2948 
2949 /* module_blacklist is a comma-separated list of module names */
2950 static char *module_blacklist;
2951 static bool blacklisted(const char *module_name)
2952 {
2953 	const char *p;
2954 	size_t len;
2955 
2956 	if (!module_blacklist)
2957 		return false;
2958 
2959 	for (p = module_blacklist; *p; p += len) {
2960 		len = strcspn(p, ",");
2961 		if (strlen(module_name) == len && !memcmp(module_name, p, len))
2962 			return true;
2963 		if (p[len] == ',')
2964 			len++;
2965 	}
2966 	return false;
2967 }
2968 core_param(module_blacklist, module_blacklist, charp, 0400);
2969 
2970 static struct module *layout_and_allocate(struct load_info *info, int flags)
2971 {
2972 	struct module *mod;
2973 	int err;
2974 
2975 	/* Allow arches to frob section contents and sizes.  */
2976 	err = module_frob_arch_sections(info->hdr, info->sechdrs,
2977 					info->secstrings, info->mod);
2978 	if (err < 0)
2979 		return ERR_PTR(err);
2980 
2981 	err = module_enforce_rwx_sections(info->hdr, info->sechdrs,
2982 					  info->secstrings, info->mod);
2983 	if (err < 0)
2984 		return ERR_PTR(err);
2985 
2986 	/* We will do a special allocation for per-cpu sections later. */
2987 	info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
2988 
2989 	/*
2990 	 * Mark relevant sections as SHF_RO_AFTER_INIT so layout_sections() can
2991 	 * put them in the right place.
2992 	 * Note: ro_after_init sections also have SHF_{WRITE,ALLOC} set.
2993 	 */
2994 	module_mark_ro_after_init(info->hdr, info->sechdrs, info->secstrings);
2995 
2996 	/*
2997 	 * Determine total sizes, and put offsets in sh_entsize.  For now
2998 	 * this is done generically; there doesn't appear to be any
2999 	 * special cases for the architectures.
3000 	 */
3001 	layout_sections(info->mod, info);
3002 	layout_symtab(info->mod, info);
3003 
3004 	/* Allocate and move to the final place */
3005 	err = move_module(info->mod, info);
3006 	if (err)
3007 		return ERR_PTR(err);
3008 
3009 	/* Module has been copied to its final place now: return it. */
3010 	mod = (void *)info->sechdrs[info->index.mod].sh_addr;
3011 	kmemleak_load_module(mod, info);
3012 	codetag_module_replaced(info->mod, mod);
3013 
3014 	return mod;
3015 }
3016 
3017 /* mod is no longer valid after this! */
3018 static void module_deallocate(struct module *mod, struct load_info *info)
3019 {
3020 	percpu_modfree(mod);
3021 	module_arch_freeing_init(mod);
3022 	codetag_free_module_sections(mod);
3023 
3024 	free_mod_mem(mod);
3025 }
3026 
3027 int __weak module_finalize(const Elf_Ehdr *hdr,
3028 			   const Elf_Shdr *sechdrs,
3029 			   struct module *me)
3030 {
3031 	return 0;
3032 }
3033 
3034 static int post_relocation(struct module *mod, const struct load_info *info)
3035 {
3036 	/* Sort exception table now relocations are done. */
3037 	sort_extable(mod->extable, mod->extable + mod->num_exentries);
3038 
3039 	/* Copy relocated percpu area over. */
3040 	percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
3041 		       info->sechdrs[info->index.pcpu].sh_size);
3042 
3043 	/* Setup kallsyms-specific fields. */
3044 	add_kallsyms(mod, info);
3045 
3046 	/* Arch-specific module finalizing. */
3047 	return module_finalize(info->hdr, info->sechdrs, mod);
3048 }
3049 
3050 /* Call module constructors. */
3051 static void do_mod_ctors(struct module *mod)
3052 {
3053 #ifdef CONFIG_CONSTRUCTORS
3054 	unsigned long i;
3055 
3056 	for (i = 0; i < mod->num_ctors; i++)
3057 		mod->ctors[i]();
3058 #endif
3059 }
3060 
3061 /* For freeing module_init on success, in case kallsyms traversing */
3062 struct mod_initfree {
3063 	struct llist_node node;
3064 	void *init_text;
3065 	void *init_data;
3066 	void *init_rodata;
3067 };
3068 
3069 static void do_free_init(struct work_struct *w)
3070 {
3071 	struct llist_node *pos, *n, *list;
3072 	struct mod_initfree *initfree;
3073 
3074 	list = llist_del_all(&init_free_list);
3075 
3076 	synchronize_rcu();
3077 
3078 	llist_for_each_safe(pos, n, list) {
3079 		initfree = container_of(pos, struct mod_initfree, node);
3080 		execmem_free(initfree->init_text);
3081 		execmem_free(initfree->init_data);
3082 		execmem_free(initfree->init_rodata);
3083 		kfree(initfree);
3084 	}
3085 }
3086 
3087 void flush_module_init_free_work(void)
3088 {
3089 	flush_work(&init_free_wq);
3090 }
3091 
3092 #undef MODULE_PARAM_PREFIX
3093 #define MODULE_PARAM_PREFIX "module."
3094 /* Default value for module->async_probe_requested */
3095 static bool async_probe;
3096 module_param(async_probe, bool, 0644);
3097 
3098 /*
3099  * This is where the real work happens.
3100  *
3101  * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb
3102  * helper command 'lx-symbols'.
3103  */
3104 static noinline int do_init_module(struct module *mod)
3105 {
3106 	int ret = 0;
3107 	struct mod_initfree *freeinit;
3108 #if defined(CONFIG_MODULE_STATS)
3109 	unsigned int text_size = 0, total_size = 0;
3110 
3111 	for_each_mod_mem_type(type) {
3112 		const struct module_memory *mod_mem = &mod->mem[type];
3113 		if (mod_mem->size) {
3114 			total_size += mod_mem->size;
3115 			if (type == MOD_TEXT || type == MOD_INIT_TEXT)
3116 				text_size += mod_mem->size;
3117 		}
3118 	}
3119 #endif
3120 
3121 	freeinit = kmalloc_obj(*freeinit);
3122 	if (!freeinit) {
3123 		ret = -ENOMEM;
3124 		goto fail;
3125 	}
3126 	freeinit->init_text = mod->mem[MOD_INIT_TEXT].base;
3127 	freeinit->init_data = mod->mem[MOD_INIT_DATA].base;
3128 	freeinit->init_rodata = mod->mem[MOD_INIT_RODATA].base;
3129 
3130 	do_mod_ctors(mod);
3131 	/* Start the module */
3132 	if (mod->init != NULL)
3133 		ret = do_one_initcall(mod->init);
3134 	if (ret < 0) {
3135 		/*
3136 		 * -EEXIST is reserved by [f]init_module() to signal to userspace that
3137 		 * a module with this name is already loaded. Use something else if the
3138 		 * module itself is returning that.
3139 		 */
3140 		if (ret == -EEXIST)
3141 			ret = -EBUSY;
3142 
3143 		goto fail_free_freeinit;
3144 	}
3145 	if (ret > 0)
3146 		pr_warn("%s: init suspiciously returned %d, it should follow 0/-E convention\n",
3147 			mod->name, ret);
3148 
3149 	/* Now it's a first class citizen! */
3150 	mod->state = MODULE_STATE_LIVE;
3151 	blocking_notifier_call_chain(&module_notify_list,
3152 				     MODULE_STATE_LIVE, mod);
3153 
3154 	/* Delay uevent until module has finished its init routine */
3155 	kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
3156 
3157 	/*
3158 	 * We need to finish all async code before the module init sequence
3159 	 * is done. This has potential to deadlock if synchronous module
3160 	 * loading is requested from async (which is not allowed!).
3161 	 *
3162 	 * See commit 0fdff3ec6d87 ("async, kmod: warn on synchronous
3163 	 * request_module() from async workers") for more details.
3164 	 */
3165 	if (!mod->async_probe_requested)
3166 		async_synchronize_full();
3167 
3168 	ftrace_free_mem(mod, mod->mem[MOD_INIT_TEXT].base,
3169 			mod->mem[MOD_INIT_TEXT].base + mod->mem[MOD_INIT_TEXT].size);
3170 	mutex_lock(&module_mutex);
3171 	/* Drop initial reference. */
3172 	module_put(mod);
3173 	trim_init_extable(mod);
3174 #ifdef CONFIG_KALLSYMS
3175 	/* Switch to core kallsyms now init is done: kallsyms may be walking! */
3176 	rcu_assign_pointer(mod->kallsyms, &mod->core_kallsyms);
3177 #endif
3178 	ret = module_enable_rodata_ro_after_init(mod);
3179 	if (ret)
3180 		pr_warn("%s: module_enable_rodata_ro_after_init() returned %d, "
3181 			"ro_after_init data might still be writable\n",
3182 			mod->name, ret);
3183 
3184 	mod_tree_remove_init(mod);
3185 	module_arch_freeing_init(mod);
3186 	for_class_mod_mem_type(type, init) {
3187 		mod->mem[type].base = NULL;
3188 		mod->mem[type].size = 0;
3189 	}
3190 
3191 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
3192 	/* .BTF is not SHF_ALLOC and will get removed, so sanitize pointers */
3193 	mod->btf_data = NULL;
3194 	mod->btf_base_data = NULL;
3195 #endif
3196 #if IS_ENABLED(CONFIG_DEBUG_INFO_BTF_INLINE)
3197 	mod->btf_inline_data = NULL;
3198 #endif
3199 	/*
3200 	 * We want to free module_init, but be aware that kallsyms may be
3201 	 * walking this within an RCU read section. In all the failure paths, we
3202 	 * call synchronize_rcu(), but we don't want to slow down the success
3203 	 * path. execmem_free() cannot be called in an interrupt, so do the
3204 	 * work and call synchronize_rcu() in a work queue.
3205 	 *
3206 	 * Note that execmem_alloc() on most architectures creates W+X page
3207 	 * mappings which won't be cleaned up until do_free_init() runs.  Any
3208 	 * code such as mark_rodata_ro() which depends on those mappings to
3209 	 * be cleaned up needs to sync with the queued work by invoking
3210 	 * flush_module_init_free_work().
3211 	 */
3212 	if (llist_add(&freeinit->node, &init_free_list))
3213 		schedule_work(&init_free_wq);
3214 
3215 	mutex_unlock(&module_mutex);
3216 	wake_up_all(&module_wq);
3217 
3218 	mod_stat_add_long(text_size, &total_text_size);
3219 	mod_stat_add_long(total_size, &total_mod_size);
3220 
3221 	mod_stat_inc(&modcount);
3222 
3223 	return 0;
3224 
3225 fail_free_freeinit:
3226 	kfree(freeinit);
3227 fail:
3228 	/* Try to protect us from buggy refcounters. */
3229 	mod->state = MODULE_STATE_GOING;
3230 	synchronize_rcu();
3231 	module_put(mod);
3232 	blocking_notifier_call_chain(&module_notify_list,
3233 				     MODULE_STATE_GOING, mod);
3234 	klp_module_going(mod);
3235 	ftrace_release_mod(mod);
3236 	free_module(mod);
3237 	wake_up_all(&module_wq);
3238 
3239 	return ret;
3240 }
3241 
3242 static int may_init_module(void)
3243 {
3244 	if (!capable(CAP_SYS_MODULE) || modules_disabled)
3245 		return -EPERM;
3246 
3247 	return 0;
3248 }
3249 
3250 /* Is this module of this name done loading?  No locks held. */
3251 static bool finished_loading(const char *name)
3252 {
3253 	struct module *mod;
3254 	bool ret;
3255 
3256 	/*
3257 	 * The module_mutex should not be a heavily contended lock;
3258 	 * if we get the occasional sleep here, we'll go an extra iteration
3259 	 * in the wait_event_interruptible(), which is harmless.
3260 	 */
3261 	sched_annotate_sleep();
3262 	mutex_lock(&module_mutex);
3263 	mod = find_module_all(name, strlen(name), true);
3264 	ret = !mod || mod->state == MODULE_STATE_LIVE
3265 		|| mod->state == MODULE_STATE_GOING;
3266 	mutex_unlock(&module_mutex);
3267 
3268 	return ret;
3269 }
3270 
3271 /* Must be called with module_mutex held */
3272 static int module_patient_check_exists(const char *name,
3273 				       enum fail_dup_mod_reason reason)
3274 {
3275 	struct module *old;
3276 	int err = 0;
3277 
3278 	old = find_module_all(name, strlen(name), true);
3279 	if (old == NULL)
3280 		return 0;
3281 
3282 	if (old->state == MODULE_STATE_COMING ||
3283 	    old->state == MODULE_STATE_UNFORMED) {
3284 		/* Wait in case it fails to load. */
3285 		mutex_unlock(&module_mutex);
3286 		err = wait_event_interruptible(module_wq,
3287 				       finished_loading(name));
3288 		mutex_lock(&module_mutex);
3289 		if (err)
3290 			return err;
3291 
3292 		/* The module might have gone in the meantime. */
3293 		old = find_module_all(name, strlen(name), true);
3294 	}
3295 
3296 	if (try_add_failed_module(name, reason))
3297 		pr_warn("Could not add fail-tracking for module: %s\n", name);
3298 
3299 	/*
3300 	 * We are here only when the same module was being loaded. Do
3301 	 * not try to load it again right now. It prevents long delays
3302 	 * caused by serialized module load failures. It might happen
3303 	 * when more devices of the same type trigger load of
3304 	 * a particular module.
3305 	 */
3306 	if (old && old->state == MODULE_STATE_LIVE)
3307 		return -EEXIST;
3308 	return -EBUSY;
3309 }
3310 
3311 /*
3312  * We try to place it in the list now to make sure it's unique before
3313  * we dedicate too many resources.  In particular, temporary percpu
3314  * memory exhaustion.
3315  */
3316 static int add_unformed_module(struct module *mod)
3317 {
3318 	int err;
3319 
3320 	mod->state = MODULE_STATE_UNFORMED;
3321 
3322 	mutex_lock(&module_mutex);
3323 	err = module_patient_check_exists(mod->name, FAIL_DUP_MOD_LOAD);
3324 	if (err)
3325 		goto out;
3326 
3327 	mod_update_bounds(mod);
3328 	list_add_rcu(&mod->list, &modules);
3329 	mod_tree_insert(mod);
3330 	err = 0;
3331 
3332 out:
3333 	mutex_unlock(&module_mutex);
3334 	return err;
3335 }
3336 
3337 static int complete_formation(struct module *mod, struct load_info *info)
3338 {
3339 	int err;
3340 
3341 	mutex_lock(&module_mutex);
3342 
3343 	/* Find duplicate symbols (must be called under lock). */
3344 	err = verify_exported_symbols(mod);
3345 	if (err < 0)
3346 		goto out;
3347 
3348 	/* These rely on module_mutex for list integrity. */
3349 	module_bug_finalize(info->hdr, info->sechdrs, mod);
3350 	module_cfi_finalize(info->hdr, info->sechdrs, mod);
3351 
3352 	err = module_enable_rodata_ro(mod);
3353 	if (err)
3354 		goto out_strict_rwx;
3355 	err = module_enable_data_nx(mod);
3356 	if (err)
3357 		goto out_strict_rwx;
3358 	err = module_enable_text_rox(mod);
3359 	if (err)
3360 		goto out_strict_rwx;
3361 
3362 	/*
3363 	 * Mark state as coming so strong_try_module_get() ignores us,
3364 	 * but kallsyms etc. can see us.
3365 	 */
3366 	mod->state = MODULE_STATE_COMING;
3367 	mutex_unlock(&module_mutex);
3368 
3369 	return 0;
3370 
3371 out_strict_rwx:
3372 	module_bug_cleanup(mod);
3373 out:
3374 	mutex_unlock(&module_mutex);
3375 	return err;
3376 }
3377 
3378 static int prepare_coming_module(struct module *mod)
3379 {
3380 	int err;
3381 
3382 	ftrace_module_enable(mod);
3383 	err = klp_module_coming(mod);
3384 	if (err)
3385 		return err;
3386 
3387 	err = blocking_notifier_call_chain_robust(&module_notify_list,
3388 			MODULE_STATE_COMING, MODULE_STATE_GOING, mod);
3389 	err = notifier_to_errno(err);
3390 	if (err)
3391 		klp_module_going(mod);
3392 
3393 	return err;
3394 }
3395 
3396 static int unknown_module_param_cb(char *param, char *val, const char *modname,
3397 				   void *arg)
3398 {
3399 	struct module *mod = arg;
3400 	int ret;
3401 
3402 	if (strcmp(param, "async_probe") == 0) {
3403 		if (kstrtobool(val, &mod->async_probe_requested))
3404 			mod->async_probe_requested = true;
3405 		return 0;
3406 	}
3407 
3408 	/* Check for magic 'dyndbg' arg */
3409 	ret = ddebug_dyndbg_module_param_cb(param, val, modname);
3410 	if (ret != 0)
3411 		pr_warn("%s: unknown parameter '%s' ignored\n", modname, param);
3412 	return 0;
3413 }
3414 
3415 /* Module within temporary copy, this doesn't do any allocation  */
3416 static int early_mod_check(struct load_info *info, int flags)
3417 {
3418 	int err;
3419 
3420 	/*
3421 	 * Now that we know we have the correct module name, check
3422 	 * if it's blacklisted.
3423 	 */
3424 	if (blacklisted(info->name)) {
3425 		pr_err("Module %s is blacklisted\n", info->name);
3426 		return -EPERM;
3427 	}
3428 
3429 	err = rewrite_section_headers(info, flags);
3430 	if (err)
3431 		return err;
3432 
3433 	/* Check module struct version now, before we try to use module. */
3434 	if (!check_modstruct_version(info, info->mod))
3435 		return -ENOEXEC;
3436 
3437 	err = check_modinfo(info->mod, info, flags);
3438 	if (err)
3439 		return err;
3440 
3441 	mutex_lock(&module_mutex);
3442 	err = module_patient_check_exists(info->mod->name, FAIL_DUP_MOD_BECOMING);
3443 	mutex_unlock(&module_mutex);
3444 
3445 	return err;
3446 }
3447 
3448 /*
3449  * Allocate and load the module: note that size of section 0 is always
3450  * zero, and we rely on this for optional sections.
3451  */
3452 static int load_module(struct load_info *info, const char __user *uargs,
3453 		       int flags)
3454 {
3455 	struct module *mod;
3456 	bool module_allocated = false;
3457 	long err = 0;
3458 	char *args = NULL, *after_dashes;
3459 
3460 	/*
3461 	 * Do the signature check (if any) first. All that
3462 	 * the signature check needs is info->len, it does
3463 	 * not need any of the section info. That can be
3464 	 * set up later. This will minimize the chances
3465 	 * of a corrupt module causing problems before
3466 	 * we even get to the signature check.
3467 	 *
3468 	 * The check will also adjust info->len by stripping
3469 	 * off the sig length at the end of the module, making
3470 	 * checks against info->len more correct.
3471 	 */
3472 	err = module_sig_check(info, flags);
3473 	if (err)
3474 		goto free_copy;
3475 
3476 	/*
3477 	 * Do basic sanity checks against the ELF header and
3478 	 * sections. Cache useful sections and set the
3479 	 * info->mod to the userspace passed struct module.
3480 	 */
3481 	err = elf_validity_cache_copy(info, flags);
3482 	if (err)
3483 		goto free_copy;
3484 
3485 	err = early_mod_check(info, flags);
3486 	if (err)
3487 		goto free_copy;
3488 
3489 	/* Figure out module layout, and allocate all the memory. */
3490 	mod = layout_and_allocate(info, flags);
3491 	if (IS_ERR(mod)) {
3492 		err = PTR_ERR(mod);
3493 		goto free_copy;
3494 	}
3495 
3496 	module_allocated = true;
3497 
3498 	audit_log_kern_module(info->name);
3499 
3500 	/* Reserve our place in the list. */
3501 	err = add_unformed_module(mod);
3502 	if (err)
3503 		goto free_module;
3504 
3505 	/*
3506 	 * We are tainting your kernel if your module gets into
3507 	 * the modules linked list somehow.
3508 	 */
3509 	module_augment_kernel_taints(mod, info);
3510 
3511 	/* To avoid stressing percpu allocator, do this once we're unique. */
3512 	err = percpu_modalloc(mod, info);
3513 	if (err)
3514 		goto unlink_mod;
3515 
3516 	/* Now module is in final location, initialize linked lists, etc. */
3517 	err = module_unload_init(mod);
3518 	if (err)
3519 		goto unlink_mod;
3520 
3521 	init_param_lock(mod);
3522 
3523 	/*
3524 	 * Now we've got everything in the final locations, we can
3525 	 * find optional sections.
3526 	 */
3527 	err = find_module_sections(mod, info);
3528 	if (err)
3529 		goto free_unload;
3530 
3531 	err = check_export_symbol_sections(mod);
3532 	if (err)
3533 		goto free_unload;
3534 
3535 	/* Set up MODINFO_ATTR fields */
3536 	err = setup_modinfo(mod, info);
3537 	if (err)
3538 		goto free_modinfo;
3539 
3540 	/* Fix up syms, so that st_value is a pointer to location. */
3541 	err = simplify_symbols(mod, info);
3542 	if (err < 0)
3543 		goto free_modinfo;
3544 
3545 	err = apply_relocations(mod, info);
3546 	if (err < 0)
3547 		goto free_modinfo;
3548 
3549 	err = post_relocation(mod, info);
3550 	if (err < 0)
3551 		goto free_modinfo;
3552 
3553 	flush_module_icache(mod);
3554 
3555 	/* Now copy in args */
3556 	args = strndup_user(uargs, ~0UL >> 1);
3557 	if (IS_ERR(args)) {
3558 		err = PTR_ERR(args);
3559 		goto free_arch_cleanup;
3560 	}
3561 
3562 	init_build_id(mod, info);
3563 
3564 	/* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
3565 	ftrace_module_init(mod);
3566 
3567 	/* Finally it's fully formed, ready to start executing. */
3568 	err = complete_formation(mod, info);
3569 	if (err)
3570 		goto ddebug_cleanup;
3571 
3572 	err = prepare_coming_module(mod);
3573 	if (err)
3574 		goto bug_cleanup;
3575 
3576 	mod->async_probe_requested = async_probe;
3577 
3578 	/* Module is ready to execute: parsing args may do that. */
3579 	after_dashes = parse_args(mod->name, args, mod->kp, mod->num_kp,
3580 				  -32768, 32767, mod,
3581 				  unknown_module_param_cb);
3582 	if (IS_ERR(after_dashes)) {
3583 		err = PTR_ERR(after_dashes);
3584 		goto coming_cleanup;
3585 	} else if (after_dashes) {
3586 		pr_warn("%s: parameters '%s' after `--' ignored\n",
3587 		       mod->name, after_dashes);
3588 	}
3589 	kfree(args);
3590 	args = NULL;
3591 
3592 	/* Link in to sysfs. */
3593 	err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
3594 	if (err < 0)
3595 		goto coming_cleanup;
3596 
3597 	if (is_livepatch_module(mod)) {
3598 		err = copy_module_elf(mod, info);
3599 		if (err < 0)
3600 			goto sysfs_cleanup;
3601 	}
3602 
3603 	err = codetag_load_module(mod);
3604 	if (err)
3605 		goto livepatch_cleanup;
3606 
3607 	/* Get rid of temporary copy. */
3608 	free_copy(info, flags);
3609 
3610 	/* Done! */
3611 	trace_module_load(mod);
3612 
3613 	return do_init_module(mod);
3614 
3615  livepatch_cleanup:
3616 	if (is_livepatch_module(mod))
3617 		free_module_elf(mod);
3618  sysfs_cleanup:
3619 	mod_sysfs_teardown(mod);
3620  coming_cleanup:
3621 	mod->state = MODULE_STATE_GOING;
3622 	module_destroy_params(mod->kp, mod->num_kp);
3623 	blocking_notifier_call_chain(&module_notify_list,
3624 				     MODULE_STATE_GOING, mod);
3625 	klp_module_going(mod);
3626  bug_cleanup:
3627 	mod->state = MODULE_STATE_GOING;
3628 	/* module_bug_cleanup needs module_mutex protection */
3629 	mutex_lock(&module_mutex);
3630 	module_bug_cleanup(mod);
3631 	mutex_unlock(&module_mutex);
3632 
3633  ddebug_cleanup:
3634 	ftrace_release_mod(mod);
3635 	synchronize_rcu();
3636 	kfree(args);
3637  free_arch_cleanup:
3638 	module_arch_cleanup(mod);
3639  free_modinfo:
3640 	free_modinfo(mod);
3641  free_unload:
3642 	module_unload_free(mod);
3643  unlink_mod:
3644 	mutex_lock(&module_mutex);
3645 	/* Unlink carefully: kallsyms could be walking list. */
3646 	list_del_rcu(&mod->list);
3647 	mod_tree_remove(mod);
3648 	wake_up_all(&module_wq);
3649 	/* Wait for RCU-sched synchronizing before releasing mod->list. */
3650 	synchronize_rcu();
3651 	mutex_unlock(&module_mutex);
3652  free_module:
3653 	mod_stat_bump_invalid(info, flags);
3654 	module_memory_restore_rox(mod);
3655 	module_deallocate(mod, info);
3656  free_copy:
3657 	/*
3658 	 * The info->len is always set. We distinguish between
3659 	 * failures once the proper module was allocated and
3660 	 * before that.
3661 	 */
3662 	if (!module_allocated) {
3663 		audit_log_kern_module(info->name ? info->name : "?");
3664 		mod_stat_bump_becoming(info, flags);
3665 	}
3666 	free_copy(info, flags);
3667 	return err;
3668 }
3669 
3670 SYSCALL_DEFINE3(init_module, void __user *, umod,
3671 		unsigned long, len, const char __user *, uargs)
3672 {
3673 	int err;
3674 	struct load_info info = { };
3675 
3676 	err = may_init_module();
3677 	if (err)
3678 		return err;
3679 
3680 	pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
3681 	       umod, len, uargs);
3682 
3683 	err = copy_module_from_user(umod, len, &info);
3684 	if (err) {
3685 		mod_stat_inc(&failed_kreads);
3686 		mod_stat_add_long(len, &invalid_kread_bytes);
3687 		return err;
3688 	}
3689 
3690 	return load_module(&info, uargs, 0);
3691 }
3692 
3693 struct idempotent {
3694 	const void *cookie;
3695 	struct hlist_node entry;
3696 	struct completion complete;
3697 	int ret;
3698 };
3699 
3700 #define IDEM_HASH_BITS 8
3701 static struct hlist_head idem_hash[1 << IDEM_HASH_BITS];
3702 static DEFINE_SPINLOCK(idem_lock);
3703 
3704 static bool idempotent(struct idempotent *u, const void *cookie)
3705 {
3706 	int hash = hash_ptr(cookie, IDEM_HASH_BITS);
3707 	struct hlist_head *head = idem_hash + hash;
3708 	struct idempotent *existing;
3709 	bool first;
3710 
3711 	u->ret = -EINTR;
3712 	u->cookie = cookie;
3713 	init_completion(&u->complete);
3714 
3715 	spin_lock(&idem_lock);
3716 	first = true;
3717 	hlist_for_each_entry(existing, head, entry) {
3718 		if (existing->cookie != cookie)
3719 			continue;
3720 		first = false;
3721 		break;
3722 	}
3723 	hlist_add_head(&u->entry, idem_hash + hash);
3724 	spin_unlock(&idem_lock);
3725 
3726 	return !first;
3727 }
3728 
3729 /*
3730  * We were the first one with 'cookie' on the list, and we ended
3731  * up completing the operation. We now need to walk the list,
3732  * remove everybody - which includes ourselves - fill in the return
3733  * value, and then complete the operation.
3734  */
3735 static int idempotent_complete(struct idempotent *u, int ret)
3736 {
3737 	const void *cookie = u->cookie;
3738 	int hash = hash_ptr(cookie, IDEM_HASH_BITS);
3739 	struct hlist_head *head = idem_hash + hash;
3740 	struct hlist_node *next;
3741 	struct idempotent *pos;
3742 
3743 	spin_lock(&idem_lock);
3744 	hlist_for_each_entry_safe(pos, next, head, entry) {
3745 		if (pos->cookie != cookie)
3746 			continue;
3747 		hlist_del_init(&pos->entry);
3748 		pos->ret = ret;
3749 		complete(&pos->complete);
3750 	}
3751 	spin_unlock(&idem_lock);
3752 	return ret;
3753 }
3754 
3755 /*
3756  * Wait for the idempotent worker.
3757  *
3758  * If we get interrupted, we need to remove ourselves from the
3759  * the idempotent list, and the completion may still come in.
3760  *
3761  * The 'idem_lock' protects against the race, and 'idem.ret' was
3762  * initialized to -EINTR and is thus always the right return
3763  * value even if the idempotent work then completes between
3764  * the wait_for_completion and the cleanup.
3765  */
3766 static int idempotent_wait_for_completion(struct idempotent *u)
3767 {
3768 	if (wait_for_completion_interruptible(&u->complete)) {
3769 		spin_lock(&idem_lock);
3770 		if (!hlist_unhashed(&u->entry))
3771 			hlist_del(&u->entry);
3772 		spin_unlock(&idem_lock);
3773 	}
3774 	return u->ret;
3775 }
3776 
3777 static int init_module_from_file(struct file *f, const char __user * uargs, int flags)
3778 {
3779 	bool compressed = !!(flags & MODULE_INIT_COMPRESSED_FILE);
3780 	struct load_info info = { };
3781 	void *buf = NULL;
3782 	int len;
3783 	int err;
3784 
3785 	len = kernel_read_file(f, 0, &buf, INT_MAX, NULL,
3786 			       compressed ? READING_MODULE_COMPRESSED :
3787 					    READING_MODULE);
3788 	if (len < 0) {
3789 		mod_stat_inc(&failed_kreads);
3790 		return len;
3791 	}
3792 
3793 	if (compressed) {
3794 		err = module_decompress(&info, buf, len);
3795 		vfree(buf); /* compressed data is no longer needed */
3796 		if (err) {
3797 			mod_stat_inc(&failed_decompress);
3798 			mod_stat_add_long(len, &invalid_decompress_bytes);
3799 			return err;
3800 		}
3801 		err = security_kernel_post_read_file(f, (char *)info.hdr, info.len,
3802 						     READING_MODULE);
3803 		if (err) {
3804 			mod_stat_inc(&failed_kreads);
3805 			free_copy(&info, flags);
3806 			return err;
3807 		}
3808 	} else {
3809 		info.hdr = buf;
3810 		info.len = len;
3811 	}
3812 
3813 	return load_module(&info, uargs, flags);
3814 }
3815 
3816 static int idempotent_init_module(struct file *f, const char __user * uargs, int flags)
3817 {
3818 	struct idempotent idem;
3819 
3820 	if (!(f->f_mode & FMODE_READ))
3821 		return -EBADF;
3822 
3823 	/* Are we the winners of the race and get to do this? */
3824 	if (!idempotent(&idem, file_inode(f))) {
3825 		int ret = init_module_from_file(f, uargs, flags);
3826 		return idempotent_complete(&idem, ret);
3827 	}
3828 
3829 	/*
3830 	 * Somebody else won the race and is loading the module.
3831 	 */
3832 	return idempotent_wait_for_completion(&idem);
3833 }
3834 
3835 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
3836 {
3837 	int err = may_init_module();
3838 	if (err)
3839 		return err;
3840 
3841 	pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
3842 
3843 	if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
3844 		      |MODULE_INIT_IGNORE_VERMAGIC
3845 		      |MODULE_INIT_COMPRESSED_FILE))
3846 		return -EINVAL;
3847 
3848 	CLASS(fd, f)(fd);
3849 	if (fd_empty(f))
3850 		return -EBADF;
3851 	return idempotent_init_module(fd_file(f), uargs, flags);
3852 }
3853 
3854 /* Keep in sync with MODULE_FLAGS_BUF_SIZE !!! */
3855 char *module_flags(struct module *mod, char *buf, bool show_state)
3856 {
3857 	int bx = 0;
3858 
3859 	BUG_ON(mod->state == MODULE_STATE_UNFORMED);
3860 	if (!mod->taints && !show_state)
3861 		goto out;
3862 	if (mod->taints ||
3863 	    mod->state == MODULE_STATE_GOING ||
3864 	    mod->state == MODULE_STATE_COMING) {
3865 		buf[bx++] = '(';
3866 		bx += module_flags_taint(mod->taints, buf + bx);
3867 		/* Show a - for module-is-being-unloaded */
3868 		if (mod->state == MODULE_STATE_GOING && show_state)
3869 			buf[bx++] = '-';
3870 		/* Show a + for module-is-being-loaded */
3871 		if (mod->state == MODULE_STATE_COMING && show_state)
3872 			buf[bx++] = '+';
3873 		buf[bx++] = ')';
3874 	}
3875 out:
3876 	buf[bx] = '\0';
3877 
3878 	return buf;
3879 }
3880 
3881 /* Given an address, look for it in the module exception tables. */
3882 const struct exception_table_entry *search_module_extables(unsigned long addr)
3883 {
3884 	struct module *mod;
3885 
3886 	guard(rcu)();
3887 	mod = __module_address(addr);
3888 	if (!mod)
3889 		return NULL;
3890 
3891 	if (!mod->num_exentries)
3892 		return NULL;
3893 	/*
3894 	 * The address passed here belongs to a module that is currently
3895 	 * invoked (we are running inside it). Therefore its module::refcnt
3896 	 * needs already be >0 to ensure that it is not removed at this stage.
3897 	 * All other user need to invoke this function within a RCU read
3898 	 * section.
3899 	 */
3900 	return search_extable(mod->extable, mod->num_exentries, addr);
3901 }
3902 
3903 /**
3904  * is_module_address() - is this address inside a module?
3905  * @addr: the address to check.
3906  *
3907  * See is_module_text_address() if you simply want to see if the address
3908  * is code (not data).
3909  */
3910 bool is_module_address(unsigned long addr)
3911 {
3912 	guard(rcu)();
3913 	return __module_address(addr) != NULL;
3914 }
3915 
3916 /**
3917  * __module_address() - get the module which contains an address.
3918  * @addr: the address.
3919  *
3920  * Must be called within RCU read section or module mutex held so that
3921  * module doesn't get freed during this.
3922  */
3923 struct module *__module_address(unsigned long addr)
3924 {
3925 	struct module *mod;
3926 
3927 	if (addr >= mod_tree.addr_min && addr <= mod_tree.addr_max)
3928 		goto lookup;
3929 
3930 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
3931 	if (addr >= mod_tree.data_addr_min && addr <= mod_tree.data_addr_max)
3932 		goto lookup;
3933 #endif
3934 
3935 	return NULL;
3936 
3937 lookup:
3938 	mod = mod_find(addr, &mod_tree);
3939 	if (mod) {
3940 		BUG_ON(!within_module(addr, mod));
3941 		if (mod->state == MODULE_STATE_UNFORMED)
3942 			mod = NULL;
3943 	}
3944 	return mod;
3945 }
3946 
3947 /**
3948  * is_module_text_address() - is this address inside module code?
3949  * @addr: the address to check.
3950  *
3951  * See is_module_address() if you simply want to see if the address is
3952  * anywhere in a module.  See kernel_text_address() for testing if an
3953  * address corresponds to kernel or module code.
3954  */
3955 bool is_module_text_address(unsigned long addr)
3956 {
3957 	guard(rcu)();
3958 	return __module_text_address(addr) != NULL;
3959 }
3960 
3961 void module_for_each_mod(int(*func)(struct module *mod, void *data), void *data)
3962 {
3963 	struct module *mod;
3964 
3965 	guard(rcu)();
3966 	list_for_each_entry_rcu(mod, &modules, list) {
3967 		if (mod->state == MODULE_STATE_UNFORMED)
3968 			continue;
3969 		if (func(mod, data))
3970 			break;
3971 	}
3972 }
3973 
3974 /**
3975  * __module_text_address() - get the module whose code contains an address.
3976  * @addr: the address.
3977  *
3978  * Must be called within RCU read section or module mutex held so that
3979  * module doesn't get freed during this.
3980  */
3981 struct module *__module_text_address(unsigned long addr)
3982 {
3983 	struct module *mod = __module_address(addr);
3984 	if (mod) {
3985 		/* Make sure it's within the text section. */
3986 		if (!within_module_mem_type(addr, mod, MOD_TEXT) &&
3987 		    !within_module_mem_type(addr, mod, MOD_INIT_TEXT))
3988 			mod = NULL;
3989 	}
3990 	return mod;
3991 }
3992 
3993 /* Don't grab lock, we're oopsing. */
3994 void print_modules(void)
3995 {
3996 	struct module *mod;
3997 	char buf[MODULE_FLAGS_BUF_SIZE];
3998 
3999 	printk(KERN_DEFAULT "Modules linked in:");
4000 	/* Most callers should already have preempt disabled, but make sure */
4001 	guard(rcu)();
4002 	list_for_each_entry_rcu(mod, &modules, list) {
4003 		if (mod->state == MODULE_STATE_UNFORMED)
4004 			continue;
4005 		pr_cont(" %s%s", mod->name, module_flags(mod, buf, true));
4006 	}
4007 
4008 	print_unloaded_tainted_modules();
4009 	if (last_unloaded_module.name[0])
4010 		pr_cont(" [last unloaded: %s%s]", last_unloaded_module.name,
4011 			last_unloaded_module.taints);
4012 	pr_cont("\n");
4013 }
4014 
4015 #ifdef CONFIG_MODULE_DEBUGFS
4016 struct dentry *mod_debugfs_root;
4017 
4018 static int module_debugfs_init(void)
4019 {
4020 	mod_debugfs_root = debugfs_create_dir("modules", NULL);
4021 	return 0;
4022 }
4023 module_init(module_debugfs_init);
4024 #endif
4025