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