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