• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3    Copyright (C) 2002 Richard Henderson
4    Copyright (C) 2001 Rusty Russell, 2002, 2010 Rusty Russell IBM.
5 
6 */
7 #include <linux/export.h>
8 #include <linux/extable.h>
9 #include <linux/moduleloader.h>
10 #include <linux/module_signature.h>
11 #include <linux/trace_events.h>
12 #include <linux/init.h>
13 #include <linux/kallsyms.h>
14 #include <linux/file.h>
15 #include <linux/fs.h>
16 #include <linux/sysfs.h>
17 #include <linux/kernel.h>
18 #include <linux/slab.h>
19 #include <linux/vmalloc.h>
20 #include <linux/elf.h>
21 #include <linux/proc_fs.h>
22 #include <linux/security.h>
23 #include <linux/seq_file.h>
24 #include <linux/syscalls.h>
25 #include <linux/fcntl.h>
26 #include <linux/rcupdate.h>
27 #include <linux/capability.h>
28 #include <linux/cpu.h>
29 #include <linux/moduleparam.h>
30 #include <linux/errno.h>
31 #include <linux/err.h>
32 #include <linux/vermagic.h>
33 #include <linux/notifier.h>
34 #include <linux/sched.h>
35 #include <linux/device.h>
36 #include <linux/string.h>
37 #include <linux/mutex.h>
38 #include <linux/rculist.h>
39 #include <linux/uaccess.h>
40 #include <asm/cacheflush.h>
41 #include <linux/set_memory.h>
42 #include <asm/mmu_context.h>
43 #include <linux/license.h>
44 #include <asm/sections.h>
45 #include <linux/tracepoint.h>
46 #include <linux/ftrace.h>
47 #include <linux/livepatch.h>
48 #include <linux/async.h>
49 #include <linux/percpu.h>
50 #include <linux/kmemleak.h>
51 #include <linux/jump_label.h>
52 #include <linux/pfn.h>
53 #include <linux/bsearch.h>
54 #include <linux/dynamic_debug.h>
55 #include <linux/audit.h>
56 #include <uapi/linux/module.h>
57 #include "module-internal.h"
58 
59 #define CREATE_TRACE_POINTS
60 #include <trace/events/module.h>
61 
62 #ifndef ARCH_SHF_SMALL
63 #define ARCH_SHF_SMALL 0
64 #endif
65 
66 /*
67  * Modules' sections will be aligned on page boundaries
68  * to ensure complete separation of code and data, but
69  * only when CONFIG_ARCH_HAS_STRICT_MODULE_RWX=y
70  */
71 #ifdef CONFIG_ARCH_HAS_STRICT_MODULE_RWX
72 # define debug_align(X) ALIGN(X, PAGE_SIZE)
73 #else
74 # define debug_align(X) (X)
75 #endif
76 
77 /* If this is set, the section belongs in the init part of the module */
78 #define INIT_OFFSET_MASK (1UL << (BITS_PER_LONG-1))
79 
80 /*
81  * Mutex protects:
82  * 1) List of modules (also safely readable with preempt_disable),
83  * 2) module_use links,
84  * 3) module_addr_min/module_addr_max.
85  * (delete and add uses RCU list operations). */
86 DEFINE_MUTEX(module_mutex);
87 EXPORT_SYMBOL_GPL(module_mutex);
88 static LIST_HEAD(modules);
89 
90 /* Work queue for freeing init sections in success case */
91 static void do_free_init(struct work_struct *w);
92 static DECLARE_WORK(init_free_wq, do_free_init);
93 static LLIST_HEAD(init_free_list);
94 
95 #ifdef CONFIG_MODULES_TREE_LOOKUP
96 
97 /*
98  * Use a latched RB-tree for __module_address(); this allows us to use
99  * RCU-sched lookups of the address from any context.
100  *
101  * This is conditional on PERF_EVENTS || TRACING because those can really hit
102  * __module_address() hard by doing a lot of stack unwinding; potentially from
103  * NMI context.
104  */
105 
__mod_tree_val(struct latch_tree_node * n)106 static __always_inline unsigned long __mod_tree_val(struct latch_tree_node *n)
107 {
108 	struct module_layout *layout = container_of(n, struct module_layout, mtn.node);
109 
110 	return (unsigned long)layout->base;
111 }
112 
__mod_tree_size(struct latch_tree_node * n)113 static __always_inline unsigned long __mod_tree_size(struct latch_tree_node *n)
114 {
115 	struct module_layout *layout = container_of(n, struct module_layout, mtn.node);
116 
117 	return (unsigned long)layout->size;
118 }
119 
120 static __always_inline bool
mod_tree_less(struct latch_tree_node * a,struct latch_tree_node * b)121 mod_tree_less(struct latch_tree_node *a, struct latch_tree_node *b)
122 {
123 	return __mod_tree_val(a) < __mod_tree_val(b);
124 }
125 
126 static __always_inline int
mod_tree_comp(void * key,struct latch_tree_node * n)127 mod_tree_comp(void *key, struct latch_tree_node *n)
128 {
129 	unsigned long val = (unsigned long)key;
130 	unsigned long start, end;
131 
132 	start = __mod_tree_val(n);
133 	if (val < start)
134 		return -1;
135 
136 	end = start + __mod_tree_size(n);
137 	if (val >= end)
138 		return 1;
139 
140 	return 0;
141 }
142 
143 static const struct latch_tree_ops mod_tree_ops = {
144 	.less = mod_tree_less,
145 	.comp = mod_tree_comp,
146 };
147 
148 static struct mod_tree_root {
149 	struct latch_tree_root root;
150 	unsigned long addr_min;
151 	unsigned long addr_max;
152 } mod_tree __cacheline_aligned = {
153 	.addr_min = -1UL,
154 };
155 
156 #define module_addr_min mod_tree.addr_min
157 #define module_addr_max mod_tree.addr_max
158 
__mod_tree_insert(struct mod_tree_node * node)159 static noinline void __mod_tree_insert(struct mod_tree_node *node)
160 {
161 	latch_tree_insert(&node->node, &mod_tree.root, &mod_tree_ops);
162 }
163 
__mod_tree_remove(struct mod_tree_node * node)164 static void __mod_tree_remove(struct mod_tree_node *node)
165 {
166 	latch_tree_erase(&node->node, &mod_tree.root, &mod_tree_ops);
167 }
168 
169 /*
170  * These modifications: insert, remove_init and remove; are serialized by the
171  * module_mutex.
172  */
mod_tree_insert(struct module * mod)173 static void mod_tree_insert(struct module *mod)
174 {
175 	mod->core_layout.mtn.mod = mod;
176 	mod->init_layout.mtn.mod = mod;
177 
178 	__mod_tree_insert(&mod->core_layout.mtn);
179 	if (mod->init_layout.size)
180 		__mod_tree_insert(&mod->init_layout.mtn);
181 }
182 
mod_tree_remove_init(struct module * mod)183 static void mod_tree_remove_init(struct module *mod)
184 {
185 	if (mod->init_layout.size)
186 		__mod_tree_remove(&mod->init_layout.mtn);
187 }
188 
mod_tree_remove(struct module * mod)189 static void mod_tree_remove(struct module *mod)
190 {
191 	__mod_tree_remove(&mod->core_layout.mtn);
192 	mod_tree_remove_init(mod);
193 }
194 
mod_find(unsigned long addr)195 static struct module *mod_find(unsigned long addr)
196 {
197 	struct latch_tree_node *ltn;
198 
199 	ltn = latch_tree_find((void *)addr, &mod_tree.root, &mod_tree_ops);
200 	if (!ltn)
201 		return NULL;
202 
203 	return container_of(ltn, struct mod_tree_node, node)->mod;
204 }
205 
206 #else /* MODULES_TREE_LOOKUP */
207 
208 static unsigned long module_addr_min = -1UL, module_addr_max = 0;
209 
mod_tree_insert(struct module * mod)210 static void mod_tree_insert(struct module *mod) { }
mod_tree_remove_init(struct module * mod)211 static void mod_tree_remove_init(struct module *mod) { }
mod_tree_remove(struct module * mod)212 static void mod_tree_remove(struct module *mod) { }
213 
mod_find(unsigned long addr)214 static struct module *mod_find(unsigned long addr)
215 {
216 	struct module *mod;
217 
218 	list_for_each_entry_rcu(mod, &modules, list,
219 				lockdep_is_held(&module_mutex)) {
220 		if (within_module(addr, mod))
221 			return mod;
222 	}
223 
224 	return NULL;
225 }
226 
227 #endif /* MODULES_TREE_LOOKUP */
228 
229 /*
230  * Bounds of module text, for speeding up __module_address.
231  * Protected by module_mutex.
232  */
__mod_update_bounds(void * base,unsigned int size)233 static void __mod_update_bounds(void *base, unsigned int size)
234 {
235 	unsigned long min = (unsigned long)base;
236 	unsigned long max = min + size;
237 
238 	if (min < module_addr_min)
239 		module_addr_min = min;
240 	if (max > module_addr_max)
241 		module_addr_max = max;
242 }
243 
mod_update_bounds(struct module * mod)244 static void mod_update_bounds(struct module *mod)
245 {
246 	__mod_update_bounds(mod->core_layout.base, mod->core_layout.size);
247 	if (mod->init_layout.size)
248 		__mod_update_bounds(mod->init_layout.base, mod->init_layout.size);
249 }
250 
251 #ifdef CONFIG_KGDB_KDB
252 struct list_head *kdb_modules = &modules; /* kdb needs the list of modules */
253 #endif /* CONFIG_KGDB_KDB */
254 
module_assert_mutex(void)255 static void module_assert_mutex(void)
256 {
257 	lockdep_assert_held(&module_mutex);
258 }
259 
module_assert_mutex_or_preempt(void)260 static void module_assert_mutex_or_preempt(void)
261 {
262 #ifdef CONFIG_LOCKDEP
263 	if (unlikely(!debug_locks))
264 		return;
265 
266 	WARN_ON_ONCE(!rcu_read_lock_sched_held() &&
267 		!lockdep_is_held(&module_mutex));
268 #endif
269 }
270 
271 #ifdef CONFIG_MODULE_SIG
272 static bool sig_enforce = IS_ENABLED(CONFIG_MODULE_SIG_FORCE);
273 module_param(sig_enforce, bool_enable_only, 0644);
274 
set_module_sig_enforced(void)275 void set_module_sig_enforced(void)
276 {
277 	sig_enforce = true;
278 }
279 #else
280 #define sig_enforce false
281 #endif
282 
283 /*
284  * Export sig_enforce kernel cmdline parameter to allow other subsystems rely
285  * on that instead of directly to CONFIG_MODULE_SIG_FORCE config.
286  */
is_module_sig_enforced(void)287 bool is_module_sig_enforced(void)
288 {
289 	return sig_enforce;
290 }
291 EXPORT_SYMBOL(is_module_sig_enforced);
292 
293 /* Block module loading/unloading? */
294 int modules_disabled = 0;
295 core_param(nomodule, modules_disabled, bint, 0);
296 
297 /* Waiting for a module to finish initializing? */
298 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
299 
300 static BLOCKING_NOTIFIER_HEAD(module_notify_list);
301 
register_module_notifier(struct notifier_block * nb)302 int register_module_notifier(struct notifier_block *nb)
303 {
304 	return blocking_notifier_chain_register(&module_notify_list, nb);
305 }
306 EXPORT_SYMBOL(register_module_notifier);
307 
unregister_module_notifier(struct notifier_block * nb)308 int unregister_module_notifier(struct notifier_block *nb)
309 {
310 	return blocking_notifier_chain_unregister(&module_notify_list, nb);
311 }
312 EXPORT_SYMBOL(unregister_module_notifier);
313 
314 /*
315  * We require a truly strong try_module_get(): 0 means success.
316  * Otherwise an error is returned due to ongoing or failed
317  * initialization etc.
318  */
strong_try_module_get(struct module * mod)319 static inline int strong_try_module_get(struct module *mod)
320 {
321 	BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED);
322 	if (mod && mod->state == MODULE_STATE_COMING)
323 		return -EBUSY;
324 	if (try_module_get(mod))
325 		return 0;
326 	else
327 		return -ENOENT;
328 }
329 
add_taint_module(struct module * mod,unsigned flag,enum lockdep_ok lockdep_ok)330 static inline void add_taint_module(struct module *mod, unsigned flag,
331 				    enum lockdep_ok lockdep_ok)
332 {
333 	add_taint(flag, lockdep_ok);
334 	set_bit(flag, &mod->taints);
335 }
336 
337 /*
338  * A thread that wants to hold a reference to a module only while it
339  * is running can call this to safely exit.  nfsd and lockd use this.
340  */
__module_put_and_exit(struct module * mod,long code)341 void __noreturn __module_put_and_exit(struct module *mod, long code)
342 {
343 	module_put(mod);
344 	do_exit(code);
345 }
346 EXPORT_SYMBOL(__module_put_and_exit);
347 
348 /* Find a module section: 0 means not found. */
find_sec(const struct load_info * info,const char * name)349 static unsigned int find_sec(const struct load_info *info, const char *name)
350 {
351 	unsigned int i;
352 
353 	for (i = 1; i < info->hdr->e_shnum; i++) {
354 		Elf_Shdr *shdr = &info->sechdrs[i];
355 		/* Alloc bit cleared means "ignore it." */
356 		if ((shdr->sh_flags & SHF_ALLOC)
357 		    && strcmp(info->secstrings + shdr->sh_name, name) == 0)
358 			return i;
359 	}
360 	return 0;
361 }
362 
363 /* Find a module section, or NULL. */
section_addr(const struct load_info * info,const char * name)364 static void *section_addr(const struct load_info *info, const char *name)
365 {
366 	/* Section 0 has sh_addr 0. */
367 	return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
368 }
369 
370 /* Find a module section, or NULL.  Fill in number of "objects" in section. */
section_objs(const struct load_info * info,const char * name,size_t object_size,unsigned int * num)371 static void *section_objs(const struct load_info *info,
372 			  const char *name,
373 			  size_t object_size,
374 			  unsigned int *num)
375 {
376 	unsigned int sec = find_sec(info, name);
377 
378 	/* Section 0 has sh_addr 0 and sh_size 0. */
379 	*num = info->sechdrs[sec].sh_size / object_size;
380 	return (void *)info->sechdrs[sec].sh_addr;
381 }
382 
383 /* Provided by the linker */
384 extern const struct kernel_symbol __start___ksymtab[];
385 extern const struct kernel_symbol __stop___ksymtab[];
386 extern const struct kernel_symbol __start___ksymtab_gpl[];
387 extern const struct kernel_symbol __stop___ksymtab_gpl[];
388 extern const struct kernel_symbol __start___ksymtab_gpl_future[];
389 extern const struct kernel_symbol __stop___ksymtab_gpl_future[];
390 extern const s32 __start___kcrctab[];
391 extern const s32 __start___kcrctab_gpl[];
392 extern const s32 __start___kcrctab_gpl_future[];
393 #ifdef CONFIG_UNUSED_SYMBOLS
394 extern const struct kernel_symbol __start___ksymtab_unused[];
395 extern const struct kernel_symbol __stop___ksymtab_unused[];
396 extern const struct kernel_symbol __start___ksymtab_unused_gpl[];
397 extern const struct kernel_symbol __stop___ksymtab_unused_gpl[];
398 extern const s32 __start___kcrctab_unused[];
399 extern const s32 __start___kcrctab_unused_gpl[];
400 #endif
401 
402 #ifndef CONFIG_MODVERSIONS
403 #define symversion(base, idx) NULL
404 #else
405 #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
406 #endif
407 
each_symbol_in_section(const struct symsearch * arr,unsigned int arrsize,struct module * owner,bool (* fn)(const struct symsearch * syms,struct module * owner,void * data),void * data)408 static bool each_symbol_in_section(const struct symsearch *arr,
409 				   unsigned int arrsize,
410 				   struct module *owner,
411 				   bool (*fn)(const struct symsearch *syms,
412 					      struct module *owner,
413 					      void *data),
414 				   void *data)
415 {
416 	unsigned int j;
417 
418 	for (j = 0; j < arrsize; j++) {
419 		if (fn(&arr[j], owner, data))
420 			return true;
421 	}
422 
423 	return false;
424 }
425 
426 /* Returns true as soon as fn returns true, otherwise false. */
each_symbol_section(bool (* fn)(const struct symsearch * arr,struct module * owner,void * data),void * data)427 static bool each_symbol_section(bool (*fn)(const struct symsearch *arr,
428 				    struct module *owner,
429 				    void *data),
430 			 void *data)
431 {
432 	struct module *mod;
433 	static const struct symsearch arr[] = {
434 		{ __start___ksymtab, __stop___ksymtab, __start___kcrctab,
435 		  NOT_GPL_ONLY, false },
436 		{ __start___ksymtab_gpl, __stop___ksymtab_gpl,
437 		  __start___kcrctab_gpl,
438 		  GPL_ONLY, false },
439 		{ __start___ksymtab_gpl_future, __stop___ksymtab_gpl_future,
440 		  __start___kcrctab_gpl_future,
441 		  WILL_BE_GPL_ONLY, false },
442 #ifdef CONFIG_UNUSED_SYMBOLS
443 		{ __start___ksymtab_unused, __stop___ksymtab_unused,
444 		  __start___kcrctab_unused,
445 		  NOT_GPL_ONLY, true },
446 		{ __start___ksymtab_unused_gpl, __stop___ksymtab_unused_gpl,
447 		  __start___kcrctab_unused_gpl,
448 		  GPL_ONLY, true },
449 #endif
450 	};
451 
452 	module_assert_mutex_or_preempt();
453 
454 	if (each_symbol_in_section(arr, ARRAY_SIZE(arr), NULL, fn, data))
455 		return true;
456 
457 	list_for_each_entry_rcu(mod, &modules, list,
458 				lockdep_is_held(&module_mutex)) {
459 		struct symsearch arr[] = {
460 			{ mod->syms, mod->syms + mod->num_syms, mod->crcs,
461 			  NOT_GPL_ONLY, false },
462 			{ mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
463 			  mod->gpl_crcs,
464 			  GPL_ONLY, false },
465 			{ mod->gpl_future_syms,
466 			  mod->gpl_future_syms + mod->num_gpl_future_syms,
467 			  mod->gpl_future_crcs,
468 			  WILL_BE_GPL_ONLY, false },
469 #ifdef CONFIG_UNUSED_SYMBOLS
470 			{ mod->unused_syms,
471 			  mod->unused_syms + mod->num_unused_syms,
472 			  mod->unused_crcs,
473 			  NOT_GPL_ONLY, true },
474 			{ mod->unused_gpl_syms,
475 			  mod->unused_gpl_syms + mod->num_unused_gpl_syms,
476 			  mod->unused_gpl_crcs,
477 			  GPL_ONLY, true },
478 #endif
479 		};
480 
481 		if (mod->state == MODULE_STATE_UNFORMED)
482 			continue;
483 
484 		if (each_symbol_in_section(arr, ARRAY_SIZE(arr), mod, fn, data))
485 			return true;
486 	}
487 	return false;
488 }
489 
490 struct find_symbol_arg {
491 	/* Input */
492 	const char *name;
493 	bool gplok;
494 	bool warn;
495 
496 	/* Output */
497 	struct module *owner;
498 	const s32 *crc;
499 	const struct kernel_symbol *sym;
500 	enum mod_license license;
501 };
502 
check_exported_symbol(const struct symsearch * syms,struct module * owner,unsigned int symnum,void * data)503 static bool check_exported_symbol(const struct symsearch *syms,
504 				  struct module *owner,
505 				  unsigned int symnum, void *data)
506 {
507 	struct find_symbol_arg *fsa = data;
508 
509 	if (!fsa->gplok) {
510 		if (syms->license == GPL_ONLY)
511 			return false;
512 		if (syms->license == WILL_BE_GPL_ONLY && fsa->warn) {
513 			pr_warn("Symbol %s is being used by a non-GPL module, "
514 				"which will not be allowed in the future\n",
515 				fsa->name);
516 		}
517 	}
518 
519 #ifdef CONFIG_UNUSED_SYMBOLS
520 	if (syms->unused && fsa->warn) {
521 		pr_warn("Symbol %s is marked as UNUSED, however this module is "
522 			"using it.\n", fsa->name);
523 		pr_warn("This symbol will go away in the future.\n");
524 		pr_warn("Please evaluate if this is the right api to use and "
525 			"if it really is, submit a report to the linux kernel "
526 			"mailing list together with submitting your code for "
527 			"inclusion.\n");
528 	}
529 #endif
530 
531 	fsa->owner = owner;
532 	fsa->crc = symversion(syms->crcs, symnum);
533 	fsa->sym = &syms->start[symnum];
534 	fsa->license = syms->license;
535 	return true;
536 }
537 
kernel_symbol_value(const struct kernel_symbol * sym)538 static unsigned long kernel_symbol_value(const struct kernel_symbol *sym)
539 {
540 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
541 	return (unsigned long)offset_to_ptr(&sym->value_offset);
542 #else
543 	return sym->value;
544 #endif
545 }
546 
kernel_symbol_name(const struct kernel_symbol * sym)547 static const char *kernel_symbol_name(const struct kernel_symbol *sym)
548 {
549 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
550 	return offset_to_ptr(&sym->name_offset);
551 #else
552 	return sym->name;
553 #endif
554 }
555 
kernel_symbol_namespace(const struct kernel_symbol * sym)556 static const char *kernel_symbol_namespace(const struct kernel_symbol *sym)
557 {
558 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
559 	if (!sym->namespace_offset)
560 		return NULL;
561 	return offset_to_ptr(&sym->namespace_offset);
562 #else
563 	return sym->namespace;
564 #endif
565 }
566 
cmp_name(const void * name,const void * sym)567 static int cmp_name(const void *name, const void *sym)
568 {
569 	return strcmp(name, kernel_symbol_name(sym));
570 }
571 
find_exported_symbol_in_section(const struct symsearch * syms,struct module * owner,void * data)572 static bool find_exported_symbol_in_section(const struct symsearch *syms,
573 					    struct module *owner,
574 					    void *data)
575 {
576 	struct find_symbol_arg *fsa = data;
577 	struct kernel_symbol *sym;
578 
579 	sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
580 			sizeof(struct kernel_symbol), cmp_name);
581 
582 	if (sym != NULL && check_exported_symbol(syms, owner,
583 						 sym - syms->start, data))
584 		return true;
585 
586 	return false;
587 }
588 
589 /* Find an exported symbol and return it, along with, (optional) crc and
590  * (optional) module which owns it.  Needs preempt disabled or module_mutex. */
find_symbol(const char * name,struct module ** owner,const s32 ** crc,enum mod_license * license,bool gplok,bool warn)591 static const struct kernel_symbol *find_symbol(const char *name,
592 					struct module **owner,
593 					const s32 **crc,
594 					enum mod_license *license,
595 					bool gplok,
596 					bool warn)
597 {
598 	struct find_symbol_arg fsa;
599 
600 	fsa.name = name;
601 	fsa.gplok = gplok;
602 	fsa.warn = warn;
603 
604 	if (each_symbol_section(find_exported_symbol_in_section, &fsa)) {
605 		if (owner)
606 			*owner = fsa.owner;
607 		if (crc)
608 			*crc = fsa.crc;
609 		if (license)
610 			*license = fsa.license;
611 		return fsa.sym;
612 	}
613 
614 	pr_debug("Failed to find symbol %s\n", name);
615 	return NULL;
616 }
617 
618 /*
619  * Search for module by name: must hold module_mutex (or preempt disabled
620  * for read-only access).
621  */
find_module_all(const char * name,size_t len,bool even_unformed)622 static struct module *find_module_all(const char *name, size_t len,
623 				      bool even_unformed)
624 {
625 	struct module *mod;
626 
627 	module_assert_mutex_or_preempt();
628 
629 	list_for_each_entry_rcu(mod, &modules, list,
630 				lockdep_is_held(&module_mutex)) {
631 		if (!even_unformed && mod->state == MODULE_STATE_UNFORMED)
632 			continue;
633 		if (strlen(mod->name) == len && !memcmp(mod->name, name, len))
634 			return mod;
635 	}
636 	return NULL;
637 }
638 
find_module(const char * name)639 struct module *find_module(const char *name)
640 {
641 	module_assert_mutex();
642 	return find_module_all(name, strlen(name), false);
643 }
644 EXPORT_SYMBOL_GPL(find_module);
645 
646 #ifdef CONFIG_SMP
647 
mod_percpu(struct module * mod)648 static inline void __percpu *mod_percpu(struct module *mod)
649 {
650 	return mod->percpu;
651 }
652 
percpu_modalloc(struct module * mod,struct load_info * info)653 static int percpu_modalloc(struct module *mod, struct load_info *info)
654 {
655 	Elf_Shdr *pcpusec = &info->sechdrs[info->index.pcpu];
656 	unsigned long align = pcpusec->sh_addralign;
657 
658 	if (!pcpusec->sh_size)
659 		return 0;
660 
661 	if (align > PAGE_SIZE) {
662 		pr_warn("%s: per-cpu alignment %li > %li\n",
663 			mod->name, align, PAGE_SIZE);
664 		align = PAGE_SIZE;
665 	}
666 
667 	mod->percpu = __alloc_reserved_percpu(pcpusec->sh_size, align);
668 	if (!mod->percpu) {
669 		pr_warn("%s: Could not allocate %lu bytes percpu data\n",
670 			mod->name, (unsigned long)pcpusec->sh_size);
671 		return -ENOMEM;
672 	}
673 	mod->percpu_size = pcpusec->sh_size;
674 	return 0;
675 }
676 
percpu_modfree(struct module * mod)677 static void percpu_modfree(struct module *mod)
678 {
679 	free_percpu(mod->percpu);
680 }
681 
find_pcpusec(struct load_info * info)682 static unsigned int find_pcpusec(struct load_info *info)
683 {
684 	return find_sec(info, ".data..percpu");
685 }
686 
percpu_modcopy(struct module * mod,const void * from,unsigned long size)687 static void percpu_modcopy(struct module *mod,
688 			   const void *from, unsigned long size)
689 {
690 	int cpu;
691 
692 	for_each_possible_cpu(cpu)
693 		memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
694 }
695 
__is_module_percpu_address(unsigned long addr,unsigned long * can_addr)696 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
697 {
698 	struct module *mod;
699 	unsigned int cpu;
700 
701 	preempt_disable();
702 
703 	list_for_each_entry_rcu(mod, &modules, list) {
704 		if (mod->state == MODULE_STATE_UNFORMED)
705 			continue;
706 		if (!mod->percpu_size)
707 			continue;
708 		for_each_possible_cpu(cpu) {
709 			void *start = per_cpu_ptr(mod->percpu, cpu);
710 			void *va = (void *)addr;
711 
712 			if (va >= start && va < start + mod->percpu_size) {
713 				if (can_addr) {
714 					*can_addr = (unsigned long) (va - start);
715 					*can_addr += (unsigned long)
716 						per_cpu_ptr(mod->percpu,
717 							    get_boot_cpu_id());
718 				}
719 				preempt_enable();
720 				return true;
721 			}
722 		}
723 	}
724 
725 	preempt_enable();
726 	return false;
727 }
728 
729 /**
730  * is_module_percpu_address - test whether address is from module static percpu
731  * @addr: address to test
732  *
733  * Test whether @addr belongs to module static percpu area.
734  *
735  * RETURNS:
736  * %true if @addr is from module static percpu area
737  */
is_module_percpu_address(unsigned long addr)738 bool is_module_percpu_address(unsigned long addr)
739 {
740 	return __is_module_percpu_address(addr, NULL);
741 }
742 
743 #else /* ... !CONFIG_SMP */
744 
mod_percpu(struct module * mod)745 static inline void __percpu *mod_percpu(struct module *mod)
746 {
747 	return NULL;
748 }
percpu_modalloc(struct module * mod,struct load_info * info)749 static int percpu_modalloc(struct module *mod, struct load_info *info)
750 {
751 	/* UP modules shouldn't have this section: ENOMEM isn't quite right */
752 	if (info->sechdrs[info->index.pcpu].sh_size != 0)
753 		return -ENOMEM;
754 	return 0;
755 }
percpu_modfree(struct module * mod)756 static inline void percpu_modfree(struct module *mod)
757 {
758 }
find_pcpusec(struct load_info * info)759 static unsigned int find_pcpusec(struct load_info *info)
760 {
761 	return 0;
762 }
percpu_modcopy(struct module * mod,const void * from,unsigned long size)763 static inline void percpu_modcopy(struct module *mod,
764 				  const void *from, unsigned long size)
765 {
766 	/* pcpusec should be 0, and size of that section should be 0. */
767 	BUG_ON(size != 0);
768 }
is_module_percpu_address(unsigned long addr)769 bool is_module_percpu_address(unsigned long addr)
770 {
771 	return false;
772 }
773 
__is_module_percpu_address(unsigned long addr,unsigned long * can_addr)774 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
775 {
776 	return false;
777 }
778 
779 #endif /* CONFIG_SMP */
780 
781 #define MODINFO_ATTR(field)	\
782 static void setup_modinfo_##field(struct module *mod, const char *s)  \
783 {                                                                     \
784 	mod->field = kstrdup(s, GFP_KERNEL);                          \
785 }                                                                     \
786 static ssize_t show_modinfo_##field(struct module_attribute *mattr,   \
787 			struct module_kobject *mk, char *buffer)      \
788 {                                                                     \
789 	return scnprintf(buffer, PAGE_SIZE, "%s\n", mk->mod->field);  \
790 }                                                                     \
791 static int modinfo_##field##_exists(struct module *mod)               \
792 {                                                                     \
793 	return mod->field != NULL;                                    \
794 }                                                                     \
795 static void free_modinfo_##field(struct module *mod)                  \
796 {                                                                     \
797 	kfree(mod->field);                                            \
798 	mod->field = NULL;                                            \
799 }                                                                     \
800 static struct module_attribute modinfo_##field = {                    \
801 	.attr = { .name = __stringify(field), .mode = 0444 },         \
802 	.show = show_modinfo_##field,                                 \
803 	.setup = setup_modinfo_##field,                               \
804 	.test = modinfo_##field##_exists,                             \
805 	.free = free_modinfo_##field,                                 \
806 };
807 
808 MODINFO_ATTR(version);
809 MODINFO_ATTR(srcversion);
810 
811 static char last_unloaded_module[MODULE_NAME_LEN+1];
812 
813 #ifdef CONFIG_MODULE_UNLOAD
814 
815 EXPORT_TRACEPOINT_SYMBOL(module_get);
816 
817 /* MODULE_REF_BASE is the base reference count by kmodule loader. */
818 #define MODULE_REF_BASE	1
819 
820 /* Init the unload section of the module. */
module_unload_init(struct module * mod)821 static int module_unload_init(struct module *mod)
822 {
823 	/*
824 	 * Initialize reference counter to MODULE_REF_BASE.
825 	 * refcnt == 0 means module is going.
826 	 */
827 	atomic_set(&mod->refcnt, MODULE_REF_BASE);
828 
829 	INIT_LIST_HEAD(&mod->source_list);
830 	INIT_LIST_HEAD(&mod->target_list);
831 
832 	/* Hold reference count during initialization. */
833 	atomic_inc(&mod->refcnt);
834 
835 	return 0;
836 }
837 
838 /* Does a already use b? */
already_uses(struct module * a,struct module * b)839 static int already_uses(struct module *a, struct module *b)
840 {
841 	struct module_use *use;
842 
843 	list_for_each_entry(use, &b->source_list, source_list) {
844 		if (use->source == a) {
845 			pr_debug("%s uses %s!\n", a->name, b->name);
846 			return 1;
847 		}
848 	}
849 	pr_debug("%s does not use %s!\n", a->name, b->name);
850 	return 0;
851 }
852 
853 /*
854  * Module a uses b
855  *  - we add 'a' as a "source", 'b' as a "target" of module use
856  *  - the module_use is added to the list of 'b' sources (so
857  *    'b' can walk the list to see who sourced them), and of 'a'
858  *    targets (so 'a' can see what modules it targets).
859  */
add_module_usage(struct module * a,struct module * b)860 static int add_module_usage(struct module *a, struct module *b)
861 {
862 	struct module_use *use;
863 
864 	pr_debug("Allocating new usage for %s.\n", a->name);
865 	use = kmalloc(sizeof(*use), GFP_ATOMIC);
866 	if (!use)
867 		return -ENOMEM;
868 
869 	use->source = a;
870 	use->target = b;
871 	list_add(&use->source_list, &b->source_list);
872 	list_add(&use->target_list, &a->target_list);
873 	return 0;
874 }
875 
876 /* Module a uses b: caller needs module_mutex() */
ref_module(struct module * a,struct module * b)877 static int ref_module(struct module *a, struct module *b)
878 {
879 	int err;
880 
881 	if (b == NULL || already_uses(a, b))
882 		return 0;
883 
884 	/* If module isn't available, we fail. */
885 	err = strong_try_module_get(b);
886 	if (err)
887 		return err;
888 
889 	err = add_module_usage(a, b);
890 	if (err) {
891 		module_put(b);
892 		return err;
893 	}
894 	return 0;
895 }
896 
897 /* Clear the unload stuff of the module. */
module_unload_free(struct module * mod)898 static void module_unload_free(struct module *mod)
899 {
900 	struct module_use *use, *tmp;
901 
902 	mutex_lock(&module_mutex);
903 	list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
904 		struct module *i = use->target;
905 		pr_debug("%s unusing %s\n", mod->name, i->name);
906 		module_put(i);
907 		list_del(&use->source_list);
908 		list_del(&use->target_list);
909 		kfree(use);
910 	}
911 	mutex_unlock(&module_mutex);
912 }
913 
914 #ifdef CONFIG_MODULE_FORCE_UNLOAD
try_force_unload(unsigned int flags)915 static inline int try_force_unload(unsigned int flags)
916 {
917 	int ret = (flags & O_TRUNC);
918 	if (ret)
919 		add_taint(TAINT_FORCED_RMMOD, LOCKDEP_NOW_UNRELIABLE);
920 	return ret;
921 }
922 #else
try_force_unload(unsigned int flags)923 static inline int try_force_unload(unsigned int flags)
924 {
925 	return 0;
926 }
927 #endif /* CONFIG_MODULE_FORCE_UNLOAD */
928 
929 /* Try to release refcount of module, 0 means success. */
try_release_module_ref(struct module * mod)930 static int try_release_module_ref(struct module *mod)
931 {
932 	int ret;
933 
934 	/* Try to decrement refcnt which we set at loading */
935 	ret = atomic_sub_return(MODULE_REF_BASE, &mod->refcnt);
936 	BUG_ON(ret < 0);
937 	if (ret)
938 		/* Someone can put this right now, recover with checking */
939 		ret = atomic_add_unless(&mod->refcnt, MODULE_REF_BASE, 0);
940 
941 	return ret;
942 }
943 
try_stop_module(struct module * mod,int flags,int * forced)944 static int try_stop_module(struct module *mod, int flags, int *forced)
945 {
946 	/* If it's not unused, quit unless we're forcing. */
947 	if (try_release_module_ref(mod) != 0) {
948 		*forced = try_force_unload(flags);
949 		if (!(*forced))
950 			return -EWOULDBLOCK;
951 	}
952 
953 	/* Mark it as dying. */
954 	mod->state = MODULE_STATE_GOING;
955 
956 	return 0;
957 }
958 
959 /**
960  * module_refcount - return the refcount or -1 if unloading
961  *
962  * @mod:	the module we're checking
963  *
964  * Returns:
965  *	-1 if the module is in the process of unloading
966  *	otherwise the number of references in the kernel to the module
967  */
module_refcount(struct module * mod)968 int module_refcount(struct module *mod)
969 {
970 	return atomic_read(&mod->refcnt) - MODULE_REF_BASE;
971 }
972 EXPORT_SYMBOL(module_refcount);
973 
974 /* This exists whether we can unload or not */
975 static void free_module(struct module *mod);
976 
SYSCALL_DEFINE2(delete_module,const char __user *,name_user,unsigned int,flags)977 SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
978 		unsigned int, flags)
979 {
980 	struct module *mod;
981 	char name[MODULE_NAME_LEN];
982 	int ret, forced = 0;
983 
984 	if (!capable(CAP_SYS_MODULE) || modules_disabled)
985 		return -EPERM;
986 
987 	if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
988 		return -EFAULT;
989 	name[MODULE_NAME_LEN-1] = '\0';
990 
991 	audit_log_kern_module(name);
992 
993 	if (mutex_lock_interruptible(&module_mutex) != 0)
994 		return -EINTR;
995 
996 	mod = find_module(name);
997 	if (!mod) {
998 		ret = -ENOENT;
999 		goto out;
1000 	}
1001 
1002 	if (!list_empty(&mod->source_list)) {
1003 		/* Other modules depend on us: get rid of them first. */
1004 		ret = -EWOULDBLOCK;
1005 		goto out;
1006 	}
1007 
1008 	/* Doing init or already dying? */
1009 	if (mod->state != MODULE_STATE_LIVE) {
1010 		/* FIXME: if (force), slam module count damn the torpedoes */
1011 		pr_debug("%s already dying\n", mod->name);
1012 		ret = -EBUSY;
1013 		goto out;
1014 	}
1015 
1016 	/* If it has an init func, it must have an exit func to unload */
1017 	if (mod->init && !mod->exit) {
1018 		forced = try_force_unload(flags);
1019 		if (!forced) {
1020 			/* This module can't be removed */
1021 			ret = -EBUSY;
1022 			goto out;
1023 		}
1024 	}
1025 
1026 	/* Stop the machine so refcounts can't move and disable module. */
1027 	ret = try_stop_module(mod, flags, &forced);
1028 	if (ret != 0)
1029 		goto out;
1030 
1031 	mutex_unlock(&module_mutex);
1032 	/* Final destruction now no one is using it. */
1033 	if (mod->exit != NULL)
1034 		mod->exit();
1035 	blocking_notifier_call_chain(&module_notify_list,
1036 				     MODULE_STATE_GOING, mod);
1037 	klp_module_going(mod);
1038 	ftrace_release_mod(mod);
1039 
1040 	async_synchronize_full();
1041 
1042 	/* Store the name of the last unloaded module for diagnostic purposes */
1043 	strlcpy(last_unloaded_module, mod->name, sizeof(last_unloaded_module));
1044 
1045 	free_module(mod);
1046 	/* someone could wait for the module in add_unformed_module() */
1047 	wake_up_all(&module_wq);
1048 	return 0;
1049 out:
1050 	mutex_unlock(&module_mutex);
1051 	return ret;
1052 }
1053 
print_unload_info(struct seq_file * m,struct module * mod)1054 static inline void print_unload_info(struct seq_file *m, struct module *mod)
1055 {
1056 	struct module_use *use;
1057 	int printed_something = 0;
1058 
1059 	seq_printf(m, " %i ", module_refcount(mod));
1060 
1061 	/*
1062 	 * Always include a trailing , so userspace can differentiate
1063 	 * between this and the old multi-field proc format.
1064 	 */
1065 	list_for_each_entry(use, &mod->source_list, source_list) {
1066 		printed_something = 1;
1067 		seq_printf(m, "%s,", use->source->name);
1068 	}
1069 
1070 	if (mod->init != NULL && mod->exit == NULL) {
1071 		printed_something = 1;
1072 		seq_puts(m, "[permanent],");
1073 	}
1074 
1075 	if (!printed_something)
1076 		seq_puts(m, "-");
1077 }
1078 
__symbol_put(const char * symbol)1079 void __symbol_put(const char *symbol)
1080 {
1081 	struct module *owner;
1082 
1083 	preempt_disable();
1084 	if (!find_symbol(symbol, &owner, NULL, NULL, true, false))
1085 		BUG();
1086 	module_put(owner);
1087 	preempt_enable();
1088 }
1089 
1090 /* Note this assumes addr is a function, which it currently always is. */
symbol_put_addr(void * addr)1091 void symbol_put_addr(void *addr)
1092 {
1093 	struct module *modaddr;
1094 	unsigned long a = (unsigned long)dereference_function_descriptor(addr);
1095 
1096 	if (core_kernel_text(a))
1097 		return;
1098 
1099 	/*
1100 	 * Even though we hold a reference on the module; we still need to
1101 	 * disable preemption in order to safely traverse the data structure.
1102 	 */
1103 	preempt_disable();
1104 	modaddr = __module_text_address(a);
1105 	BUG_ON(!modaddr);
1106 	module_put(modaddr);
1107 	preempt_enable();
1108 }
1109 EXPORT_SYMBOL_GPL(symbol_put_addr);
1110 
show_refcnt(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)1111 static ssize_t show_refcnt(struct module_attribute *mattr,
1112 			   struct module_kobject *mk, char *buffer)
1113 {
1114 	return sprintf(buffer, "%i\n", module_refcount(mk->mod));
1115 }
1116 
1117 static struct module_attribute modinfo_refcnt =
1118 	__ATTR(refcnt, 0444, show_refcnt, NULL);
1119 
__module_get(struct module * module)1120 void __module_get(struct module *module)
1121 {
1122 	if (module) {
1123 		preempt_disable();
1124 		atomic_inc(&module->refcnt);
1125 		trace_module_get(module, _RET_IP_);
1126 		preempt_enable();
1127 	}
1128 }
1129 EXPORT_SYMBOL(__module_get);
1130 
try_module_get(struct module * module)1131 bool try_module_get(struct module *module)
1132 {
1133 	bool ret = true;
1134 
1135 	if (module) {
1136 		preempt_disable();
1137 		/* Note: here, we can fail to get a reference */
1138 		if (likely(module_is_live(module) &&
1139 			   atomic_inc_not_zero(&module->refcnt) != 0))
1140 			trace_module_get(module, _RET_IP_);
1141 		else
1142 			ret = false;
1143 
1144 		preempt_enable();
1145 	}
1146 	return ret;
1147 }
1148 EXPORT_SYMBOL(try_module_get);
1149 
module_put(struct module * module)1150 void module_put(struct module *module)
1151 {
1152 	int ret;
1153 
1154 	if (module) {
1155 		preempt_disable();
1156 		ret = atomic_dec_if_positive(&module->refcnt);
1157 		WARN_ON(ret < 0);	/* Failed to put refcount */
1158 		trace_module_put(module, _RET_IP_);
1159 		preempt_enable();
1160 	}
1161 }
1162 EXPORT_SYMBOL(module_put);
1163 
1164 #else /* !CONFIG_MODULE_UNLOAD */
print_unload_info(struct seq_file * m,struct module * mod)1165 static inline void print_unload_info(struct seq_file *m, struct module *mod)
1166 {
1167 	/* We don't know the usage count, or what modules are using. */
1168 	seq_puts(m, " - -");
1169 }
1170 
module_unload_free(struct module * mod)1171 static inline void module_unload_free(struct module *mod)
1172 {
1173 }
1174 
ref_module(struct module * a,struct module * b)1175 static int ref_module(struct module *a, struct module *b)
1176 {
1177 	return strong_try_module_get(b);
1178 }
1179 
module_unload_init(struct module * mod)1180 static inline int module_unload_init(struct module *mod)
1181 {
1182 	return 0;
1183 }
1184 #endif /* CONFIG_MODULE_UNLOAD */
1185 
module_flags_taint(struct module * mod,char * buf)1186 static size_t module_flags_taint(struct module *mod, char *buf)
1187 {
1188 	size_t l = 0;
1189 	int i;
1190 
1191 	for (i = 0; i < TAINT_FLAGS_COUNT; i++) {
1192 		if (taint_flags[i].module && test_bit(i, &mod->taints))
1193 			buf[l++] = taint_flags[i].c_true;
1194 	}
1195 
1196 	return l;
1197 }
1198 
show_initstate(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)1199 static ssize_t show_initstate(struct module_attribute *mattr,
1200 			      struct module_kobject *mk, char *buffer)
1201 {
1202 	const char *state = "unknown";
1203 
1204 	switch (mk->mod->state) {
1205 	case MODULE_STATE_LIVE:
1206 		state = "live";
1207 		break;
1208 	case MODULE_STATE_COMING:
1209 		state = "coming";
1210 		break;
1211 	case MODULE_STATE_GOING:
1212 		state = "going";
1213 		break;
1214 	default:
1215 		BUG();
1216 	}
1217 	return sprintf(buffer, "%s\n", state);
1218 }
1219 
1220 static struct module_attribute modinfo_initstate =
1221 	__ATTR(initstate, 0444, show_initstate, NULL);
1222 
store_uevent(struct module_attribute * mattr,struct module_kobject * mk,const char * buffer,size_t count)1223 static ssize_t store_uevent(struct module_attribute *mattr,
1224 			    struct module_kobject *mk,
1225 			    const char *buffer, size_t count)
1226 {
1227 	int rc;
1228 
1229 	rc = kobject_synth_uevent(&mk->kobj, buffer, count);
1230 	return rc ? rc : count;
1231 }
1232 
1233 struct module_attribute module_uevent =
1234 	__ATTR(uevent, 0200, NULL, store_uevent);
1235 
show_coresize(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)1236 static ssize_t show_coresize(struct module_attribute *mattr,
1237 			     struct module_kobject *mk, char *buffer)
1238 {
1239 	return sprintf(buffer, "%u\n", mk->mod->core_layout.size);
1240 }
1241 
1242 static struct module_attribute modinfo_coresize =
1243 	__ATTR(coresize, 0444, show_coresize, NULL);
1244 
show_initsize(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)1245 static ssize_t show_initsize(struct module_attribute *mattr,
1246 			     struct module_kobject *mk, char *buffer)
1247 {
1248 	return sprintf(buffer, "%u\n", mk->mod->init_layout.size);
1249 }
1250 
1251 static struct module_attribute modinfo_initsize =
1252 	__ATTR(initsize, 0444, show_initsize, NULL);
1253 
show_taint(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)1254 static ssize_t show_taint(struct module_attribute *mattr,
1255 			  struct module_kobject *mk, char *buffer)
1256 {
1257 	size_t l;
1258 
1259 	l = module_flags_taint(mk->mod, buffer);
1260 	buffer[l++] = '\n';
1261 	return l;
1262 }
1263 
1264 static struct module_attribute modinfo_taint =
1265 	__ATTR(taint, 0444, show_taint, NULL);
1266 
1267 static struct module_attribute *modinfo_attrs[] = {
1268 	&module_uevent,
1269 	&modinfo_version,
1270 	&modinfo_srcversion,
1271 	&modinfo_initstate,
1272 	&modinfo_coresize,
1273 	&modinfo_initsize,
1274 	&modinfo_taint,
1275 #ifdef CONFIG_MODULE_UNLOAD
1276 	&modinfo_refcnt,
1277 #endif
1278 	NULL,
1279 };
1280 
1281 static const char vermagic[] = VERMAGIC_STRING;
1282 
try_to_force_load(struct module * mod,const char * reason)1283 static int try_to_force_load(struct module *mod, const char *reason)
1284 {
1285 #ifdef CONFIG_MODULE_FORCE_LOAD
1286 	if (!test_taint(TAINT_FORCED_MODULE))
1287 		pr_warn("%s: %s: kernel tainted.\n", mod->name, reason);
1288 	add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE);
1289 	return 0;
1290 #else
1291 	return -ENOEXEC;
1292 #endif
1293 }
1294 
1295 #ifdef CONFIG_MODVERSIONS
1296 
resolve_rel_crc(const s32 * crc)1297 static u32 resolve_rel_crc(const s32 *crc)
1298 {
1299 	return *(u32 *)((void *)crc + *crc);
1300 }
1301 
check_version(const struct load_info * info,const char * symname,struct module * mod,const s32 * crc)1302 static int check_version(const struct load_info *info,
1303 			 const char *symname,
1304 			 struct module *mod,
1305 			 const s32 *crc)
1306 {
1307 	Elf_Shdr *sechdrs = info->sechdrs;
1308 	unsigned int versindex = info->index.vers;
1309 	unsigned int i, num_versions;
1310 	struct modversion_info *versions;
1311 
1312 	/* Exporting module didn't supply crcs?  OK, we're already tainted. */
1313 	if (!crc)
1314 		return 1;
1315 
1316 	/* No versions at all?  modprobe --force does this. */
1317 	if (versindex == 0)
1318 		return try_to_force_load(mod, symname) == 0;
1319 
1320 	versions = (void *) sechdrs[versindex].sh_addr;
1321 	num_versions = sechdrs[versindex].sh_size
1322 		/ sizeof(struct modversion_info);
1323 
1324 	for (i = 0; i < num_versions; i++) {
1325 		u32 crcval;
1326 
1327 		if (strcmp(versions[i].name, symname) != 0)
1328 			continue;
1329 
1330 		if (IS_ENABLED(CONFIG_MODULE_REL_CRCS))
1331 			crcval = resolve_rel_crc(crc);
1332 		else
1333 			crcval = *crc;
1334 		if (versions[i].crc == crcval)
1335 			return 1;
1336 		pr_debug("Found checksum %X vs module %lX\n",
1337 			 crcval, versions[i].crc);
1338 		goto bad_version;
1339 	}
1340 
1341 	/* Broken toolchain. Warn once, then let it go.. */
1342 	pr_warn_once("%s: no symbol version for %s\n", info->name, symname);
1343 	return 1;
1344 
1345 bad_version:
1346 	pr_warn("%s: disagrees about version of symbol %s\n",
1347 	       info->name, symname);
1348 	return 0;
1349 }
1350 
check_modstruct_version(const struct load_info * info,struct module * mod)1351 static inline int check_modstruct_version(const struct load_info *info,
1352 					  struct module *mod)
1353 {
1354 	const s32 *crc;
1355 
1356 	/*
1357 	 * Since this should be found in kernel (which can't be removed), no
1358 	 * locking is necessary -- use preempt_disable() to placate lockdep.
1359 	 */
1360 	preempt_disable();
1361 	if (!find_symbol("module_layout", NULL, &crc, NULL, true, false)) {
1362 		preempt_enable();
1363 		BUG();
1364 	}
1365 	preempt_enable();
1366 	return check_version(info, "module_layout", mod, crc);
1367 }
1368 
1369 /* First part is kernel version, which we ignore if module has crcs. */
same_magic(const char * amagic,const char * bmagic,bool has_crcs)1370 static inline int same_magic(const char *amagic, const char *bmagic,
1371 			     bool has_crcs)
1372 {
1373 	if (has_crcs) {
1374 		amagic += strcspn(amagic, " ");
1375 		bmagic += strcspn(bmagic, " ");
1376 	}
1377 	return strcmp(amagic, bmagic) == 0;
1378 }
1379 #else
check_version(const struct load_info * info,const char * symname,struct module * mod,const s32 * crc)1380 static inline int check_version(const struct load_info *info,
1381 				const char *symname,
1382 				struct module *mod,
1383 				const s32 *crc)
1384 {
1385 	return 1;
1386 }
1387 
check_modstruct_version(const struct load_info * info,struct module * mod)1388 static inline int check_modstruct_version(const struct load_info *info,
1389 					  struct module *mod)
1390 {
1391 	return 1;
1392 }
1393 
same_magic(const char * amagic,const char * bmagic,bool has_crcs)1394 static inline int same_magic(const char *amagic, const char *bmagic,
1395 			     bool has_crcs)
1396 {
1397 	return strcmp(amagic, bmagic) == 0;
1398 }
1399 #endif /* CONFIG_MODVERSIONS */
1400 
1401 static char *get_modinfo(const struct load_info *info, const char *tag);
1402 static char *get_next_modinfo(const struct load_info *info, const char *tag,
1403 			      char *prev);
1404 
verify_namespace_is_imported(const struct load_info * info,const struct kernel_symbol * sym,struct module * mod)1405 static int verify_namespace_is_imported(const struct load_info *info,
1406 					const struct kernel_symbol *sym,
1407 					struct module *mod)
1408 {
1409 	const char *namespace;
1410 	char *imported_namespace;
1411 
1412 	namespace = kernel_symbol_namespace(sym);
1413 	if (namespace) {
1414 		imported_namespace = get_modinfo(info, "import_ns");
1415 		while (imported_namespace) {
1416 			if (strcmp(namespace, imported_namespace) == 0)
1417 				return 0;
1418 			imported_namespace = get_next_modinfo(
1419 				info, "import_ns", imported_namespace);
1420 		}
1421 #ifdef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1422 		pr_warn(
1423 #else
1424 		pr_err(
1425 #endif
1426 			"%s: module uses symbol (%s) from namespace %s, but does not import it.\n",
1427 			mod->name, kernel_symbol_name(sym), namespace);
1428 #ifndef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1429 		return -EINVAL;
1430 #endif
1431 	}
1432 	return 0;
1433 }
1434 
inherit_taint(struct module * mod,struct module * owner)1435 static bool inherit_taint(struct module *mod, struct module *owner)
1436 {
1437 	if (!owner || !test_bit(TAINT_PROPRIETARY_MODULE, &owner->taints))
1438 		return true;
1439 
1440 	if (mod->using_gplonly_symbols) {
1441 		pr_err("%s: module using GPL-only symbols uses symbols from proprietary module %s.\n",
1442 			mod->name, owner->name);
1443 		return false;
1444 	}
1445 
1446 	if (!test_bit(TAINT_PROPRIETARY_MODULE, &mod->taints)) {
1447 		pr_warn("%s: module uses symbols from proprietary module %s, inheriting taint.\n",
1448 			mod->name, owner->name);
1449 		set_bit(TAINT_PROPRIETARY_MODULE, &mod->taints);
1450 	}
1451 	return true;
1452 }
1453 
1454 /* Resolve a symbol for this module.  I.e. if we find one, record usage. */
resolve_symbol(struct module * mod,const struct load_info * info,const char * name,char ownername[])1455 static const struct kernel_symbol *resolve_symbol(struct module *mod,
1456 						  const struct load_info *info,
1457 						  const char *name,
1458 						  char ownername[])
1459 {
1460 	struct module *owner;
1461 	const struct kernel_symbol *sym;
1462 	const s32 *crc;
1463 	enum mod_license license;
1464 	int err;
1465 
1466 	/*
1467 	 * The module_mutex should not be a heavily contended lock;
1468 	 * if we get the occasional sleep here, we'll go an extra iteration
1469 	 * in the wait_event_interruptible(), which is harmless.
1470 	 */
1471 	sched_annotate_sleep();
1472 	mutex_lock(&module_mutex);
1473 	sym = find_symbol(name, &owner, &crc, &license,
1474 			  !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)), true);
1475 	if (!sym)
1476 		goto unlock;
1477 
1478 	if (license == GPL_ONLY)
1479 		mod->using_gplonly_symbols = true;
1480 
1481 	if (!inherit_taint(mod, owner)) {
1482 		sym = NULL;
1483 		goto getname;
1484 	}
1485 
1486 	if (!check_version(info, name, mod, crc)) {
1487 		sym = ERR_PTR(-EINVAL);
1488 		goto getname;
1489 	}
1490 
1491 	err = verify_namespace_is_imported(info, sym, mod);
1492 	if (err) {
1493 		sym = ERR_PTR(err);
1494 		goto getname;
1495 	}
1496 
1497 	err = ref_module(mod, owner);
1498 	if (err) {
1499 		sym = ERR_PTR(err);
1500 		goto getname;
1501 	}
1502 
1503 getname:
1504 	/* We must make copy under the lock if we failed to get ref. */
1505 	strncpy(ownername, module_name(owner), MODULE_NAME_LEN);
1506 unlock:
1507 	mutex_unlock(&module_mutex);
1508 	return sym;
1509 }
1510 
1511 static const struct kernel_symbol *
resolve_symbol_wait(struct module * mod,const struct load_info * info,const char * name)1512 resolve_symbol_wait(struct module *mod,
1513 		    const struct load_info *info,
1514 		    const char *name)
1515 {
1516 	const struct kernel_symbol *ksym;
1517 	char owner[MODULE_NAME_LEN];
1518 
1519 	if (wait_event_interruptible_timeout(module_wq,
1520 			!IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1521 			|| PTR_ERR(ksym) != -EBUSY,
1522 					     30 * HZ) <= 0) {
1523 		pr_warn("%s: gave up waiting for init of module %s.\n",
1524 			mod->name, owner);
1525 	}
1526 	return ksym;
1527 }
1528 
1529 /*
1530  * /sys/module/foo/sections stuff
1531  * J. Corbet <corbet@lwn.net>
1532  */
1533 #ifdef CONFIG_SYSFS
1534 
1535 #ifdef CONFIG_KALLSYMS
sect_empty(const Elf_Shdr * sect)1536 static inline bool sect_empty(const Elf_Shdr *sect)
1537 {
1538 	return !(sect->sh_flags & SHF_ALLOC) || sect->sh_size == 0;
1539 }
1540 
1541 struct module_sect_attr {
1542 	struct bin_attribute battr;
1543 	unsigned long address;
1544 };
1545 
1546 struct module_sect_attrs {
1547 	struct attribute_group grp;
1548 	unsigned int nsections;
1549 	struct module_sect_attr attrs[0];
1550 };
1551 
1552 #define MODULE_SECT_READ_SIZE (3 /* "0x", "\n" */ + (BITS_PER_LONG / 4))
module_sect_read(struct file * file,struct kobject * kobj,struct bin_attribute * battr,char * buf,loff_t pos,size_t count)1553 static ssize_t module_sect_read(struct file *file, struct kobject *kobj,
1554 				struct bin_attribute *battr,
1555 				char *buf, loff_t pos, size_t count)
1556 {
1557 	struct module_sect_attr *sattr =
1558 		container_of(battr, struct module_sect_attr, battr);
1559 	char bounce[MODULE_SECT_READ_SIZE + 1];
1560 	size_t wrote;
1561 
1562 	if (pos != 0)
1563 		return -EINVAL;
1564 
1565 	/*
1566 	 * Since we're a binary read handler, we must account for the
1567 	 * trailing NUL byte that sprintf will write: if "buf" is
1568 	 * too small to hold the NUL, or the NUL is exactly the last
1569 	 * byte, the read will look like it got truncated by one byte.
1570 	 * Since there is no way to ask sprintf nicely to not write
1571 	 * the NUL, we have to use a bounce buffer.
1572 	 */
1573 	wrote = scnprintf(bounce, sizeof(bounce), "0x%px\n",
1574 			 kallsyms_show_value(file->f_cred)
1575 				? (void *)sattr->address : NULL);
1576 	count = min(count, wrote);
1577 	memcpy(buf, bounce, count);
1578 
1579 	return count;
1580 }
1581 
free_sect_attrs(struct module_sect_attrs * sect_attrs)1582 static void free_sect_attrs(struct module_sect_attrs *sect_attrs)
1583 {
1584 	unsigned int section;
1585 
1586 	for (section = 0; section < sect_attrs->nsections; section++)
1587 		kfree(sect_attrs->attrs[section].battr.attr.name);
1588 	kfree(sect_attrs);
1589 }
1590 
add_sect_attrs(struct module * mod,const struct load_info * info)1591 static void add_sect_attrs(struct module *mod, const struct load_info *info)
1592 {
1593 	unsigned int nloaded = 0, i, size[2];
1594 	struct module_sect_attrs *sect_attrs;
1595 	struct module_sect_attr *sattr;
1596 	struct bin_attribute **gattr;
1597 
1598 	/* Count loaded sections and allocate structures */
1599 	for (i = 0; i < info->hdr->e_shnum; i++)
1600 		if (!sect_empty(&info->sechdrs[i]))
1601 			nloaded++;
1602 	size[0] = ALIGN(struct_size(sect_attrs, attrs, nloaded),
1603 			sizeof(sect_attrs->grp.bin_attrs[0]));
1604 	size[1] = (nloaded + 1) * sizeof(sect_attrs->grp.bin_attrs[0]);
1605 	sect_attrs = kzalloc(size[0] + size[1], GFP_KERNEL);
1606 	if (sect_attrs == NULL)
1607 		return;
1608 
1609 	/* Setup section attributes. */
1610 	sect_attrs->grp.name = "sections";
1611 	sect_attrs->grp.bin_attrs = (void *)sect_attrs + size[0];
1612 
1613 	sect_attrs->nsections = 0;
1614 	sattr = &sect_attrs->attrs[0];
1615 	gattr = &sect_attrs->grp.bin_attrs[0];
1616 	for (i = 0; i < info->hdr->e_shnum; i++) {
1617 		Elf_Shdr *sec = &info->sechdrs[i];
1618 		if (sect_empty(sec))
1619 			continue;
1620 		sysfs_bin_attr_init(&sattr->battr);
1621 		sattr->address = sec->sh_addr;
1622 		sattr->battr.attr.name =
1623 			kstrdup(info->secstrings + sec->sh_name, GFP_KERNEL);
1624 		if (sattr->battr.attr.name == NULL)
1625 			goto out;
1626 		sect_attrs->nsections++;
1627 		sattr->battr.read = module_sect_read;
1628 		sattr->battr.size = MODULE_SECT_READ_SIZE;
1629 		sattr->battr.attr.mode = 0400;
1630 		*(gattr++) = &(sattr++)->battr;
1631 	}
1632 	*gattr = NULL;
1633 
1634 	if (sysfs_create_group(&mod->mkobj.kobj, &sect_attrs->grp))
1635 		goto out;
1636 
1637 	mod->sect_attrs = sect_attrs;
1638 	return;
1639   out:
1640 	free_sect_attrs(sect_attrs);
1641 }
1642 
remove_sect_attrs(struct module * mod)1643 static void remove_sect_attrs(struct module *mod)
1644 {
1645 	if (mod->sect_attrs) {
1646 		sysfs_remove_group(&mod->mkobj.kobj,
1647 				   &mod->sect_attrs->grp);
1648 		/* We are positive that no one is using any sect attrs
1649 		 * at this point.  Deallocate immediately. */
1650 		free_sect_attrs(mod->sect_attrs);
1651 		mod->sect_attrs = NULL;
1652 	}
1653 }
1654 
1655 /*
1656  * /sys/module/foo/notes/.section.name gives contents of SHT_NOTE sections.
1657  */
1658 
1659 struct module_notes_attrs {
1660 	struct kobject *dir;
1661 	unsigned int notes;
1662 	struct bin_attribute attrs[0];
1663 };
1664 
module_notes_read(struct file * filp,struct kobject * kobj,struct bin_attribute * bin_attr,char * buf,loff_t pos,size_t count)1665 static ssize_t module_notes_read(struct file *filp, struct kobject *kobj,
1666 				 struct bin_attribute *bin_attr,
1667 				 char *buf, loff_t pos, size_t count)
1668 {
1669 	/*
1670 	 * The caller checked the pos and count against our size.
1671 	 */
1672 	memcpy(buf, bin_attr->private + pos, count);
1673 	return count;
1674 }
1675 
free_notes_attrs(struct module_notes_attrs * notes_attrs,unsigned int i)1676 static void free_notes_attrs(struct module_notes_attrs *notes_attrs,
1677 			     unsigned int i)
1678 {
1679 	if (notes_attrs->dir) {
1680 		while (i-- > 0)
1681 			sysfs_remove_bin_file(notes_attrs->dir,
1682 					      &notes_attrs->attrs[i]);
1683 		kobject_put(notes_attrs->dir);
1684 	}
1685 	kfree(notes_attrs);
1686 }
1687 
add_notes_attrs(struct module * mod,const struct load_info * info)1688 static void add_notes_attrs(struct module *mod, const struct load_info *info)
1689 {
1690 	unsigned int notes, loaded, i;
1691 	struct module_notes_attrs *notes_attrs;
1692 	struct bin_attribute *nattr;
1693 
1694 	/* failed to create section attributes, so can't create notes */
1695 	if (!mod->sect_attrs)
1696 		return;
1697 
1698 	/* Count notes sections and allocate structures.  */
1699 	notes = 0;
1700 	for (i = 0; i < info->hdr->e_shnum; i++)
1701 		if (!sect_empty(&info->sechdrs[i]) &&
1702 		    (info->sechdrs[i].sh_type == SHT_NOTE))
1703 			++notes;
1704 
1705 	if (notes == 0)
1706 		return;
1707 
1708 	notes_attrs = kzalloc(struct_size(notes_attrs, attrs, notes),
1709 			      GFP_KERNEL);
1710 	if (notes_attrs == NULL)
1711 		return;
1712 
1713 	notes_attrs->notes = notes;
1714 	nattr = &notes_attrs->attrs[0];
1715 	for (loaded = i = 0; i < info->hdr->e_shnum; ++i) {
1716 		if (sect_empty(&info->sechdrs[i]))
1717 			continue;
1718 		if (info->sechdrs[i].sh_type == SHT_NOTE) {
1719 			sysfs_bin_attr_init(nattr);
1720 			nattr->attr.name = mod->sect_attrs->attrs[loaded].battr.attr.name;
1721 			nattr->attr.mode = S_IRUGO;
1722 			nattr->size = info->sechdrs[i].sh_size;
1723 			nattr->private = (void *) info->sechdrs[i].sh_addr;
1724 			nattr->read = module_notes_read;
1725 			++nattr;
1726 		}
1727 		++loaded;
1728 	}
1729 
1730 	notes_attrs->dir = kobject_create_and_add("notes", &mod->mkobj.kobj);
1731 	if (!notes_attrs->dir)
1732 		goto out;
1733 
1734 	for (i = 0; i < notes; ++i)
1735 		if (sysfs_create_bin_file(notes_attrs->dir,
1736 					  &notes_attrs->attrs[i]))
1737 			goto out;
1738 
1739 	mod->notes_attrs = notes_attrs;
1740 	return;
1741 
1742   out:
1743 	free_notes_attrs(notes_attrs, i);
1744 }
1745 
remove_notes_attrs(struct module * mod)1746 static void remove_notes_attrs(struct module *mod)
1747 {
1748 	if (mod->notes_attrs)
1749 		free_notes_attrs(mod->notes_attrs, mod->notes_attrs->notes);
1750 }
1751 
1752 #else
1753 
add_sect_attrs(struct module * mod,const struct load_info * info)1754 static inline void add_sect_attrs(struct module *mod,
1755 				  const struct load_info *info)
1756 {
1757 }
1758 
remove_sect_attrs(struct module * mod)1759 static inline void remove_sect_attrs(struct module *mod)
1760 {
1761 }
1762 
add_notes_attrs(struct module * mod,const struct load_info * info)1763 static inline void add_notes_attrs(struct module *mod,
1764 				   const struct load_info *info)
1765 {
1766 }
1767 
remove_notes_attrs(struct module * mod)1768 static inline void remove_notes_attrs(struct module *mod)
1769 {
1770 }
1771 #endif /* CONFIG_KALLSYMS */
1772 
del_usage_links(struct module * mod)1773 static void del_usage_links(struct module *mod)
1774 {
1775 #ifdef CONFIG_MODULE_UNLOAD
1776 	struct module_use *use;
1777 
1778 	mutex_lock(&module_mutex);
1779 	list_for_each_entry(use, &mod->target_list, target_list)
1780 		sysfs_remove_link(use->target->holders_dir, mod->name);
1781 	mutex_unlock(&module_mutex);
1782 #endif
1783 }
1784 
add_usage_links(struct module * mod)1785 static int add_usage_links(struct module *mod)
1786 {
1787 	int ret = 0;
1788 #ifdef CONFIG_MODULE_UNLOAD
1789 	struct module_use *use;
1790 
1791 	mutex_lock(&module_mutex);
1792 	list_for_each_entry(use, &mod->target_list, target_list) {
1793 		ret = sysfs_create_link(use->target->holders_dir,
1794 					&mod->mkobj.kobj, mod->name);
1795 		if (ret)
1796 			break;
1797 	}
1798 	mutex_unlock(&module_mutex);
1799 	if (ret)
1800 		del_usage_links(mod);
1801 #endif
1802 	return ret;
1803 }
1804 
1805 static void module_remove_modinfo_attrs(struct module *mod, int end);
1806 
module_add_modinfo_attrs(struct module * mod)1807 static int module_add_modinfo_attrs(struct module *mod)
1808 {
1809 	struct module_attribute *attr;
1810 	struct module_attribute *temp_attr;
1811 	int error = 0;
1812 	int i;
1813 
1814 	mod->modinfo_attrs = kzalloc((sizeof(struct module_attribute) *
1815 					(ARRAY_SIZE(modinfo_attrs) + 1)),
1816 					GFP_KERNEL);
1817 	if (!mod->modinfo_attrs)
1818 		return -ENOMEM;
1819 
1820 	temp_attr = mod->modinfo_attrs;
1821 	for (i = 0; (attr = modinfo_attrs[i]); i++) {
1822 		if (!attr->test || attr->test(mod)) {
1823 			memcpy(temp_attr, attr, sizeof(*temp_attr));
1824 			sysfs_attr_init(&temp_attr->attr);
1825 			error = sysfs_create_file(&mod->mkobj.kobj,
1826 					&temp_attr->attr);
1827 			if (error)
1828 				goto error_out;
1829 			++temp_attr;
1830 		}
1831 	}
1832 
1833 	return 0;
1834 
1835 error_out:
1836 	if (i > 0)
1837 		module_remove_modinfo_attrs(mod, --i);
1838 	else
1839 		kfree(mod->modinfo_attrs);
1840 	return error;
1841 }
1842 
module_remove_modinfo_attrs(struct module * mod,int end)1843 static void module_remove_modinfo_attrs(struct module *mod, int end)
1844 {
1845 	struct module_attribute *attr;
1846 	int i;
1847 
1848 	for (i = 0; (attr = &mod->modinfo_attrs[i]); i++) {
1849 		if (end >= 0 && i > end)
1850 			break;
1851 		/* pick a field to test for end of list */
1852 		if (!attr->attr.name)
1853 			break;
1854 		sysfs_remove_file(&mod->mkobj.kobj, &attr->attr);
1855 		if (attr->free)
1856 			attr->free(mod);
1857 	}
1858 	kfree(mod->modinfo_attrs);
1859 }
1860 
mod_kobject_put(struct module * mod)1861 static void mod_kobject_put(struct module *mod)
1862 {
1863 	DECLARE_COMPLETION_ONSTACK(c);
1864 	mod->mkobj.kobj_completion = &c;
1865 	kobject_put(&mod->mkobj.kobj);
1866 	wait_for_completion(&c);
1867 }
1868 
mod_sysfs_init(struct module * mod)1869 static int mod_sysfs_init(struct module *mod)
1870 {
1871 	int err;
1872 	struct kobject *kobj;
1873 
1874 	if (!module_sysfs_initialized) {
1875 		pr_err("%s: module sysfs not initialized\n", mod->name);
1876 		err = -EINVAL;
1877 		goto out;
1878 	}
1879 
1880 	kobj = kset_find_obj(module_kset, mod->name);
1881 	if (kobj) {
1882 		pr_err("%s: module is already loaded\n", mod->name);
1883 		kobject_put(kobj);
1884 		err = -EINVAL;
1885 		goto out;
1886 	}
1887 
1888 	mod->mkobj.mod = mod;
1889 
1890 	memset(&mod->mkobj.kobj, 0, sizeof(mod->mkobj.kobj));
1891 	mod->mkobj.kobj.kset = module_kset;
1892 	err = kobject_init_and_add(&mod->mkobj.kobj, &module_ktype, NULL,
1893 				   "%s", mod->name);
1894 	if (err)
1895 		mod_kobject_put(mod);
1896 
1897 out:
1898 	return err;
1899 }
1900 
mod_sysfs_setup(struct module * mod,const struct load_info * info,struct kernel_param * kparam,unsigned int num_params)1901 static int mod_sysfs_setup(struct module *mod,
1902 			   const struct load_info *info,
1903 			   struct kernel_param *kparam,
1904 			   unsigned int num_params)
1905 {
1906 	int err;
1907 
1908 	err = mod_sysfs_init(mod);
1909 	if (err)
1910 		goto out;
1911 
1912 	mod->holders_dir = kobject_create_and_add("holders", &mod->mkobj.kobj);
1913 	if (!mod->holders_dir) {
1914 		err = -ENOMEM;
1915 		goto out_unreg;
1916 	}
1917 
1918 	err = module_param_sysfs_setup(mod, kparam, num_params);
1919 	if (err)
1920 		goto out_unreg_holders;
1921 
1922 	err = module_add_modinfo_attrs(mod);
1923 	if (err)
1924 		goto out_unreg_param;
1925 
1926 	err = add_usage_links(mod);
1927 	if (err)
1928 		goto out_unreg_modinfo_attrs;
1929 
1930 	add_sect_attrs(mod, info);
1931 	add_notes_attrs(mod, info);
1932 
1933 	return 0;
1934 
1935 out_unreg_modinfo_attrs:
1936 	module_remove_modinfo_attrs(mod, -1);
1937 out_unreg_param:
1938 	module_param_sysfs_remove(mod);
1939 out_unreg_holders:
1940 	kobject_put(mod->holders_dir);
1941 out_unreg:
1942 	mod_kobject_put(mod);
1943 out:
1944 	return err;
1945 }
1946 
mod_sysfs_fini(struct module * mod)1947 static void mod_sysfs_fini(struct module *mod)
1948 {
1949 	remove_notes_attrs(mod);
1950 	remove_sect_attrs(mod);
1951 	mod_kobject_put(mod);
1952 }
1953 
init_param_lock(struct module * mod)1954 static void init_param_lock(struct module *mod)
1955 {
1956 	mutex_init(&mod->param_lock);
1957 }
1958 #else /* !CONFIG_SYSFS */
1959 
mod_sysfs_setup(struct module * mod,const struct load_info * info,struct kernel_param * kparam,unsigned int num_params)1960 static int mod_sysfs_setup(struct module *mod,
1961 			   const struct load_info *info,
1962 			   struct kernel_param *kparam,
1963 			   unsigned int num_params)
1964 {
1965 	return 0;
1966 }
1967 
mod_sysfs_fini(struct module * mod)1968 static void mod_sysfs_fini(struct module *mod)
1969 {
1970 }
1971 
module_remove_modinfo_attrs(struct module * mod,int end)1972 static void module_remove_modinfo_attrs(struct module *mod, int end)
1973 {
1974 }
1975 
del_usage_links(struct module * mod)1976 static void del_usage_links(struct module *mod)
1977 {
1978 }
1979 
init_param_lock(struct module * mod)1980 static void init_param_lock(struct module *mod)
1981 {
1982 }
1983 #endif /* CONFIG_SYSFS */
1984 
mod_sysfs_teardown(struct module * mod)1985 static void mod_sysfs_teardown(struct module *mod)
1986 {
1987 	del_usage_links(mod);
1988 	module_remove_modinfo_attrs(mod, -1);
1989 	module_param_sysfs_remove(mod);
1990 	kobject_put(mod->mkobj.drivers_dir);
1991 	kobject_put(mod->holders_dir);
1992 	mod_sysfs_fini(mod);
1993 }
1994 
1995 #ifdef CONFIG_ARCH_HAS_STRICT_MODULE_RWX
1996 /*
1997  * LKM RO/NX protection: protect module's text/ro-data
1998  * from modification and any data from execution.
1999  *
2000  * General layout of module is:
2001  *          [text] [read-only-data] [ro-after-init] [writable data]
2002  * text_size -----^                ^               ^               ^
2003  * ro_size ------------------------|               |               |
2004  * ro_after_init_size -----------------------------|               |
2005  * size -----------------------------------------------------------|
2006  *
2007  * These values are always page-aligned (as is base)
2008  */
frob_text(const struct module_layout * layout,int (* set_memory)(unsigned long start,int num_pages))2009 static void frob_text(const struct module_layout *layout,
2010 		      int (*set_memory)(unsigned long start, int num_pages))
2011 {
2012 	BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
2013 	BUG_ON((unsigned long)layout->text_size & (PAGE_SIZE-1));
2014 	set_memory((unsigned long)layout->base,
2015 		   layout->text_size >> PAGE_SHIFT);
2016 }
2017 
2018 #ifdef CONFIG_STRICT_MODULE_RWX
frob_rodata(const struct module_layout * layout,int (* set_memory)(unsigned long start,int num_pages))2019 static void frob_rodata(const struct module_layout *layout,
2020 			int (*set_memory)(unsigned long start, int num_pages))
2021 {
2022 	BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
2023 	BUG_ON((unsigned long)layout->text_size & (PAGE_SIZE-1));
2024 	BUG_ON((unsigned long)layout->ro_size & (PAGE_SIZE-1));
2025 	set_memory((unsigned long)layout->base + layout->text_size,
2026 		   (layout->ro_size - layout->text_size) >> PAGE_SHIFT);
2027 }
2028 
frob_ro_after_init(const struct module_layout * layout,int (* set_memory)(unsigned long start,int num_pages))2029 static void frob_ro_after_init(const struct module_layout *layout,
2030 				int (*set_memory)(unsigned long start, int num_pages))
2031 {
2032 	BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
2033 	BUG_ON((unsigned long)layout->ro_size & (PAGE_SIZE-1));
2034 	BUG_ON((unsigned long)layout->ro_after_init_size & (PAGE_SIZE-1));
2035 	set_memory((unsigned long)layout->base + layout->ro_size,
2036 		   (layout->ro_after_init_size - layout->ro_size) >> PAGE_SHIFT);
2037 }
2038 
frob_writable_data(const struct module_layout * layout,int (* set_memory)(unsigned long start,int num_pages))2039 static void frob_writable_data(const struct module_layout *layout,
2040 			       int (*set_memory)(unsigned long start, int num_pages))
2041 {
2042 	BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
2043 	BUG_ON((unsigned long)layout->ro_after_init_size & (PAGE_SIZE-1));
2044 	BUG_ON((unsigned long)layout->size & (PAGE_SIZE-1));
2045 	set_memory((unsigned long)layout->base + layout->ro_after_init_size,
2046 		   (layout->size - layout->ro_after_init_size) >> PAGE_SHIFT);
2047 }
2048 
2049 /* livepatching wants to disable read-only so it can frob module. */
module_disable_ro(const struct module * mod)2050 void module_disable_ro(const struct module *mod)
2051 {
2052 	if (!rodata_enabled)
2053 		return;
2054 
2055 	frob_text(&mod->core_layout, set_memory_rw);
2056 	frob_rodata(&mod->core_layout, set_memory_rw);
2057 	frob_ro_after_init(&mod->core_layout, set_memory_rw);
2058 	frob_text(&mod->init_layout, set_memory_rw);
2059 	frob_rodata(&mod->init_layout, set_memory_rw);
2060 }
2061 
module_enable_ro(const struct module * mod,bool after_init)2062 void module_enable_ro(const struct module *mod, bool after_init)
2063 {
2064 	if (!rodata_enabled)
2065 		return;
2066 
2067 	set_vm_flush_reset_perms(mod->core_layout.base);
2068 	set_vm_flush_reset_perms(mod->init_layout.base);
2069 	frob_text(&mod->core_layout, set_memory_ro);
2070 
2071 	frob_rodata(&mod->core_layout, set_memory_ro);
2072 	frob_text(&mod->init_layout, set_memory_ro);
2073 	frob_rodata(&mod->init_layout, set_memory_ro);
2074 
2075 	if (after_init)
2076 		frob_ro_after_init(&mod->core_layout, set_memory_ro);
2077 }
2078 
module_enable_nx(const struct module * mod)2079 static void module_enable_nx(const struct module *mod)
2080 {
2081 	frob_rodata(&mod->core_layout, set_memory_nx);
2082 	frob_ro_after_init(&mod->core_layout, set_memory_nx);
2083 	frob_writable_data(&mod->core_layout, set_memory_nx);
2084 	frob_rodata(&mod->init_layout, set_memory_nx);
2085 	frob_writable_data(&mod->init_layout, set_memory_nx);
2086 }
2087 
2088 /* Iterate through all modules and set each module's text as RW */
set_all_modules_text_rw(void)2089 void set_all_modules_text_rw(void)
2090 {
2091 	struct module *mod;
2092 
2093 	if (!rodata_enabled)
2094 		return;
2095 
2096 	mutex_lock(&module_mutex);
2097 	list_for_each_entry_rcu(mod, &modules, list) {
2098 		if (mod->state == MODULE_STATE_UNFORMED)
2099 			continue;
2100 
2101 		frob_text(&mod->core_layout, set_memory_rw);
2102 		frob_text(&mod->init_layout, set_memory_rw);
2103 	}
2104 	mutex_unlock(&module_mutex);
2105 }
2106 
2107 /* Iterate through all modules and set each module's text as RO */
set_all_modules_text_ro(void)2108 void set_all_modules_text_ro(void)
2109 {
2110 	struct module *mod;
2111 
2112 	if (!rodata_enabled)
2113 		return;
2114 
2115 	mutex_lock(&module_mutex);
2116 	list_for_each_entry_rcu(mod, &modules, list) {
2117 		/*
2118 		 * Ignore going modules since it's possible that ro
2119 		 * protection has already been disabled, otherwise we'll
2120 		 * run into protection faults at module deallocation.
2121 		 */
2122 		if (mod->state == MODULE_STATE_UNFORMED ||
2123 			mod->state == MODULE_STATE_GOING)
2124 			continue;
2125 
2126 		frob_text(&mod->core_layout, set_memory_ro);
2127 		frob_text(&mod->init_layout, set_memory_ro);
2128 	}
2129 	mutex_unlock(&module_mutex);
2130 }
2131 #else /* !CONFIG_STRICT_MODULE_RWX */
module_enable_nx(const struct module * mod)2132 static void module_enable_nx(const struct module *mod) { }
2133 #endif /*  CONFIG_STRICT_MODULE_RWX */
module_enable_x(const struct module * mod)2134 static void module_enable_x(const struct module *mod)
2135 {
2136 	frob_text(&mod->core_layout, set_memory_x);
2137 	frob_text(&mod->init_layout, set_memory_x);
2138 }
2139 #else /* !CONFIG_ARCH_HAS_STRICT_MODULE_RWX */
module_enable_nx(const struct module * mod)2140 static void module_enable_nx(const struct module *mod) { }
module_enable_x(const struct module * mod)2141 static void module_enable_x(const struct module *mod) { }
2142 #endif /* CONFIG_ARCH_HAS_STRICT_MODULE_RWX */
2143 
2144 
2145 #ifdef CONFIG_LIVEPATCH
2146 /*
2147  * Persist Elf information about a module. Copy the Elf header,
2148  * section header table, section string table, and symtab section
2149  * index from info to mod->klp_info.
2150  */
copy_module_elf(struct module * mod,struct load_info * info)2151 static int copy_module_elf(struct module *mod, struct load_info *info)
2152 {
2153 	unsigned int size, symndx;
2154 	int ret;
2155 
2156 	size = sizeof(*mod->klp_info);
2157 	mod->klp_info = kmalloc(size, GFP_KERNEL);
2158 	if (mod->klp_info == NULL)
2159 		return -ENOMEM;
2160 
2161 	/* Elf header */
2162 	size = sizeof(mod->klp_info->hdr);
2163 	memcpy(&mod->klp_info->hdr, info->hdr, size);
2164 
2165 	/* Elf section header table */
2166 	size = sizeof(*info->sechdrs) * info->hdr->e_shnum;
2167 	mod->klp_info->sechdrs = kmemdup(info->sechdrs, size, GFP_KERNEL);
2168 	if (mod->klp_info->sechdrs == NULL) {
2169 		ret = -ENOMEM;
2170 		goto free_info;
2171 	}
2172 
2173 	/* Elf section name string table */
2174 	size = info->sechdrs[info->hdr->e_shstrndx].sh_size;
2175 	mod->klp_info->secstrings = kmemdup(info->secstrings, size, GFP_KERNEL);
2176 	if (mod->klp_info->secstrings == NULL) {
2177 		ret = -ENOMEM;
2178 		goto free_sechdrs;
2179 	}
2180 
2181 	/* Elf symbol section index */
2182 	symndx = info->index.sym;
2183 	mod->klp_info->symndx = symndx;
2184 
2185 	/*
2186 	 * For livepatch modules, core_kallsyms.symtab is a complete
2187 	 * copy of the original symbol table. Adjust sh_addr to point
2188 	 * to core_kallsyms.symtab since the copy of the symtab in module
2189 	 * init memory is freed at the end of do_init_module().
2190 	 */
2191 	mod->klp_info->sechdrs[symndx].sh_addr = \
2192 		(unsigned long) mod->core_kallsyms.symtab;
2193 
2194 	return 0;
2195 
2196 free_sechdrs:
2197 	kfree(mod->klp_info->sechdrs);
2198 free_info:
2199 	kfree(mod->klp_info);
2200 	return ret;
2201 }
2202 
free_module_elf(struct module * mod)2203 static void free_module_elf(struct module *mod)
2204 {
2205 	kfree(mod->klp_info->sechdrs);
2206 	kfree(mod->klp_info->secstrings);
2207 	kfree(mod->klp_info);
2208 }
2209 #else /* !CONFIG_LIVEPATCH */
copy_module_elf(struct module * mod,struct load_info * info)2210 static int copy_module_elf(struct module *mod, struct load_info *info)
2211 {
2212 	return 0;
2213 }
2214 
free_module_elf(struct module * mod)2215 static void free_module_elf(struct module *mod)
2216 {
2217 }
2218 #endif /* CONFIG_LIVEPATCH */
2219 
module_memfree(void * module_region)2220 void __weak module_memfree(void *module_region)
2221 {
2222 	/*
2223 	 * This memory may be RO, and freeing RO memory in an interrupt is not
2224 	 * supported by vmalloc.
2225 	 */
2226 	WARN_ON(in_interrupt());
2227 	vfree(module_region);
2228 }
2229 
module_arch_cleanup(struct module * mod)2230 void __weak module_arch_cleanup(struct module *mod)
2231 {
2232 }
2233 
module_arch_freeing_init(struct module * mod)2234 void __weak module_arch_freeing_init(struct module *mod)
2235 {
2236 }
2237 
2238 static void cfi_cleanup(struct module *mod);
2239 
2240 /* Free a module, remove from lists, etc. */
free_module(struct module * mod)2241 static void free_module(struct module *mod)
2242 {
2243 	trace_module_free(mod);
2244 
2245 	mod_sysfs_teardown(mod);
2246 
2247 	/* We leave it in list to prevent duplicate loads, but make sure
2248 	 * that noone uses it while it's being deconstructed. */
2249 	mutex_lock(&module_mutex);
2250 	mod->state = MODULE_STATE_UNFORMED;
2251 	mutex_unlock(&module_mutex);
2252 
2253 	/* Remove dynamic debug info */
2254 	ddebug_remove_module(mod->name);
2255 
2256 	/* Arch-specific cleanup. */
2257 	module_arch_cleanup(mod);
2258 
2259 	/* Module unload stuff */
2260 	module_unload_free(mod);
2261 
2262 	/* Free any allocated parameters. */
2263 	destroy_params(mod->kp, mod->num_kp);
2264 
2265 	if (is_livepatch_module(mod))
2266 		free_module_elf(mod);
2267 
2268 	/* Now we can delete it from the lists */
2269 	mutex_lock(&module_mutex);
2270 	/* Unlink carefully: kallsyms could be walking list. */
2271 	list_del_rcu(&mod->list);
2272 	mod_tree_remove(mod);
2273 	/* Remove this module from bug list, this uses list_del_rcu */
2274 	module_bug_cleanup(mod);
2275 	/* Wait for RCU-sched synchronizing before releasing mod->list and buglist. */
2276 	synchronize_rcu();
2277 	mutex_unlock(&module_mutex);
2278 
2279 	/* Clean up CFI for the module. */
2280 	cfi_cleanup(mod);
2281 
2282 	/* This may be empty, but that's OK */
2283 	module_arch_freeing_init(mod);
2284 	module_memfree(mod->init_layout.base);
2285 	kfree(mod->args);
2286 	percpu_modfree(mod);
2287 
2288 	/* Free lock-classes; relies on the preceding sync_rcu(). */
2289 	lockdep_free_key_range(mod->core_layout.base, mod->core_layout.size);
2290 
2291 	/* Finally, free the core (containing the module structure) */
2292 	module_memfree(mod->core_layout.base);
2293 }
2294 
__symbol_get(const char * symbol)2295 void *__symbol_get(const char *symbol)
2296 {
2297 	struct module *owner;
2298 	enum mod_license license;
2299 	const struct kernel_symbol *sym;
2300 
2301 	preempt_disable();
2302 	sym = find_symbol(symbol, &owner, NULL, &license, true, true);
2303 	if (!sym)
2304 		goto fail;
2305 	if (license != GPL_ONLY) {
2306 		pr_warn("failing symbol_get of non-GPLONLY symbol %s.\n",
2307 			symbol);
2308 		goto fail;
2309 	}
2310 	if (strong_try_module_get(owner))
2311 		sym = NULL;
2312 	preempt_enable();
2313 
2314 	return sym ? (void *)kernel_symbol_value(sym) : NULL;
2315 fail:
2316 	preempt_enable();
2317 	return NULL;
2318 }
2319 
2320 /*
2321  * Ensure that an exported symbol [global namespace] does not already exist
2322  * in the kernel or in some other module's exported symbol table.
2323  *
2324  * You must hold the module_mutex.
2325  */
verify_exported_symbols(struct module * mod)2326 static int verify_exported_symbols(struct module *mod)
2327 {
2328 	unsigned int i;
2329 	struct module *owner;
2330 	const struct kernel_symbol *s;
2331 	struct {
2332 		const struct kernel_symbol *sym;
2333 		unsigned int num;
2334 	} arr[] = {
2335 		{ mod->syms, mod->num_syms },
2336 		{ mod->gpl_syms, mod->num_gpl_syms },
2337 		{ mod->gpl_future_syms, mod->num_gpl_future_syms },
2338 #ifdef CONFIG_UNUSED_SYMBOLS
2339 		{ mod->unused_syms, mod->num_unused_syms },
2340 		{ mod->unused_gpl_syms, mod->num_unused_gpl_syms },
2341 #endif
2342 	};
2343 
2344 	for (i = 0; i < ARRAY_SIZE(arr); i++) {
2345 		for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
2346 			if (find_symbol(kernel_symbol_name(s), &owner, NULL,
2347 					NULL, true, false)) {
2348 				pr_err("%s: exports duplicate symbol %s"
2349 				       " (owned by %s)\n",
2350 				       mod->name, kernel_symbol_name(s),
2351 				       module_name(owner));
2352 				return -ENOEXEC;
2353 			}
2354 		}
2355 	}
2356 	return 0;
2357 }
2358 
ignore_undef_symbol(Elf_Half emachine,const char * name)2359 static bool ignore_undef_symbol(Elf_Half emachine, const char *name)
2360 {
2361 	/*
2362 	 * On x86, PIC code and Clang non-PIC code may have call foo@PLT. GNU as
2363 	 * before 2.37 produces an unreferenced _GLOBAL_OFFSET_TABLE_ on x86-64.
2364 	 * i386 has a similar problem but may not deserve a fix.
2365 	 *
2366 	 * If we ever have to ignore many symbols, consider refactoring the code to
2367 	 * only warn if referenced by a relocation.
2368 	 */
2369 	if (emachine == EM_386 || emachine == EM_X86_64)
2370 		return !strcmp(name, "_GLOBAL_OFFSET_TABLE_");
2371 	return false;
2372 }
2373 
2374 /* Change all symbols so that st_value encodes the pointer directly. */
simplify_symbols(struct module * mod,const struct load_info * info)2375 static int simplify_symbols(struct module *mod, const struct load_info *info)
2376 {
2377 	Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2378 	Elf_Sym *sym = (void *)symsec->sh_addr;
2379 	unsigned long secbase;
2380 	unsigned int i;
2381 	int ret = 0;
2382 	const struct kernel_symbol *ksym;
2383 
2384 	for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
2385 		const char *name = info->strtab + sym[i].st_name;
2386 
2387 		switch (sym[i].st_shndx) {
2388 		case SHN_COMMON:
2389 			/* Ignore common symbols */
2390 			if (!strncmp(name, "__gnu_lto", 9))
2391 				break;
2392 
2393 			/* We compiled with -fno-common.  These are not
2394 			   supposed to happen.  */
2395 			pr_debug("Common symbol: %s\n", name);
2396 			pr_warn("%s: please compile with -fno-common\n",
2397 			       mod->name);
2398 			ret = -ENOEXEC;
2399 			break;
2400 
2401 		case SHN_ABS:
2402 			/* Don't need to do anything */
2403 			pr_debug("Absolute symbol: 0x%08lx\n",
2404 			       (long)sym[i].st_value);
2405 			break;
2406 
2407 		case SHN_LIVEPATCH:
2408 			/* Livepatch symbols are resolved by livepatch */
2409 			break;
2410 
2411 		case SHN_UNDEF:
2412 			ksym = resolve_symbol_wait(mod, info, name);
2413 			/* Ok if resolved.  */
2414 			if (ksym && !IS_ERR(ksym)) {
2415 				sym[i].st_value = kernel_symbol_value(ksym);
2416 				break;
2417 			}
2418 
2419 			/* Ok if weak or ignored.  */
2420 			if (!ksym &&
2421 			    (ELF_ST_BIND(sym[i].st_info) == STB_WEAK ||
2422 			     ignore_undef_symbol(info->hdr->e_machine, name)))
2423 				break;
2424 
2425 			ret = PTR_ERR(ksym) ?: -ENOENT;
2426 			pr_warn("%s: Unknown symbol %s (err %d)\n",
2427 				mod->name, name, ret);
2428 			break;
2429 
2430 		default:
2431 			/* Divert to percpu allocation if a percpu var. */
2432 			if (sym[i].st_shndx == info->index.pcpu)
2433 				secbase = (unsigned long)mod_percpu(mod);
2434 			else
2435 				secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
2436 			sym[i].st_value += secbase;
2437 			break;
2438 		}
2439 	}
2440 
2441 	return ret;
2442 }
2443 
apply_relocations(struct module * mod,const struct load_info * info)2444 static int apply_relocations(struct module *mod, const struct load_info *info)
2445 {
2446 	unsigned int i;
2447 	int err = 0;
2448 
2449 	/* Now do relocations. */
2450 	for (i = 1; i < info->hdr->e_shnum; i++) {
2451 		unsigned int infosec = info->sechdrs[i].sh_info;
2452 
2453 		/* Not a valid relocation section? */
2454 		if (infosec >= info->hdr->e_shnum)
2455 			continue;
2456 
2457 		/* Don't bother with non-allocated sections */
2458 		if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
2459 			continue;
2460 
2461 		/* Livepatch relocation sections are applied by livepatch */
2462 		if (info->sechdrs[i].sh_flags & SHF_RELA_LIVEPATCH)
2463 			continue;
2464 
2465 		if (info->sechdrs[i].sh_type == SHT_REL)
2466 			err = apply_relocate(info->sechdrs, info->strtab,
2467 					     info->index.sym, i, mod);
2468 		else if (info->sechdrs[i].sh_type == SHT_RELA)
2469 			err = apply_relocate_add(info->sechdrs, info->strtab,
2470 						 info->index.sym, i, mod);
2471 		if (err < 0)
2472 			break;
2473 	}
2474 	return err;
2475 }
2476 
2477 /* Additional bytes needed by arch in front of individual sections */
arch_mod_section_prepend(struct module * mod,unsigned int section)2478 unsigned int __weak arch_mod_section_prepend(struct module *mod,
2479 					     unsigned int section)
2480 {
2481 	/* default implementation just returns zero */
2482 	return 0;
2483 }
2484 
2485 /* Update size with this section: return offset. */
get_offset(struct module * mod,unsigned int * size,Elf_Shdr * sechdr,unsigned int section)2486 static long get_offset(struct module *mod, unsigned int *size,
2487 		       Elf_Shdr *sechdr, unsigned int section)
2488 {
2489 	long ret;
2490 
2491 	*size += arch_mod_section_prepend(mod, section);
2492 	ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
2493 	*size = ret + sechdr->sh_size;
2494 	return ret;
2495 }
2496 
2497 /* Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
2498    might -- code, read-only data, read-write data, small data.  Tally
2499    sizes, and place the offsets into sh_entsize fields: high bit means it
2500    belongs in init. */
layout_sections(struct module * mod,struct load_info * info)2501 static void layout_sections(struct module *mod, struct load_info *info)
2502 {
2503 	static unsigned long const masks[][2] = {
2504 		/* NOTE: all executable code must be the first section
2505 		 * in this array; otherwise modify the text_size
2506 		 * finder in the two loops below */
2507 		{ SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
2508 		{ SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
2509 		{ SHF_RO_AFTER_INIT | SHF_ALLOC, ARCH_SHF_SMALL },
2510 		{ SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
2511 		{ ARCH_SHF_SMALL | SHF_ALLOC, 0 }
2512 	};
2513 	unsigned int m, i;
2514 
2515 	for (i = 0; i < info->hdr->e_shnum; i++)
2516 		info->sechdrs[i].sh_entsize = ~0UL;
2517 
2518 	pr_debug("Core section allocation order:\n");
2519 	for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2520 		for (i = 0; i < info->hdr->e_shnum; ++i) {
2521 			Elf_Shdr *s = &info->sechdrs[i];
2522 			const char *sname = info->secstrings + s->sh_name;
2523 
2524 			if ((s->sh_flags & masks[m][0]) != masks[m][0]
2525 			    || (s->sh_flags & masks[m][1])
2526 			    || s->sh_entsize != ~0UL
2527 			    || strstarts(sname, ".init"))
2528 				continue;
2529 			s->sh_entsize = get_offset(mod, &mod->core_layout.size, s, i);
2530 			pr_debug("\t%s\n", sname);
2531 		}
2532 		switch (m) {
2533 		case 0: /* executable */
2534 			mod->core_layout.size = debug_align(mod->core_layout.size);
2535 			mod->core_layout.text_size = mod->core_layout.size;
2536 			break;
2537 		case 1: /* RO: text and ro-data */
2538 			mod->core_layout.size = debug_align(mod->core_layout.size);
2539 			mod->core_layout.ro_size = mod->core_layout.size;
2540 			break;
2541 		case 2: /* RO after init */
2542 			mod->core_layout.size = debug_align(mod->core_layout.size);
2543 			mod->core_layout.ro_after_init_size = mod->core_layout.size;
2544 			break;
2545 		case 4: /* whole core */
2546 			mod->core_layout.size = debug_align(mod->core_layout.size);
2547 			break;
2548 		}
2549 	}
2550 
2551 	pr_debug("Init section allocation order:\n");
2552 	for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2553 		for (i = 0; i < info->hdr->e_shnum; ++i) {
2554 			Elf_Shdr *s = &info->sechdrs[i];
2555 			const char *sname = info->secstrings + s->sh_name;
2556 
2557 			if ((s->sh_flags & masks[m][0]) != masks[m][0]
2558 			    || (s->sh_flags & masks[m][1])
2559 			    || s->sh_entsize != ~0UL
2560 			    || !strstarts(sname, ".init"))
2561 				continue;
2562 			s->sh_entsize = (get_offset(mod, &mod->init_layout.size, s, i)
2563 					 | INIT_OFFSET_MASK);
2564 			pr_debug("\t%s\n", sname);
2565 		}
2566 		switch (m) {
2567 		case 0: /* executable */
2568 			mod->init_layout.size = debug_align(mod->init_layout.size);
2569 			mod->init_layout.text_size = mod->init_layout.size;
2570 			break;
2571 		case 1: /* RO: text and ro-data */
2572 			mod->init_layout.size = debug_align(mod->init_layout.size);
2573 			mod->init_layout.ro_size = mod->init_layout.size;
2574 			break;
2575 		case 2:
2576 			/*
2577 			 * RO after init doesn't apply to init_layout (only
2578 			 * core_layout), so it just takes the value of ro_size.
2579 			 */
2580 			mod->init_layout.ro_after_init_size = mod->init_layout.ro_size;
2581 			break;
2582 		case 4: /* whole init */
2583 			mod->init_layout.size = debug_align(mod->init_layout.size);
2584 			break;
2585 		}
2586 	}
2587 }
2588 
set_license(struct module * mod,const char * license)2589 static void set_license(struct module *mod, const char *license)
2590 {
2591 	if (!license)
2592 		license = "unspecified";
2593 
2594 	if (!license_is_gpl_compatible(license)) {
2595 		if (!test_taint(TAINT_PROPRIETARY_MODULE))
2596 			pr_warn("%s: module license '%s' taints kernel.\n",
2597 				mod->name, license);
2598 		add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2599 				 LOCKDEP_NOW_UNRELIABLE);
2600 	}
2601 }
2602 
2603 /* Parse tag=value strings from .modinfo section */
next_string(char * string,unsigned long * secsize)2604 static char *next_string(char *string, unsigned long *secsize)
2605 {
2606 	/* Skip non-zero chars */
2607 	while (string[0]) {
2608 		string++;
2609 		if ((*secsize)-- <= 1)
2610 			return NULL;
2611 	}
2612 
2613 	/* Skip any zero padding. */
2614 	while (!string[0]) {
2615 		string++;
2616 		if ((*secsize)-- <= 1)
2617 			return NULL;
2618 	}
2619 	return string;
2620 }
2621 
get_next_modinfo(const struct load_info * info,const char * tag,char * prev)2622 static char *get_next_modinfo(const struct load_info *info, const char *tag,
2623 			      char *prev)
2624 {
2625 	char *p;
2626 	unsigned int taglen = strlen(tag);
2627 	Elf_Shdr *infosec = &info->sechdrs[info->index.info];
2628 	unsigned long size = infosec->sh_size;
2629 
2630 	/*
2631 	 * get_modinfo() calls made before rewrite_section_headers()
2632 	 * must use sh_offset, as sh_addr isn't set!
2633 	 */
2634 	char *modinfo = (char *)info->hdr + infosec->sh_offset;
2635 
2636 	if (prev) {
2637 		size -= prev - modinfo;
2638 		modinfo = next_string(prev, &size);
2639 	}
2640 
2641 	for (p = modinfo; p; p = next_string(p, &size)) {
2642 		if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
2643 			return p + taglen + 1;
2644 	}
2645 	return NULL;
2646 }
2647 
get_modinfo(const struct load_info * info,const char * tag)2648 static char *get_modinfo(const struct load_info *info, const char *tag)
2649 {
2650 	return get_next_modinfo(info, tag, NULL);
2651 }
2652 
setup_modinfo(struct module * mod,struct load_info * info)2653 static void setup_modinfo(struct module *mod, struct load_info *info)
2654 {
2655 	struct module_attribute *attr;
2656 	int i;
2657 
2658 	for (i = 0; (attr = modinfo_attrs[i]); i++) {
2659 		if (attr->setup)
2660 			attr->setup(mod, get_modinfo(info, attr->attr.name));
2661 	}
2662 }
2663 
free_modinfo(struct module * mod)2664 static void free_modinfo(struct module *mod)
2665 {
2666 	struct module_attribute *attr;
2667 	int i;
2668 
2669 	for (i = 0; (attr = modinfo_attrs[i]); i++) {
2670 		if (attr->free)
2671 			attr->free(mod);
2672 	}
2673 }
2674 
2675 #ifdef CONFIG_KALLSYMS
2676 
2677 /* Lookup exported symbol in given range of kernel_symbols */
lookup_exported_symbol(const char * name,const struct kernel_symbol * start,const struct kernel_symbol * stop)2678 static const struct kernel_symbol *lookup_exported_symbol(const char *name,
2679 							  const struct kernel_symbol *start,
2680 							  const struct kernel_symbol *stop)
2681 {
2682 	return bsearch(name, start, stop - start,
2683 			sizeof(struct kernel_symbol), cmp_name);
2684 }
2685 
is_exported(const char * name,unsigned long value,const struct module * mod)2686 static int is_exported(const char *name, unsigned long value,
2687 		       const struct module *mod)
2688 {
2689 	const struct kernel_symbol *ks;
2690 	if (!mod)
2691 		ks = lookup_exported_symbol(name, __start___ksymtab, __stop___ksymtab);
2692 	else
2693 		ks = lookup_exported_symbol(name, mod->syms, mod->syms + mod->num_syms);
2694 
2695 	return ks != NULL && kernel_symbol_value(ks) == value;
2696 }
2697 
2698 /* As per nm */
elf_type(const Elf_Sym * sym,const struct load_info * info)2699 static char elf_type(const Elf_Sym *sym, const struct load_info *info)
2700 {
2701 	const Elf_Shdr *sechdrs = info->sechdrs;
2702 
2703 	if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
2704 		if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT)
2705 			return 'v';
2706 		else
2707 			return 'w';
2708 	}
2709 	if (sym->st_shndx == SHN_UNDEF)
2710 		return 'U';
2711 	if (sym->st_shndx == SHN_ABS || sym->st_shndx == info->index.pcpu)
2712 		return 'a';
2713 	if (sym->st_shndx >= SHN_LORESERVE)
2714 		return '?';
2715 	if (sechdrs[sym->st_shndx].sh_flags & SHF_EXECINSTR)
2716 		return 't';
2717 	if (sechdrs[sym->st_shndx].sh_flags & SHF_ALLOC
2718 	    && sechdrs[sym->st_shndx].sh_type != SHT_NOBITS) {
2719 		if (!(sechdrs[sym->st_shndx].sh_flags & SHF_WRITE))
2720 			return 'r';
2721 		else if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2722 			return 'g';
2723 		else
2724 			return 'd';
2725 	}
2726 	if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
2727 		if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2728 			return 's';
2729 		else
2730 			return 'b';
2731 	}
2732 	if (strstarts(info->secstrings + sechdrs[sym->st_shndx].sh_name,
2733 		      ".debug")) {
2734 		return 'n';
2735 	}
2736 	return '?';
2737 }
2738 
is_core_symbol(const Elf_Sym * src,const Elf_Shdr * sechdrs,unsigned int shnum,unsigned int pcpundx)2739 static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
2740 			unsigned int shnum, unsigned int pcpundx)
2741 {
2742 	const Elf_Shdr *sec;
2743 
2744 	if (src->st_shndx == SHN_UNDEF
2745 	    || src->st_shndx >= shnum
2746 	    || !src->st_name)
2747 		return false;
2748 
2749 #ifdef CONFIG_KALLSYMS_ALL
2750 	if (src->st_shndx == pcpundx)
2751 		return true;
2752 #endif
2753 
2754 	sec = sechdrs + src->st_shndx;
2755 	if (!(sec->sh_flags & SHF_ALLOC)
2756 #ifndef CONFIG_KALLSYMS_ALL
2757 	    || !(sec->sh_flags & SHF_EXECINSTR)
2758 #endif
2759 	    || (sec->sh_entsize & INIT_OFFSET_MASK))
2760 		return false;
2761 
2762 	return true;
2763 }
2764 
2765 /*
2766  * We only allocate and copy the strings needed by the parts of symtab
2767  * we keep.  This is simple, but has the effect of making multiple
2768  * copies of duplicates.  We could be more sophisticated, see
2769  * linux-kernel thread starting with
2770  * <73defb5e4bca04a6431392cc341112b1@localhost>.
2771  */
layout_symtab(struct module * mod,struct load_info * info)2772 static void layout_symtab(struct module *mod, struct load_info *info)
2773 {
2774 	Elf_Shdr *symsect = info->sechdrs + info->index.sym;
2775 	Elf_Shdr *strsect = info->sechdrs + info->index.str;
2776 	const Elf_Sym *src;
2777 	unsigned int i, nsrc, ndst, strtab_size = 0;
2778 
2779 	/* Put symbol section at end of init part of module. */
2780 	symsect->sh_flags |= SHF_ALLOC;
2781 	symsect->sh_entsize = get_offset(mod, &mod->init_layout.size, symsect,
2782 					 info->index.sym) | INIT_OFFSET_MASK;
2783 	pr_debug("\t%s\n", info->secstrings + symsect->sh_name);
2784 
2785 	src = (void *)info->hdr + symsect->sh_offset;
2786 	nsrc = symsect->sh_size / sizeof(*src);
2787 
2788 	/* Compute total space required for the core symbols' strtab. */
2789 	for (ndst = i = 0; i < nsrc; i++) {
2790 		if (i == 0 || is_livepatch_module(mod) ||
2791 		    is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum,
2792 				   info->index.pcpu)) {
2793 			strtab_size += strlen(&info->strtab[src[i].st_name])+1;
2794 			ndst++;
2795 		}
2796 	}
2797 
2798 	/* Append room for core symbols at end of core part. */
2799 	info->symoffs = ALIGN(mod->core_layout.size, symsect->sh_addralign ?: 1);
2800 	info->stroffs = mod->core_layout.size = info->symoffs + ndst * sizeof(Elf_Sym);
2801 	mod->core_layout.size += strtab_size;
2802 	info->core_typeoffs = mod->core_layout.size;
2803 	mod->core_layout.size += ndst * sizeof(char);
2804 	mod->core_layout.size = debug_align(mod->core_layout.size);
2805 
2806 	/* Put string table section at end of init part of module. */
2807 	strsect->sh_flags |= SHF_ALLOC;
2808 	strsect->sh_entsize = get_offset(mod, &mod->init_layout.size, strsect,
2809 					 info->index.str) | INIT_OFFSET_MASK;
2810 	pr_debug("\t%s\n", info->secstrings + strsect->sh_name);
2811 
2812 	/* We'll tack temporary mod_kallsyms on the end. */
2813 	mod->init_layout.size = ALIGN(mod->init_layout.size,
2814 				      __alignof__(struct mod_kallsyms));
2815 	info->mod_kallsyms_init_off = mod->init_layout.size;
2816 	mod->init_layout.size += sizeof(struct mod_kallsyms);
2817 	info->init_typeoffs = mod->init_layout.size;
2818 	mod->init_layout.size += nsrc * sizeof(char);
2819 	mod->init_layout.size = debug_align(mod->init_layout.size);
2820 }
2821 
2822 /*
2823  * We use the full symtab and strtab which layout_symtab arranged to
2824  * be appended to the init section.  Later we switch to the cut-down
2825  * core-only ones.
2826  */
add_kallsyms(struct module * mod,const struct load_info * info)2827 static void add_kallsyms(struct module *mod, const struct load_info *info)
2828 {
2829 	unsigned int i, ndst;
2830 	const Elf_Sym *src;
2831 	Elf_Sym *dst;
2832 	char *s;
2833 	Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2834 
2835 	/* Set up to point into init section. */
2836 	mod->kallsyms = mod->init_layout.base + info->mod_kallsyms_init_off;
2837 
2838 	mod->kallsyms->symtab = (void *)symsec->sh_addr;
2839 	mod->kallsyms->num_symtab = symsec->sh_size / sizeof(Elf_Sym);
2840 	/* Make sure we get permanent strtab: don't use info->strtab. */
2841 	mod->kallsyms->strtab = (void *)info->sechdrs[info->index.str].sh_addr;
2842 	mod->kallsyms->typetab = mod->init_layout.base + info->init_typeoffs;
2843 
2844 	/*
2845 	 * Now populate the cut down core kallsyms for after init
2846 	 * and set types up while we still have access to sections.
2847 	 */
2848 	mod->core_kallsyms.symtab = dst = mod->core_layout.base + info->symoffs;
2849 	mod->core_kallsyms.strtab = s = mod->core_layout.base + info->stroffs;
2850 	mod->core_kallsyms.typetab = mod->core_layout.base + info->core_typeoffs;
2851 	src = mod->kallsyms->symtab;
2852 	for (ndst = i = 0; i < mod->kallsyms->num_symtab; i++) {
2853 		mod->kallsyms->typetab[i] = elf_type(src + i, info);
2854 		if (i == 0 || is_livepatch_module(mod) ||
2855 		    is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum,
2856 				   info->index.pcpu)) {
2857 			mod->core_kallsyms.typetab[ndst] =
2858 			    mod->kallsyms->typetab[i];
2859 			dst[ndst] = src[i];
2860 			dst[ndst++].st_name = s - mod->core_kallsyms.strtab;
2861 			s += strlcpy(s, &mod->kallsyms->strtab[src[i].st_name],
2862 				     KSYM_NAME_LEN) + 1;
2863 		}
2864 	}
2865 	mod->core_kallsyms.num_symtab = ndst;
2866 }
2867 #else
layout_symtab(struct module * mod,struct load_info * info)2868 static inline void layout_symtab(struct module *mod, struct load_info *info)
2869 {
2870 }
2871 
add_kallsyms(struct module * mod,const struct load_info * info)2872 static void add_kallsyms(struct module *mod, const struct load_info *info)
2873 {
2874 }
2875 #endif /* CONFIG_KALLSYMS */
2876 
dynamic_debug_setup(struct module * mod,struct _ddebug * debug,unsigned int num)2877 static void dynamic_debug_setup(struct module *mod, struct _ddebug *debug, unsigned int num)
2878 {
2879 	if (!debug)
2880 		return;
2881 	ddebug_add_module(debug, num, mod->name);
2882 }
2883 
dynamic_debug_remove(struct module * mod,struct _ddebug * debug)2884 static void dynamic_debug_remove(struct module *mod, struct _ddebug *debug)
2885 {
2886 	if (debug)
2887 		ddebug_remove_module(mod->name);
2888 }
2889 
module_alloc(unsigned long size)2890 void * __weak module_alloc(unsigned long size)
2891 {
2892 	return vmalloc_exec(size);
2893 }
2894 
module_exit_section(const char * name)2895 bool __weak module_exit_section(const char *name)
2896 {
2897 	return strstarts(name, ".exit");
2898 }
2899 
2900 #ifdef CONFIG_DEBUG_KMEMLEAK
kmemleak_load_module(const struct module * mod,const struct load_info * info)2901 static void kmemleak_load_module(const struct module *mod,
2902 				 const struct load_info *info)
2903 {
2904 	unsigned int i;
2905 
2906 	/* only scan the sections containing data */
2907 	kmemleak_scan_area(mod, sizeof(struct module), GFP_KERNEL);
2908 
2909 	for (i = 1; i < info->hdr->e_shnum; i++) {
2910 		/* Scan all writable sections that's not executable */
2911 		if (!(info->sechdrs[i].sh_flags & SHF_ALLOC) ||
2912 		    !(info->sechdrs[i].sh_flags & SHF_WRITE) ||
2913 		    (info->sechdrs[i].sh_flags & SHF_EXECINSTR))
2914 			continue;
2915 
2916 		kmemleak_scan_area((void *)info->sechdrs[i].sh_addr,
2917 				   info->sechdrs[i].sh_size, GFP_KERNEL);
2918 	}
2919 }
2920 #else
kmemleak_load_module(const struct module * mod,const struct load_info * info)2921 static inline void kmemleak_load_module(const struct module *mod,
2922 					const struct load_info *info)
2923 {
2924 }
2925 #endif
2926 
2927 #ifdef CONFIG_MODULE_SIG
module_sig_check(struct load_info * info,int flags)2928 static int module_sig_check(struct load_info *info, int flags)
2929 {
2930 	int err = -ENODATA;
2931 	const unsigned long markerlen = sizeof(MODULE_SIG_STRING) - 1;
2932 	const char *reason;
2933 	const void *mod = info->hdr;
2934 
2935 	/*
2936 	 * Require flags == 0, as a module with version information
2937 	 * removed is no longer the module that was signed
2938 	 */
2939 	if (flags == 0 &&
2940 	    info->len > markerlen &&
2941 	    memcmp(mod + info->len - markerlen, MODULE_SIG_STRING, markerlen) == 0) {
2942 		/* We truncate the module to discard the signature */
2943 		info->len -= markerlen;
2944 		err = mod_verify_sig(mod, info);
2945 	}
2946 
2947 	switch (err) {
2948 	case 0:
2949 		info->sig_ok = true;
2950 		return 0;
2951 
2952 		/* We don't permit modules to be loaded into trusted kernels
2953 		 * without a valid signature on them, but if we're not
2954 		 * enforcing, certain errors are non-fatal.
2955 		 */
2956 	case -ENODATA:
2957 		reason = "unsigned module";
2958 		break;
2959 	case -ENOPKG:
2960 		reason = "module with unsupported crypto";
2961 		break;
2962 	case -ENOKEY:
2963 		reason = "module with unavailable key";
2964 		break;
2965 
2966 		/* All other errors are fatal, including nomem, unparseable
2967 		 * signatures and signature check failures - even if signatures
2968 		 * aren't required.
2969 		 */
2970 	default:
2971 		return err;
2972 	}
2973 
2974 	if (is_module_sig_enforced()) {
2975 		pr_notice("Loading of %s is rejected\n", reason);
2976 		return -EKEYREJECTED;
2977 	}
2978 
2979 	return security_locked_down(LOCKDOWN_MODULE_SIGNATURE);
2980 }
2981 #else /* !CONFIG_MODULE_SIG */
module_sig_check(struct load_info * info,int flags)2982 static int module_sig_check(struct load_info *info, int flags)
2983 {
2984 	return 0;
2985 }
2986 #endif /* !CONFIG_MODULE_SIG */
2987 
validate_section_offset(struct load_info * info,Elf_Shdr * shdr)2988 static int validate_section_offset(struct load_info *info, Elf_Shdr *shdr)
2989 {
2990 	unsigned long secend;
2991 
2992 	/*
2993 	 * Check for both overflow and offset/size being
2994 	 * too large.
2995 	 */
2996 	secend = shdr->sh_offset + shdr->sh_size;
2997 	if (secend < shdr->sh_offset || secend > info->len)
2998 		return -ENOEXEC;
2999 
3000 	return 0;
3001 }
3002 
3003 /*
3004  * Sanity checks against invalid binaries, wrong arch, weird elf version.
3005  *
3006  * Also do basic validity checks against section offsets and sizes, the
3007  * section name string table, and the indices used for it (sh_name).
3008  */
elf_validity_check(struct load_info * info)3009 static int elf_validity_check(struct load_info *info)
3010 {
3011 	unsigned int i;
3012 	Elf_Shdr *shdr, *strhdr;
3013 	int err;
3014 
3015 	if (info->len < sizeof(*(info->hdr)))
3016 		return -ENOEXEC;
3017 
3018 	if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0
3019 	    || info->hdr->e_type != ET_REL
3020 	    || !elf_check_arch(info->hdr)
3021 	    || info->hdr->e_shentsize != sizeof(Elf_Shdr))
3022 		return -ENOEXEC;
3023 
3024 	/*
3025 	 * e_shnum is 16 bits, and sizeof(Elf_Shdr) is
3026 	 * known and small. So e_shnum * sizeof(Elf_Shdr)
3027 	 * will not overflow unsigned long on any platform.
3028 	 */
3029 	if (info->hdr->e_shoff >= info->len
3030 	    || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
3031 		info->len - info->hdr->e_shoff))
3032 		return -ENOEXEC;
3033 
3034 	info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
3035 
3036 	/*
3037 	 * Verify if the section name table index is valid.
3038 	 */
3039 	if (info->hdr->e_shstrndx == SHN_UNDEF
3040 	    || info->hdr->e_shstrndx >= info->hdr->e_shnum)
3041 		return -ENOEXEC;
3042 
3043 	strhdr = &info->sechdrs[info->hdr->e_shstrndx];
3044 	err = validate_section_offset(info, strhdr);
3045 	if (err < 0)
3046 		return err;
3047 
3048 	/*
3049 	 * The section name table must be NUL-terminated, as required
3050 	 * by the spec. This makes strcmp and pr_* calls that access
3051 	 * strings in the section safe.
3052 	 */
3053 	info->secstrings = (void *)info->hdr + strhdr->sh_offset;
3054 	if (info->secstrings[strhdr->sh_size - 1] != '\0')
3055 		return -ENOEXEC;
3056 
3057 	/*
3058 	 * The code assumes that section 0 has a length of zero and
3059 	 * an addr of zero, so check for it.
3060 	 */
3061 	if (info->sechdrs[0].sh_type != SHT_NULL
3062 	    || info->sechdrs[0].sh_size != 0
3063 	    || info->sechdrs[0].sh_addr != 0)
3064 		return -ENOEXEC;
3065 
3066 	for (i = 1; i < info->hdr->e_shnum; i++) {
3067 		shdr = &info->sechdrs[i];
3068 		switch (shdr->sh_type) {
3069 		case SHT_NULL:
3070 		case SHT_NOBITS:
3071 			continue;
3072 		case SHT_SYMTAB:
3073 			if (shdr->sh_link == SHN_UNDEF
3074 			    || shdr->sh_link >= info->hdr->e_shnum)
3075 				return -ENOEXEC;
3076 			fallthrough;
3077 		default:
3078 			err = validate_section_offset(info, shdr);
3079 			if (err < 0) {
3080 				pr_err("Invalid ELF section in module (section %u type %u)\n",
3081 					i, shdr->sh_type);
3082 				return err;
3083 			}
3084 
3085 			if (shdr->sh_flags & SHF_ALLOC) {
3086 				if (shdr->sh_name >= strhdr->sh_size) {
3087 					pr_err("Invalid ELF section name in module (section %u type %u)\n",
3088 					       i, shdr->sh_type);
3089 					return -ENOEXEC;
3090 				}
3091 			}
3092 			break;
3093 		}
3094 	}
3095 
3096 	return 0;
3097 }
3098 
3099 #define COPY_CHUNK_SIZE (16*PAGE_SIZE)
3100 
copy_chunked_from_user(void * dst,const void __user * usrc,unsigned long len)3101 static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len)
3102 {
3103 	do {
3104 		unsigned long n = min(len, COPY_CHUNK_SIZE);
3105 
3106 		if (copy_from_user(dst, usrc, n) != 0)
3107 			return -EFAULT;
3108 		cond_resched();
3109 		dst += n;
3110 		usrc += n;
3111 		len -= n;
3112 	} while (len);
3113 	return 0;
3114 }
3115 
3116 #ifdef CONFIG_LIVEPATCH
check_modinfo_livepatch(struct module * mod,struct load_info * info)3117 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
3118 {
3119 	if (get_modinfo(info, "livepatch")) {
3120 		mod->klp = true;
3121 		add_taint_module(mod, TAINT_LIVEPATCH, LOCKDEP_STILL_OK);
3122 		pr_notice_once("%s: tainting kernel with TAINT_LIVEPATCH\n",
3123 			       mod->name);
3124 	}
3125 
3126 	return 0;
3127 }
3128 #else /* !CONFIG_LIVEPATCH */
check_modinfo_livepatch(struct module * mod,struct load_info * info)3129 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
3130 {
3131 	if (get_modinfo(info, "livepatch")) {
3132 		pr_err("%s: module is marked as livepatch module, but livepatch support is disabled",
3133 		       mod->name);
3134 		return -ENOEXEC;
3135 	}
3136 
3137 	return 0;
3138 }
3139 #endif /* CONFIG_LIVEPATCH */
3140 
check_modinfo_retpoline(struct module * mod,struct load_info * info)3141 static void check_modinfo_retpoline(struct module *mod, struct load_info *info)
3142 {
3143 	if (retpoline_module_ok(get_modinfo(info, "retpoline")))
3144 		return;
3145 
3146 	pr_warn("%s: loading module not compiled with retpoline compiler.\n",
3147 		mod->name);
3148 }
3149 
3150 /* Sets info->hdr and info->len. */
copy_module_from_user(const void __user * umod,unsigned long len,struct load_info * info)3151 static int copy_module_from_user(const void __user *umod, unsigned long len,
3152 				  struct load_info *info)
3153 {
3154 	int err;
3155 
3156 	info->len = len;
3157 	if (info->len < sizeof(*(info->hdr)))
3158 		return -ENOEXEC;
3159 
3160 	err = security_kernel_load_data(LOADING_MODULE);
3161 	if (err)
3162 		return err;
3163 
3164 	/* Suck in entire file: we'll want most of it. */
3165 	info->hdr = __vmalloc(info->len,
3166 			GFP_KERNEL | __GFP_NOWARN, PAGE_KERNEL);
3167 	if (!info->hdr)
3168 		return -ENOMEM;
3169 
3170 	if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) {
3171 		vfree(info->hdr);
3172 		return -EFAULT;
3173 	}
3174 
3175 	return 0;
3176 }
3177 
free_copy(struct load_info * info)3178 static void free_copy(struct load_info *info)
3179 {
3180 	vfree(info->hdr);
3181 }
3182 
rewrite_section_headers(struct load_info * info,int flags)3183 static int rewrite_section_headers(struct load_info *info, int flags)
3184 {
3185 	unsigned int i;
3186 
3187 	/* This should always be true, but let's be sure. */
3188 	info->sechdrs[0].sh_addr = 0;
3189 
3190 	for (i = 1; i < info->hdr->e_shnum; i++) {
3191 		Elf_Shdr *shdr = &info->sechdrs[i];
3192 
3193 		/* Mark all sections sh_addr with their address in the
3194 		   temporary image. */
3195 		shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
3196 
3197 #ifndef CONFIG_MODULE_UNLOAD
3198 		/* Don't load .exit sections */
3199 		if (module_exit_section(info->secstrings+shdr->sh_name))
3200 			shdr->sh_flags &= ~(unsigned long)SHF_ALLOC;
3201 #endif
3202 	}
3203 
3204 	/* Track but don't keep modinfo and version sections. */
3205 	info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
3206 	info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
3207 
3208 	return 0;
3209 }
3210 
3211 /*
3212  * Set up our basic convenience variables (pointers to section headers,
3213  * search for module section index etc), and do some basic section
3214  * verification.
3215  *
3216  * Set info->mod to the temporary copy of the module in info->hdr. The final one
3217  * will be allocated in move_module().
3218  */
setup_load_info(struct load_info * info,int flags)3219 static int setup_load_info(struct load_info *info, int flags)
3220 {
3221 	unsigned int i;
3222 
3223 	/* Try to find a name early so we can log errors with a module name */
3224 	info->index.info = find_sec(info, ".modinfo");
3225 	if (info->index.info)
3226 		info->name = get_modinfo(info, "name");
3227 
3228 	/* Find internal symbols and strings. */
3229 	for (i = 1; i < info->hdr->e_shnum; i++) {
3230 		if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
3231 			info->index.sym = i;
3232 			info->index.str = info->sechdrs[i].sh_link;
3233 			info->strtab = (char *)info->hdr
3234 				+ info->sechdrs[info->index.str].sh_offset;
3235 			break;
3236 		}
3237 	}
3238 
3239 	if (info->index.sym == 0) {
3240 		pr_warn("%s: module has no symbols (stripped?)\n",
3241 			info->name ?: "(missing .modinfo section or name field)");
3242 		return -ENOEXEC;
3243 	}
3244 
3245 	info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
3246 	if (!info->index.mod) {
3247 		pr_warn("%s: No module found in object\n",
3248 			info->name ?: "(missing .modinfo section or name field)");
3249 		return -ENOEXEC;
3250 	}
3251 	/* This is temporary: point mod into copy of data. */
3252 	info->mod = (void *)info->hdr + info->sechdrs[info->index.mod].sh_offset;
3253 
3254 	/*
3255 	 * If we didn't load the .modinfo 'name' field earlier, fall back to
3256 	 * on-disk struct mod 'name' field.
3257 	 */
3258 	if (!info->name)
3259 		info->name = info->mod->name;
3260 
3261 	if (flags & MODULE_INIT_IGNORE_MODVERSIONS)
3262 		info->index.vers = 0; /* Pretend no __versions section! */
3263 	else
3264 		info->index.vers = find_sec(info, "__versions");
3265 
3266 	info->index.pcpu = find_pcpusec(info);
3267 
3268 	return 0;
3269 }
3270 
check_modinfo(struct module * mod,struct load_info * info,int flags)3271 static int check_modinfo(struct module *mod, struct load_info *info, int flags)
3272 {
3273 	const char *modmagic = get_modinfo(info, "vermagic");
3274 	int err;
3275 
3276 	if (flags & MODULE_INIT_IGNORE_VERMAGIC)
3277 		modmagic = NULL;
3278 
3279 	/* This is allowed: modprobe --force will invalidate it. */
3280 	if (!modmagic) {
3281 		err = try_to_force_load(mod, "bad vermagic");
3282 		if (err)
3283 			return err;
3284 	} else if (!same_magic(modmagic, vermagic, info->index.vers)) {
3285 		pr_err("%s: version magic '%s' should be '%s'\n",
3286 		       info->name, modmagic, vermagic);
3287 		return -ENOEXEC;
3288 	}
3289 
3290 	if (!get_modinfo(info, "intree")) {
3291 		if (!test_taint(TAINT_OOT_MODULE))
3292 			pr_warn("%s: loading out-of-tree module taints kernel.\n",
3293 				mod->name);
3294 		add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
3295 	}
3296 
3297 	check_modinfo_retpoline(mod, info);
3298 
3299 	if (get_modinfo(info, "staging")) {
3300 		add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
3301 		pr_warn("%s: module is from the staging directory, the quality "
3302 			"is unknown, you have been warned.\n", mod->name);
3303 	}
3304 
3305 	err = check_modinfo_livepatch(mod, info);
3306 	if (err)
3307 		return err;
3308 
3309 	/* Set up license info based on the info section */
3310 	set_license(mod, get_modinfo(info, "license"));
3311 
3312 	return 0;
3313 }
3314 
find_module_sections(struct module * mod,struct load_info * info)3315 static int find_module_sections(struct module *mod, struct load_info *info)
3316 {
3317 	mod->kp = section_objs(info, "__param",
3318 			       sizeof(*mod->kp), &mod->num_kp);
3319 	mod->syms = section_objs(info, "__ksymtab",
3320 				 sizeof(*mod->syms), &mod->num_syms);
3321 	mod->crcs = section_addr(info, "__kcrctab");
3322 	mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
3323 				     sizeof(*mod->gpl_syms),
3324 				     &mod->num_gpl_syms);
3325 	mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
3326 	mod->gpl_future_syms = section_objs(info,
3327 					    "__ksymtab_gpl_future",
3328 					    sizeof(*mod->gpl_future_syms),
3329 					    &mod->num_gpl_future_syms);
3330 	mod->gpl_future_crcs = section_addr(info, "__kcrctab_gpl_future");
3331 
3332 #ifdef CONFIG_UNUSED_SYMBOLS
3333 	mod->unused_syms = section_objs(info, "__ksymtab_unused",
3334 					sizeof(*mod->unused_syms),
3335 					&mod->num_unused_syms);
3336 	mod->unused_crcs = section_addr(info, "__kcrctab_unused");
3337 	mod->unused_gpl_syms = section_objs(info, "__ksymtab_unused_gpl",
3338 					    sizeof(*mod->unused_gpl_syms),
3339 					    &mod->num_unused_gpl_syms);
3340 	mod->unused_gpl_crcs = section_addr(info, "__kcrctab_unused_gpl");
3341 #endif
3342 #ifdef CONFIG_CONSTRUCTORS
3343 	mod->ctors = section_objs(info, ".ctors",
3344 				  sizeof(*mod->ctors), &mod->num_ctors);
3345 	if (!mod->ctors)
3346 		mod->ctors = section_objs(info, ".init_array",
3347 				sizeof(*mod->ctors), &mod->num_ctors);
3348 	else if (find_sec(info, ".init_array")) {
3349 		/*
3350 		 * This shouldn't happen with same compiler and binutils
3351 		 * building all parts of the module.
3352 		 */
3353 		pr_warn("%s: has both .ctors and .init_array.\n",
3354 		       mod->name);
3355 		return -EINVAL;
3356 	}
3357 #endif
3358 
3359 #ifdef CONFIG_TRACEPOINTS
3360 	mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
3361 					     sizeof(*mod->tracepoints_ptrs),
3362 					     &mod->num_tracepoints);
3363 #endif
3364 #ifdef CONFIG_TREE_SRCU
3365 	mod->srcu_struct_ptrs = section_objs(info, "___srcu_struct_ptrs",
3366 					     sizeof(*mod->srcu_struct_ptrs),
3367 					     &mod->num_srcu_structs);
3368 #endif
3369 #ifdef CONFIG_BPF_EVENTS
3370 	mod->bpf_raw_events = section_objs(info, "__bpf_raw_tp_map",
3371 					   sizeof(*mod->bpf_raw_events),
3372 					   &mod->num_bpf_raw_events);
3373 #endif
3374 #ifdef CONFIG_JUMP_LABEL
3375 	mod->jump_entries = section_objs(info, "__jump_table",
3376 					sizeof(*mod->jump_entries),
3377 					&mod->num_jump_entries);
3378 #endif
3379 #ifdef CONFIG_EVENT_TRACING
3380 	mod->trace_events = section_objs(info, "_ftrace_events",
3381 					 sizeof(*mod->trace_events),
3382 					 &mod->num_trace_events);
3383 	mod->trace_evals = section_objs(info, "_ftrace_eval_map",
3384 					sizeof(*mod->trace_evals),
3385 					&mod->num_trace_evals);
3386 #endif
3387 #ifdef CONFIG_TRACING
3388 	mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
3389 					 sizeof(*mod->trace_bprintk_fmt_start),
3390 					 &mod->num_trace_bprintk_fmt);
3391 #endif
3392 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
3393 	/* sechdrs[0].sh_size is always zero */
3394 	mod->ftrace_callsites = section_objs(info, FTRACE_CALLSITE_SECTION,
3395 					     sizeof(*mod->ftrace_callsites),
3396 					     &mod->num_ftrace_callsites);
3397 #endif
3398 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
3399 	mod->ei_funcs = section_objs(info, "_error_injection_whitelist",
3400 					    sizeof(*mod->ei_funcs),
3401 					    &mod->num_ei_funcs);
3402 #endif
3403 	mod->extable = section_objs(info, "__ex_table",
3404 				    sizeof(*mod->extable), &mod->num_exentries);
3405 
3406 	if (section_addr(info, "__obsparm"))
3407 		pr_warn("%s: Ignoring obsolete parameters\n", mod->name);
3408 
3409 	info->debug = section_objs(info, "__verbose",
3410 				   sizeof(*info->debug), &info->num_debug);
3411 
3412 	return 0;
3413 }
3414 
move_module(struct module * mod,struct load_info * info)3415 static int move_module(struct module *mod, struct load_info *info)
3416 {
3417 	int i;
3418 	void *ptr;
3419 
3420 	/* Do the allocs. */
3421 	ptr = module_alloc(mod->core_layout.size);
3422 	/*
3423 	 * The pointer to this block is stored in the module structure
3424 	 * which is inside the block. Just mark it as not being a
3425 	 * leak.
3426 	 */
3427 	kmemleak_not_leak(ptr);
3428 	if (!ptr)
3429 		return -ENOMEM;
3430 
3431 	memset(ptr, 0, mod->core_layout.size);
3432 	mod->core_layout.base = ptr;
3433 
3434 	if (mod->init_layout.size) {
3435 		ptr = module_alloc(mod->init_layout.size);
3436 		/*
3437 		 * The pointer to this block is stored in the module structure
3438 		 * which is inside the block. This block doesn't need to be
3439 		 * scanned as it contains data and code that will be freed
3440 		 * after the module is initialized.
3441 		 */
3442 		kmemleak_ignore(ptr);
3443 		if (!ptr) {
3444 			module_memfree(mod->core_layout.base);
3445 			return -ENOMEM;
3446 		}
3447 		memset(ptr, 0, mod->init_layout.size);
3448 		mod->init_layout.base = ptr;
3449 	} else
3450 		mod->init_layout.base = NULL;
3451 
3452 	/* Transfer each section which specifies SHF_ALLOC */
3453 	pr_debug("final section addresses:\n");
3454 	for (i = 0; i < info->hdr->e_shnum; i++) {
3455 		void *dest;
3456 		Elf_Shdr *shdr = &info->sechdrs[i];
3457 
3458 		if (!(shdr->sh_flags & SHF_ALLOC))
3459 			continue;
3460 
3461 		if (shdr->sh_entsize & INIT_OFFSET_MASK)
3462 			dest = mod->init_layout.base
3463 				+ (shdr->sh_entsize & ~INIT_OFFSET_MASK);
3464 		else
3465 			dest = mod->core_layout.base + shdr->sh_entsize;
3466 
3467 		if (shdr->sh_type != SHT_NOBITS)
3468 			memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
3469 		/* Update sh_addr to point to copy in image. */
3470 		shdr->sh_addr = (unsigned long)dest;
3471 		pr_debug("\t0x%lx %s\n",
3472 			 (long)shdr->sh_addr, info->secstrings + shdr->sh_name);
3473 	}
3474 
3475 	return 0;
3476 }
3477 
check_module_license_and_versions(struct module * mod)3478 static int check_module_license_and_versions(struct module *mod)
3479 {
3480 	int prev_taint = test_taint(TAINT_PROPRIETARY_MODULE);
3481 
3482 	/*
3483 	 * ndiswrapper is under GPL by itself, but loads proprietary modules.
3484 	 * Don't use add_taint_module(), as it would prevent ndiswrapper from
3485 	 * using GPL-only symbols it needs.
3486 	 */
3487 	if (strcmp(mod->name, "ndiswrapper") == 0)
3488 		add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
3489 
3490 	/* driverloader was caught wrongly pretending to be under GPL */
3491 	if (strcmp(mod->name, "driverloader") == 0)
3492 		add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
3493 				 LOCKDEP_NOW_UNRELIABLE);
3494 
3495 	/* lve claims to be GPL but upstream won't provide source */
3496 	if (strcmp(mod->name, "lve") == 0)
3497 		add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
3498 				 LOCKDEP_NOW_UNRELIABLE);
3499 
3500 	if (!prev_taint && test_taint(TAINT_PROPRIETARY_MODULE))
3501 		pr_warn("%s: module license taints kernel.\n", mod->name);
3502 
3503 #ifdef CONFIG_MODVERSIONS
3504 	if ((mod->num_syms && !mod->crcs)
3505 	    || (mod->num_gpl_syms && !mod->gpl_crcs)
3506 	    || (mod->num_gpl_future_syms && !mod->gpl_future_crcs)
3507 #ifdef CONFIG_UNUSED_SYMBOLS
3508 	    || (mod->num_unused_syms && !mod->unused_crcs)
3509 	    || (mod->num_unused_gpl_syms && !mod->unused_gpl_crcs)
3510 #endif
3511 		) {
3512 		return try_to_force_load(mod,
3513 					 "no versions for exported symbols");
3514 	}
3515 #endif
3516 	return 0;
3517 }
3518 
flush_module_icache(const struct module * mod)3519 static void flush_module_icache(const struct module *mod)
3520 {
3521 	mm_segment_t old_fs;
3522 
3523 	/* flush the icache in correct context */
3524 	old_fs = get_fs();
3525 	set_fs(KERNEL_DS);
3526 
3527 	/*
3528 	 * Flush the instruction cache, since we've played with text.
3529 	 * Do it before processing of module parameters, so the module
3530 	 * can provide parameter accessor functions of its own.
3531 	 */
3532 	if (mod->init_layout.base)
3533 		flush_icache_range((unsigned long)mod->init_layout.base,
3534 				   (unsigned long)mod->init_layout.base
3535 				   + mod->init_layout.size);
3536 	flush_icache_range((unsigned long)mod->core_layout.base,
3537 			   (unsigned long)mod->core_layout.base + mod->core_layout.size);
3538 
3539 	set_fs(old_fs);
3540 }
3541 
module_frob_arch_sections(Elf_Ehdr * hdr,Elf_Shdr * sechdrs,char * secstrings,struct module * mod)3542 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
3543 				     Elf_Shdr *sechdrs,
3544 				     char *secstrings,
3545 				     struct module *mod)
3546 {
3547 	return 0;
3548 }
3549 
3550 /* module_blacklist is a comma-separated list of module names */
3551 static char *module_blacklist;
blacklisted(const char * module_name)3552 static bool blacklisted(const char *module_name)
3553 {
3554 	const char *p;
3555 	size_t len;
3556 
3557 	if (!module_blacklist)
3558 		return false;
3559 
3560 	for (p = module_blacklist; *p; p += len) {
3561 		len = strcspn(p, ",");
3562 		if (strlen(module_name) == len && !memcmp(module_name, p, len))
3563 			return true;
3564 		if (p[len] == ',')
3565 			len++;
3566 	}
3567 	return false;
3568 }
3569 core_param(module_blacklist, module_blacklist, charp, 0400);
3570 
layout_and_allocate(struct load_info * info,int flags)3571 static struct module *layout_and_allocate(struct load_info *info, int flags)
3572 {
3573 	struct module *mod;
3574 	unsigned int ndx;
3575 	int err;
3576 
3577 	err = check_modinfo(info->mod, info, flags);
3578 	if (err)
3579 		return ERR_PTR(err);
3580 
3581 	/* Allow arches to frob section contents and sizes.  */
3582 	err = module_frob_arch_sections(info->hdr, info->sechdrs,
3583 					info->secstrings, info->mod);
3584 	if (err < 0)
3585 		return ERR_PTR(err);
3586 
3587 	/* We will do a special allocation for per-cpu sections later. */
3588 	info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
3589 
3590 	/*
3591 	 * Mark ro_after_init section with SHF_RO_AFTER_INIT so that
3592 	 * layout_sections() can put it in the right place.
3593 	 * Note: ro_after_init sections also have SHF_{WRITE,ALLOC} set.
3594 	 */
3595 	ndx = find_sec(info, ".data..ro_after_init");
3596 	if (ndx)
3597 		info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
3598 	/*
3599 	 * Mark the __jump_table section as ro_after_init as well: these data
3600 	 * structures are never modified, with the exception of entries that
3601 	 * refer to code in the __init section, which are annotated as such
3602 	 * at module load time.
3603 	 */
3604 	ndx = find_sec(info, "__jump_table");
3605 	if (ndx)
3606 		info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
3607 
3608 	/* Determine total sizes, and put offsets in sh_entsize.  For now
3609 	   this is done generically; there doesn't appear to be any
3610 	   special cases for the architectures. */
3611 	layout_sections(info->mod, info);
3612 	layout_symtab(info->mod, info);
3613 
3614 	/* Allocate and move to the final place */
3615 	err = move_module(info->mod, info);
3616 	if (err)
3617 		return ERR_PTR(err);
3618 
3619 	/* Module has been copied to its final place now: return it. */
3620 	mod = (void *)info->sechdrs[info->index.mod].sh_addr;
3621 	kmemleak_load_module(mod, info);
3622 	return mod;
3623 }
3624 
3625 /* mod is no longer valid after this! */
module_deallocate(struct module * mod,struct load_info * info)3626 static void module_deallocate(struct module *mod, struct load_info *info)
3627 {
3628 	percpu_modfree(mod);
3629 	module_arch_freeing_init(mod);
3630 	module_memfree(mod->init_layout.base);
3631 	module_memfree(mod->core_layout.base);
3632 }
3633 
module_finalize(const Elf_Ehdr * hdr,const Elf_Shdr * sechdrs,struct module * me)3634 int __weak module_finalize(const Elf_Ehdr *hdr,
3635 			   const Elf_Shdr *sechdrs,
3636 			   struct module *me)
3637 {
3638 	return 0;
3639 }
3640 
3641 static void cfi_init(struct module *mod);
3642 
post_relocation(struct module * mod,const struct load_info * info)3643 static int post_relocation(struct module *mod, const struct load_info *info)
3644 {
3645 	/* Sort exception table now relocations are done. */
3646 	sort_extable(mod->extable, mod->extable + mod->num_exentries);
3647 
3648 	/* Copy relocated percpu area over. */
3649 	percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
3650 		       info->sechdrs[info->index.pcpu].sh_size);
3651 
3652 	/* Setup kallsyms-specific fields. */
3653 	add_kallsyms(mod, info);
3654 
3655 	/* Setup CFI for the module. */
3656 	cfi_init(mod);
3657 
3658 	/* Arch-specific module finalizing. */
3659 	return module_finalize(info->hdr, info->sechdrs, mod);
3660 }
3661 
3662 /* Is this module of this name done loading?  No locks held. */
finished_loading(const char * name)3663 static bool finished_loading(const char *name)
3664 {
3665 	struct module *mod;
3666 	bool ret;
3667 
3668 	/*
3669 	 * The module_mutex should not be a heavily contended lock;
3670 	 * if we get the occasional sleep here, we'll go an extra iteration
3671 	 * in the wait_event_interruptible(), which is harmless.
3672 	 */
3673 	sched_annotate_sleep();
3674 	mutex_lock(&module_mutex);
3675 	mod = find_module_all(name, strlen(name), true);
3676 	ret = !mod || mod->state == MODULE_STATE_LIVE
3677 		|| mod->state == MODULE_STATE_GOING;
3678 	mutex_unlock(&module_mutex);
3679 
3680 	return ret;
3681 }
3682 
3683 /* Call module constructors. */
do_mod_ctors(struct module * mod)3684 static void do_mod_ctors(struct module *mod)
3685 {
3686 #ifdef CONFIG_CONSTRUCTORS
3687 	unsigned long i;
3688 
3689 	for (i = 0; i < mod->num_ctors; i++)
3690 		mod->ctors[i]();
3691 #endif
3692 }
3693 
3694 /* For freeing module_init on success, in case kallsyms traversing */
3695 struct mod_initfree {
3696 	struct llist_node node;
3697 	void *module_init;
3698 };
3699 
do_free_init(struct work_struct * w)3700 static void do_free_init(struct work_struct *w)
3701 {
3702 	struct llist_node *pos, *n, *list;
3703 	struct mod_initfree *initfree;
3704 
3705 	list = llist_del_all(&init_free_list);
3706 
3707 	synchronize_rcu();
3708 
3709 	llist_for_each_safe(pos, n, list) {
3710 		initfree = container_of(pos, struct mod_initfree, node);
3711 		module_memfree(initfree->module_init);
3712 		kfree(initfree);
3713 	}
3714 }
3715 
3716 /*
3717  * This is where the real work happens.
3718  *
3719  * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb
3720  * helper command 'lx-symbols'.
3721  */
do_init_module(struct module * mod)3722 static noinline int do_init_module(struct module *mod)
3723 {
3724 	int ret = 0;
3725 	struct mod_initfree *freeinit;
3726 
3727 	freeinit = kmalloc(sizeof(*freeinit), GFP_KERNEL);
3728 	if (!freeinit) {
3729 		ret = -ENOMEM;
3730 		goto fail;
3731 	}
3732 	freeinit->module_init = mod->init_layout.base;
3733 
3734 	do_mod_ctors(mod);
3735 	/* Start the module */
3736 	if (mod->init != NULL)
3737 		ret = do_one_initcall(mod->init);
3738 	if (ret < 0) {
3739 		goto fail_free_freeinit;
3740 	}
3741 	if (ret > 0) {
3742 		pr_warn("%s: '%s'->init suspiciously returned %d, it should "
3743 			"follow 0/-E convention\n"
3744 			"%s: loading module anyway...\n",
3745 			__func__, mod->name, ret, __func__);
3746 		dump_stack();
3747 	}
3748 
3749 	/* Now it's a first class citizen! */
3750 	mod->state = MODULE_STATE_LIVE;
3751 	blocking_notifier_call_chain(&module_notify_list,
3752 				     MODULE_STATE_LIVE, mod);
3753 
3754 	/* Delay uevent until module has finished its init routine */
3755 	kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
3756 
3757 	/*
3758 	 * We need to finish all async code before the module init sequence
3759 	 * is done. This has potential to deadlock if synchronous module
3760 	 * loading is requested from async (which is not allowed!).
3761 	 *
3762 	 * See commit 0fdff3ec6d87 ("async, kmod: warn on synchronous
3763 	 * request_module() from async workers") for more details.
3764 	 */
3765 	if (!mod->async_probe_requested)
3766 		async_synchronize_full();
3767 
3768 	ftrace_free_mem(mod, mod->init_layout.base, mod->init_layout.base +
3769 			mod->init_layout.size);
3770 	mutex_lock(&module_mutex);
3771 	/* Drop initial reference. */
3772 	module_put(mod);
3773 	trim_init_extable(mod);
3774 #ifdef CONFIG_KALLSYMS
3775 	/* Switch to core kallsyms now init is done: kallsyms may be walking! */
3776 	rcu_assign_pointer(mod->kallsyms, &mod->core_kallsyms);
3777 #endif
3778 	module_enable_ro(mod, true);
3779 	mod_tree_remove_init(mod);
3780 	module_arch_freeing_init(mod);
3781 	mod->init_layout.base = NULL;
3782 	mod->init_layout.size = 0;
3783 	mod->init_layout.ro_size = 0;
3784 	mod->init_layout.ro_after_init_size = 0;
3785 	mod->init_layout.text_size = 0;
3786 	/*
3787 	 * We want to free module_init, but be aware that kallsyms may be
3788 	 * walking this with preempt disabled.  In all the failure paths, we
3789 	 * call synchronize_rcu(), but we don't want to slow down the success
3790 	 * path. module_memfree() cannot be called in an interrupt, so do the
3791 	 * work and call synchronize_rcu() in a work queue.
3792 	 *
3793 	 * Note that module_alloc() on most architectures creates W+X page
3794 	 * mappings which won't be cleaned up until do_free_init() runs.  Any
3795 	 * code such as mark_rodata_ro() which depends on those mappings to
3796 	 * be cleaned up needs to sync with the queued work - ie
3797 	 * rcu_barrier()
3798 	 */
3799 	if (llist_add(&freeinit->node, &init_free_list))
3800 		schedule_work(&init_free_wq);
3801 
3802 	mutex_unlock(&module_mutex);
3803 	wake_up_all(&module_wq);
3804 
3805 	return 0;
3806 
3807 fail_free_freeinit:
3808 	kfree(freeinit);
3809 fail:
3810 	/* Try to protect us from buggy refcounters. */
3811 	mod->state = MODULE_STATE_GOING;
3812 	synchronize_rcu();
3813 	module_put(mod);
3814 	blocking_notifier_call_chain(&module_notify_list,
3815 				     MODULE_STATE_GOING, mod);
3816 	klp_module_going(mod);
3817 	ftrace_release_mod(mod);
3818 	free_module(mod);
3819 	wake_up_all(&module_wq);
3820 	return ret;
3821 }
3822 
may_init_module(void)3823 static int may_init_module(void)
3824 {
3825 	if (!capable(CAP_SYS_MODULE) || modules_disabled)
3826 		return -EPERM;
3827 
3828 	return 0;
3829 }
3830 
3831 /*
3832  * We try to place it in the list now to make sure it's unique before
3833  * we dedicate too many resources.  In particular, temporary percpu
3834  * memory exhaustion.
3835  */
add_unformed_module(struct module * mod)3836 static int add_unformed_module(struct module *mod)
3837 {
3838 	int err;
3839 	struct module *old;
3840 
3841 	mod->state = MODULE_STATE_UNFORMED;
3842 
3843 	mutex_lock(&module_mutex);
3844 	old = find_module_all(mod->name, strlen(mod->name), true);
3845 	if (old != NULL) {
3846 		if (old->state == MODULE_STATE_COMING
3847 		    || old->state == MODULE_STATE_UNFORMED) {
3848 			/* Wait in case it fails to load. */
3849 			mutex_unlock(&module_mutex);
3850 			err = wait_event_interruptible(module_wq,
3851 					       finished_loading(mod->name));
3852 			if (err)
3853 				goto out_unlocked;
3854 
3855 			/* The module might have gone in the meantime. */
3856 			mutex_lock(&module_mutex);
3857 			old = find_module_all(mod->name, strlen(mod->name),
3858 					      true);
3859 		}
3860 
3861 		/*
3862 		 * We are here only when the same module was being loaded. Do
3863 		 * not try to load it again right now. It prevents long delays
3864 		 * caused by serialized module load failures. It might happen
3865 		 * when more devices of the same type trigger load of
3866 		 * a particular module.
3867 		 */
3868 		if (old && old->state == MODULE_STATE_LIVE)
3869 			err = -EEXIST;
3870 		else
3871 			err = -EBUSY;
3872 		goto out;
3873 	}
3874 	mod_update_bounds(mod);
3875 	list_add_rcu(&mod->list, &modules);
3876 	mod_tree_insert(mod);
3877 	err = 0;
3878 
3879 out:
3880 	mutex_unlock(&module_mutex);
3881 out_unlocked:
3882 	return err;
3883 }
3884 
complete_formation(struct module * mod,struct load_info * info)3885 static int complete_formation(struct module *mod, struct load_info *info)
3886 {
3887 	int err;
3888 
3889 	mutex_lock(&module_mutex);
3890 
3891 	/* Find duplicate symbols (must be called under lock). */
3892 	err = verify_exported_symbols(mod);
3893 	if (err < 0)
3894 		goto out;
3895 
3896 	/* This relies on module_mutex for list integrity. */
3897 	module_bug_finalize(info->hdr, info->sechdrs, mod);
3898 
3899 	module_enable_ro(mod, false);
3900 	module_enable_nx(mod);
3901 	module_enable_x(mod);
3902 
3903 	/* Mark state as coming so strong_try_module_get() ignores us,
3904 	 * but kallsyms etc. can see us. */
3905 	mod->state = MODULE_STATE_COMING;
3906 	mutex_unlock(&module_mutex);
3907 
3908 	return 0;
3909 
3910 out:
3911 	mutex_unlock(&module_mutex);
3912 	return err;
3913 }
3914 
prepare_coming_module(struct module * mod)3915 static int prepare_coming_module(struct module *mod)
3916 {
3917 	int err;
3918 
3919 	ftrace_module_enable(mod);
3920 	err = klp_module_coming(mod);
3921 	if (err)
3922 		return err;
3923 
3924 	blocking_notifier_call_chain(&module_notify_list,
3925 				     MODULE_STATE_COMING, mod);
3926 	return 0;
3927 }
3928 
unknown_module_param_cb(char * param,char * val,const char * modname,void * arg)3929 static int unknown_module_param_cb(char *param, char *val, const char *modname,
3930 				   void *arg)
3931 {
3932 	struct module *mod = arg;
3933 	int ret;
3934 
3935 	if (strcmp(param, "async_probe") == 0) {
3936 		mod->async_probe_requested = true;
3937 		return 0;
3938 	}
3939 
3940 	/* Check for magic 'dyndbg' arg */
3941 	ret = ddebug_dyndbg_module_param_cb(param, val, modname);
3942 	if (ret != 0)
3943 		pr_warn("%s: unknown parameter '%s' ignored\n", modname, param);
3944 	return 0;
3945 }
3946 
3947 /* Allocate and load the module: note that size of section 0 is always
3948    zero, and we rely on this for optional sections. */
load_module(struct load_info * info,const char __user * uargs,int flags)3949 static int load_module(struct load_info *info, const char __user *uargs,
3950 		       int flags)
3951 {
3952 	struct module *mod;
3953 	long err = 0;
3954 	char *after_dashes;
3955 
3956 	/*
3957 	 * Do the signature check (if any) first. All that
3958 	 * the signature check needs is info->len, it does
3959 	 * not need any of the section info. That can be
3960 	 * set up later. This will minimize the chances
3961 	 * of a corrupt module causing problems before
3962 	 * we even get to the signature check.
3963 	 *
3964 	 * The check will also adjust info->len by stripping
3965 	 * off the sig length at the end of the module, making
3966 	 * checks against info->len more correct.
3967 	 */
3968 	err = module_sig_check(info, flags);
3969 	if (err)
3970 		goto free_copy;
3971 
3972 	/*
3973 	 * Do basic sanity checks against the ELF header and
3974 	 * sections.
3975 	 */
3976 	err = elf_validity_check(info);
3977 	if (err) {
3978 		pr_err("Module has invalid ELF structures\n");
3979 		goto free_copy;
3980 	}
3981 
3982 	/*
3983 	 * Everything checks out, so set up the section info
3984 	 * in the info structure.
3985 	 */
3986 	err = setup_load_info(info, flags);
3987 	if (err)
3988 		goto free_copy;
3989 
3990 	/*
3991 	 * Now that we know we have the correct module name, check
3992 	 * if it's blacklisted.
3993 	 */
3994 	if (blacklisted(info->name)) {
3995 		err = -EPERM;
3996 		goto free_copy;
3997 	}
3998 
3999 	err = rewrite_section_headers(info, flags);
4000 	if (err)
4001 		goto free_copy;
4002 
4003 	/* Check module struct version now, before we try to use module. */
4004 	if (!check_modstruct_version(info, info->mod)) {
4005 		err = -ENOEXEC;
4006 		goto free_copy;
4007 	}
4008 
4009 	/* Figure out module layout, and allocate all the memory. */
4010 	mod = layout_and_allocate(info, flags);
4011 	if (IS_ERR(mod)) {
4012 		err = PTR_ERR(mod);
4013 		goto free_copy;
4014 	}
4015 
4016 	audit_log_kern_module(mod->name);
4017 
4018 	/* Reserve our place in the list. */
4019 	err = add_unformed_module(mod);
4020 	if (err)
4021 		goto free_module;
4022 
4023 #ifdef CONFIG_MODULE_SIG
4024 	mod->sig_ok = info->sig_ok;
4025 	if (!mod->sig_ok) {
4026 		pr_notice_once("%s: module verification failed: signature "
4027 			       "and/or required key missing - tainting "
4028 			       "kernel\n", mod->name);
4029 		add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
4030 	}
4031 #endif
4032 
4033 	/* To avoid stressing percpu allocator, do this once we're unique. */
4034 	err = percpu_modalloc(mod, info);
4035 	if (err)
4036 		goto unlink_mod;
4037 
4038 	/* Now module is in final location, initialize linked lists, etc. */
4039 	err = module_unload_init(mod);
4040 	if (err)
4041 		goto unlink_mod;
4042 
4043 	init_param_lock(mod);
4044 
4045 	/* Now we've got everything in the final locations, we can
4046 	 * find optional sections. */
4047 	err = find_module_sections(mod, info);
4048 	if (err)
4049 		goto free_unload;
4050 
4051 	err = check_module_license_and_versions(mod);
4052 	if (err)
4053 		goto free_unload;
4054 
4055 	/* Set up MODINFO_ATTR fields */
4056 	setup_modinfo(mod, info);
4057 
4058 	/* Fix up syms, so that st_value is a pointer to location. */
4059 	err = simplify_symbols(mod, info);
4060 	if (err < 0)
4061 		goto free_modinfo;
4062 
4063 	err = apply_relocations(mod, info);
4064 	if (err < 0)
4065 		goto free_modinfo;
4066 
4067 	err = post_relocation(mod, info);
4068 	if (err < 0)
4069 		goto free_modinfo;
4070 
4071 	flush_module_icache(mod);
4072 
4073 	/* Now copy in args */
4074 	mod->args = strndup_user(uargs, ~0UL >> 1);
4075 	if (IS_ERR(mod->args)) {
4076 		err = PTR_ERR(mod->args);
4077 		goto free_arch_cleanup;
4078 	}
4079 
4080 	dynamic_debug_setup(mod, info->debug, info->num_debug);
4081 
4082 	/* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
4083 	ftrace_module_init(mod);
4084 
4085 	/* Finally it's fully formed, ready to start executing. */
4086 	err = complete_formation(mod, info);
4087 	if (err)
4088 		goto ddebug_cleanup;
4089 
4090 	err = prepare_coming_module(mod);
4091 	if (err)
4092 		goto bug_cleanup;
4093 
4094 	/* Module is ready to execute: parsing args may do that. */
4095 	after_dashes = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
4096 				  -32768, 32767, mod,
4097 				  unknown_module_param_cb);
4098 	if (IS_ERR(after_dashes)) {
4099 		err = PTR_ERR(after_dashes);
4100 		goto coming_cleanup;
4101 	} else if (after_dashes) {
4102 		pr_warn("%s: parameters '%s' after `--' ignored\n",
4103 		       mod->name, after_dashes);
4104 	}
4105 
4106 	/* Link in to sysfs. */
4107 	err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
4108 	if (err < 0)
4109 		goto coming_cleanup;
4110 
4111 	if (is_livepatch_module(mod)) {
4112 		err = copy_module_elf(mod, info);
4113 		if (err < 0)
4114 			goto sysfs_cleanup;
4115 	}
4116 
4117 	/* Get rid of temporary copy. */
4118 	free_copy(info);
4119 
4120 	/* Done! */
4121 	trace_module_load(mod);
4122 
4123 	return do_init_module(mod);
4124 
4125  sysfs_cleanup:
4126 	mod_sysfs_teardown(mod);
4127  coming_cleanup:
4128 	mod->state = MODULE_STATE_GOING;
4129 	destroy_params(mod->kp, mod->num_kp);
4130 	blocking_notifier_call_chain(&module_notify_list,
4131 				     MODULE_STATE_GOING, mod);
4132 	klp_module_going(mod);
4133  bug_cleanup:
4134 	mod->state = MODULE_STATE_GOING;
4135 	/* module_bug_cleanup needs module_mutex protection */
4136 	mutex_lock(&module_mutex);
4137 	module_bug_cleanup(mod);
4138 	mutex_unlock(&module_mutex);
4139 
4140  ddebug_cleanup:
4141 	/* Clean up CFI for the module. */
4142 	cfi_cleanup(mod);
4143 	ftrace_release_mod(mod);
4144 	dynamic_debug_remove(mod, info->debug);
4145 	synchronize_rcu();
4146 	kfree(mod->args);
4147  free_arch_cleanup:
4148 	module_arch_cleanup(mod);
4149  free_modinfo:
4150 	free_modinfo(mod);
4151  free_unload:
4152 	module_unload_free(mod);
4153  unlink_mod:
4154 	mutex_lock(&module_mutex);
4155 	/* Unlink carefully: kallsyms could be walking list. */
4156 	list_del_rcu(&mod->list);
4157 	mod_tree_remove(mod);
4158 	wake_up_all(&module_wq);
4159 	/* Wait for RCU-sched synchronizing before releasing mod->list. */
4160 	synchronize_rcu();
4161 	mutex_unlock(&module_mutex);
4162  free_module:
4163 	/* Free lock-classes; relies on the preceding sync_rcu() */
4164 	lockdep_free_key_range(mod->core_layout.base, mod->core_layout.size);
4165 
4166 	module_deallocate(mod, info);
4167  free_copy:
4168 	free_copy(info);
4169 	return err;
4170 }
4171 
SYSCALL_DEFINE3(init_module,void __user *,umod,unsigned long,len,const char __user *,uargs)4172 SYSCALL_DEFINE3(init_module, void __user *, umod,
4173 		unsigned long, len, const char __user *, uargs)
4174 {
4175 	int err;
4176 	struct load_info info = { };
4177 
4178 	err = may_init_module();
4179 	if (err)
4180 		return err;
4181 
4182 	pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
4183 	       umod, len, uargs);
4184 
4185 	err = copy_module_from_user(umod, len, &info);
4186 	if (err)
4187 		return err;
4188 
4189 	return load_module(&info, uargs, 0);
4190 }
4191 
SYSCALL_DEFINE3(finit_module,int,fd,const char __user *,uargs,int,flags)4192 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
4193 {
4194 	struct load_info info = { };
4195 	loff_t size;
4196 	void *hdr;
4197 	int err;
4198 
4199 	err = may_init_module();
4200 	if (err)
4201 		return err;
4202 
4203 	pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
4204 
4205 	if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
4206 		      |MODULE_INIT_IGNORE_VERMAGIC))
4207 		return -EINVAL;
4208 
4209 	err = kernel_read_file_from_fd(fd, &hdr, &size, INT_MAX,
4210 				       READING_MODULE);
4211 	if (err)
4212 		return err;
4213 	info.hdr = hdr;
4214 	info.len = size;
4215 
4216 	return load_module(&info, uargs, flags);
4217 }
4218 
within(unsigned long addr,void * start,unsigned long size)4219 static inline int within(unsigned long addr, void *start, unsigned long size)
4220 {
4221 	return ((void *)addr >= start && (void *)addr < start + size);
4222 }
4223 
4224 #ifdef CONFIG_KALLSYMS
4225 /*
4226  * This ignores the intensely annoying "mapping symbols" found
4227  * in ARM ELF files: $a, $t and $d.
4228  */
is_arm_mapping_symbol(const char * str)4229 static inline int is_arm_mapping_symbol(const char *str)
4230 {
4231 	if (str[0] == '.' && str[1] == 'L')
4232 		return true;
4233 	return str[0] == '$' && strchr("axtd", str[1])
4234 	       && (str[2] == '\0' || str[2] == '.');
4235 }
4236 
kallsyms_symbol_name(struct mod_kallsyms * kallsyms,unsigned int symnum)4237 static const char *kallsyms_symbol_name(struct mod_kallsyms *kallsyms, unsigned int symnum)
4238 {
4239 	return kallsyms->strtab + kallsyms->symtab[symnum].st_name;
4240 }
4241 
4242 /*
4243  * Given a module and address, find the corresponding symbol and return its name
4244  * while providing its size and offset if needed.
4245  */
find_kallsyms_symbol(struct module * mod,unsigned long addr,unsigned long * size,unsigned long * offset)4246 static const char *find_kallsyms_symbol(struct module *mod,
4247 					unsigned long addr,
4248 					unsigned long *size,
4249 					unsigned long *offset)
4250 {
4251 	unsigned int i, best = 0;
4252 	unsigned long nextval, bestval;
4253 	struct mod_kallsyms *kallsyms = rcu_dereference_sched(mod->kallsyms);
4254 
4255 	/* At worse, next value is at end of module */
4256 	if (within_module_init(addr, mod))
4257 		nextval = (unsigned long)mod->init_layout.base+mod->init_layout.text_size;
4258 	else
4259 		nextval = (unsigned long)mod->core_layout.base+mod->core_layout.text_size;
4260 
4261 	bestval = kallsyms_symbol_value(&kallsyms->symtab[best]);
4262 
4263 	/* Scan for closest preceding symbol, and next symbol. (ELF
4264 	   starts real symbols at 1). */
4265 	for (i = 1; i < kallsyms->num_symtab; i++) {
4266 		const Elf_Sym *sym = &kallsyms->symtab[i];
4267 		unsigned long thisval = kallsyms_symbol_value(sym);
4268 
4269 		if (sym->st_shndx == SHN_UNDEF)
4270 			continue;
4271 
4272 		/* We ignore unnamed symbols: they're uninformative
4273 		 * and inserted at a whim. */
4274 		if (*kallsyms_symbol_name(kallsyms, i) == '\0'
4275 		    || is_arm_mapping_symbol(kallsyms_symbol_name(kallsyms, i)))
4276 			continue;
4277 
4278 		if (thisval <= addr && thisval > bestval) {
4279 			best = i;
4280 			bestval = thisval;
4281 		}
4282 		if (thisval > addr && thisval < nextval)
4283 			nextval = thisval;
4284 	}
4285 
4286 	if (!best)
4287 		return NULL;
4288 
4289 	if (size)
4290 		*size = nextval - bestval;
4291 	if (offset)
4292 		*offset = addr - bestval;
4293 
4294 	return kallsyms_symbol_name(kallsyms, best);
4295 }
4296 
dereference_module_function_descriptor(struct module * mod,void * ptr)4297 void * __weak dereference_module_function_descriptor(struct module *mod,
4298 						     void *ptr)
4299 {
4300 	return ptr;
4301 }
4302 
4303 /* For kallsyms to ask for address resolution.  NULL means not found.  Careful
4304  * not to lock to avoid deadlock on oopses, simply disable preemption. */
module_address_lookup(unsigned long addr,unsigned long * size,unsigned long * offset,char ** modname,char * namebuf)4305 const char *module_address_lookup(unsigned long addr,
4306 			    unsigned long *size,
4307 			    unsigned long *offset,
4308 			    char **modname,
4309 			    char *namebuf)
4310 {
4311 	const char *ret = NULL;
4312 	struct module *mod;
4313 
4314 	preempt_disable();
4315 	mod = __module_address(addr);
4316 	if (mod) {
4317 		if (modname)
4318 			*modname = mod->name;
4319 
4320 		ret = find_kallsyms_symbol(mod, addr, size, offset);
4321 	}
4322 	/* Make a copy in here where it's safe */
4323 	if (ret) {
4324 		strncpy(namebuf, ret, KSYM_NAME_LEN - 1);
4325 		ret = namebuf;
4326 	}
4327 	preempt_enable();
4328 
4329 	return ret;
4330 }
4331 
lookup_module_symbol_name(unsigned long addr,char * symname)4332 int lookup_module_symbol_name(unsigned long addr, char *symname)
4333 {
4334 	struct module *mod;
4335 
4336 	preempt_disable();
4337 	list_for_each_entry_rcu(mod, &modules, list) {
4338 		if (mod->state == MODULE_STATE_UNFORMED)
4339 			continue;
4340 		if (within_module(addr, mod)) {
4341 			const char *sym;
4342 
4343 			sym = find_kallsyms_symbol(mod, addr, NULL, NULL);
4344 			if (!sym)
4345 				goto out;
4346 
4347 			strlcpy(symname, sym, KSYM_NAME_LEN);
4348 			preempt_enable();
4349 			return 0;
4350 		}
4351 	}
4352 out:
4353 	preempt_enable();
4354 	return -ERANGE;
4355 }
4356 
lookup_module_symbol_attrs(unsigned long addr,unsigned long * size,unsigned long * offset,char * modname,char * name)4357 int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size,
4358 			unsigned long *offset, char *modname, char *name)
4359 {
4360 	struct module *mod;
4361 
4362 	preempt_disable();
4363 	list_for_each_entry_rcu(mod, &modules, list) {
4364 		if (mod->state == MODULE_STATE_UNFORMED)
4365 			continue;
4366 		if (within_module(addr, mod)) {
4367 			const char *sym;
4368 
4369 			sym = find_kallsyms_symbol(mod, addr, size, offset);
4370 			if (!sym)
4371 				goto out;
4372 			if (modname)
4373 				strlcpy(modname, mod->name, MODULE_NAME_LEN);
4374 			if (name)
4375 				strlcpy(name, sym, KSYM_NAME_LEN);
4376 			preempt_enable();
4377 			return 0;
4378 		}
4379 	}
4380 out:
4381 	preempt_enable();
4382 	return -ERANGE;
4383 }
4384 
module_get_kallsym(unsigned int symnum,unsigned long * value,char * type,char * name,char * module_name,int * exported)4385 int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
4386 			char *name, char *module_name, int *exported)
4387 {
4388 	struct module *mod;
4389 
4390 	preempt_disable();
4391 	list_for_each_entry_rcu(mod, &modules, list) {
4392 		struct mod_kallsyms *kallsyms;
4393 
4394 		if (mod->state == MODULE_STATE_UNFORMED)
4395 			continue;
4396 		kallsyms = rcu_dereference_sched(mod->kallsyms);
4397 		if (symnum < kallsyms->num_symtab) {
4398 			const Elf_Sym *sym = &kallsyms->symtab[symnum];
4399 
4400 			*value = kallsyms_symbol_value(sym);
4401 			*type = kallsyms->typetab[symnum];
4402 			strlcpy(name, kallsyms_symbol_name(kallsyms, symnum), KSYM_NAME_LEN);
4403 			strlcpy(module_name, mod->name, MODULE_NAME_LEN);
4404 			*exported = is_exported(name, *value, mod);
4405 			preempt_enable();
4406 			return 0;
4407 		}
4408 		symnum -= kallsyms->num_symtab;
4409 	}
4410 	preempt_enable();
4411 	return -ERANGE;
4412 }
4413 
4414 /* Given a module and name of symbol, find and return the symbol's value */
find_kallsyms_symbol_value(struct module * mod,const char * name)4415 static unsigned long find_kallsyms_symbol_value(struct module *mod, const char *name)
4416 {
4417 	unsigned int i;
4418 	struct mod_kallsyms *kallsyms = rcu_dereference_sched(mod->kallsyms);
4419 
4420 	for (i = 0; i < kallsyms->num_symtab; i++) {
4421 		const Elf_Sym *sym = &kallsyms->symtab[i];
4422 
4423 		if (strcmp(name, kallsyms_symbol_name(kallsyms, i)) == 0 &&
4424 		    sym->st_shndx != SHN_UNDEF)
4425 			return kallsyms_symbol_value(sym);
4426 	}
4427 	return 0;
4428 }
4429 
4430 /* Look for this name: can be of form module:name. */
module_kallsyms_lookup_name(const char * name)4431 unsigned long module_kallsyms_lookup_name(const char *name)
4432 {
4433 	struct module *mod;
4434 	char *colon;
4435 	unsigned long ret = 0;
4436 
4437 	/* Don't lock: we're in enough trouble already. */
4438 	preempt_disable();
4439 	if ((colon = strnchr(name, MODULE_NAME_LEN, ':')) != NULL) {
4440 		if ((mod = find_module_all(name, colon - name, false)) != NULL)
4441 			ret = find_kallsyms_symbol_value(mod, colon+1);
4442 	} else {
4443 		list_for_each_entry_rcu(mod, &modules, list) {
4444 			if (mod->state == MODULE_STATE_UNFORMED)
4445 				continue;
4446 			if ((ret = find_kallsyms_symbol_value(mod, name)) != 0)
4447 				break;
4448 		}
4449 	}
4450 	preempt_enable();
4451 	return ret;
4452 }
4453 
module_kallsyms_on_each_symbol(int (* fn)(void *,const char *,struct module *,unsigned long),void * data)4454 int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
4455 					     struct module *, unsigned long),
4456 				   void *data)
4457 {
4458 	struct module *mod;
4459 	unsigned int i;
4460 	int ret;
4461 
4462 	module_assert_mutex();
4463 
4464 	list_for_each_entry(mod, &modules, list) {
4465 		/* We hold module_mutex: no need for rcu_dereference_sched */
4466 		struct mod_kallsyms *kallsyms = mod->kallsyms;
4467 
4468 		if (mod->state == MODULE_STATE_UNFORMED)
4469 			continue;
4470 		for (i = 0; i < kallsyms->num_symtab; i++) {
4471 			const Elf_Sym *sym = &kallsyms->symtab[i];
4472 
4473 			if (sym->st_shndx == SHN_UNDEF)
4474 				continue;
4475 
4476 			ret = fn(data, kallsyms_symbol_name(kallsyms, i),
4477 				 mod, kallsyms_symbol_value(sym));
4478 			if (ret != 0)
4479 				return ret;
4480 		}
4481 	}
4482 	return 0;
4483 }
4484 #endif /* CONFIG_KALLSYMS */
4485 
cfi_init(struct module * mod)4486 static void cfi_init(struct module *mod)
4487 {
4488 #ifdef CONFIG_CFI_CLANG
4489 	rcu_read_lock_sched();
4490 	mod->cfi_check = (cfi_check_fn)find_kallsyms_symbol_value(mod,
4491 						CFI_CHECK_FN_NAME);
4492 	rcu_read_unlock_sched();
4493 	cfi_module_add(mod, module_addr_min, module_addr_max);
4494 #endif
4495 }
4496 
cfi_cleanup(struct module * mod)4497 static void cfi_cleanup(struct module *mod)
4498 {
4499 #ifdef CONFIG_CFI_CLANG
4500 	cfi_module_remove(mod, module_addr_min, module_addr_max);
4501 #endif
4502 }
4503 
4504 /* Maximum number of characters written by module_flags() */
4505 #define MODULE_FLAGS_BUF_SIZE (TAINT_FLAGS_COUNT + 4)
4506 
4507 /* Keep in sync with MODULE_FLAGS_BUF_SIZE !!! */
module_flags(struct module * mod,char * buf)4508 static char *module_flags(struct module *mod, char *buf)
4509 {
4510 	int bx = 0;
4511 
4512 	BUG_ON(mod->state == MODULE_STATE_UNFORMED);
4513 	if (mod->taints ||
4514 	    mod->state == MODULE_STATE_GOING ||
4515 	    mod->state == MODULE_STATE_COMING) {
4516 		buf[bx++] = '(';
4517 		bx += module_flags_taint(mod, buf + bx);
4518 		/* Show a - for module-is-being-unloaded */
4519 		if (mod->state == MODULE_STATE_GOING)
4520 			buf[bx++] = '-';
4521 		/* Show a + for module-is-being-loaded */
4522 		if (mod->state == MODULE_STATE_COMING)
4523 			buf[bx++] = '+';
4524 		buf[bx++] = ')';
4525 	}
4526 	buf[bx] = '\0';
4527 
4528 	return buf;
4529 }
4530 
4531 #ifdef CONFIG_PROC_FS
4532 /* Called by the /proc file system to return a list of modules. */
m_start(struct seq_file * m,loff_t * pos)4533 static void *m_start(struct seq_file *m, loff_t *pos)
4534 {
4535 	mutex_lock(&module_mutex);
4536 	return seq_list_start(&modules, *pos);
4537 }
4538 
m_next(struct seq_file * m,void * p,loff_t * pos)4539 static void *m_next(struct seq_file *m, void *p, loff_t *pos)
4540 {
4541 	return seq_list_next(p, &modules, pos);
4542 }
4543 
m_stop(struct seq_file * m,void * p)4544 static void m_stop(struct seq_file *m, void *p)
4545 {
4546 	mutex_unlock(&module_mutex);
4547 }
4548 
m_show(struct seq_file * m,void * p)4549 static int m_show(struct seq_file *m, void *p)
4550 {
4551 	struct module *mod = list_entry(p, struct module, list);
4552 	char buf[MODULE_FLAGS_BUF_SIZE];
4553 	void *value;
4554 
4555 	/* We always ignore unformed modules. */
4556 	if (mod->state == MODULE_STATE_UNFORMED)
4557 		return 0;
4558 
4559 	seq_printf(m, "%s %u",
4560 		   mod->name, mod->init_layout.size + mod->core_layout.size);
4561 	print_unload_info(m, mod);
4562 
4563 	/* Informative for users. */
4564 	seq_printf(m, " %s",
4565 		   mod->state == MODULE_STATE_GOING ? "Unloading" :
4566 		   mod->state == MODULE_STATE_COMING ? "Loading" :
4567 		   "Live");
4568 	/* Used by oprofile and other similar tools. */
4569 	value = m->private ? NULL : mod->core_layout.base;
4570 	seq_printf(m, " 0x%px", value);
4571 
4572 	/* Taints info */
4573 	if (mod->taints)
4574 		seq_printf(m, " %s", module_flags(mod, buf));
4575 
4576 	seq_puts(m, "\n");
4577 	return 0;
4578 }
4579 
4580 /* Format: modulename size refcount deps address
4581 
4582    Where refcount is a number or -, and deps is a comma-separated list
4583    of depends or -.
4584 */
4585 static const struct seq_operations modules_op = {
4586 	.start	= m_start,
4587 	.next	= m_next,
4588 	.stop	= m_stop,
4589 	.show	= m_show
4590 };
4591 
4592 /*
4593  * This also sets the "private" pointer to non-NULL if the
4594  * kernel pointers should be hidden (so you can just test
4595  * "m->private" to see if you should keep the values private).
4596  *
4597  * We use the same logic as for /proc/kallsyms.
4598  */
modules_open(struct inode * inode,struct file * file)4599 static int modules_open(struct inode *inode, struct file *file)
4600 {
4601 	int err = seq_open(file, &modules_op);
4602 
4603 	if (!err) {
4604 		struct seq_file *m = file->private_data;
4605 		m->private = kallsyms_show_value(file->f_cred) ? NULL : (void *)8ul;
4606 	}
4607 
4608 	return err;
4609 }
4610 
4611 static const struct file_operations proc_modules_operations = {
4612 	.open		= modules_open,
4613 	.read		= seq_read,
4614 	.llseek		= seq_lseek,
4615 	.release	= seq_release,
4616 };
4617 
proc_modules_init(void)4618 static int __init proc_modules_init(void)
4619 {
4620 	proc_create("modules", 0, NULL, &proc_modules_operations);
4621 	return 0;
4622 }
4623 module_init(proc_modules_init);
4624 #endif
4625 
4626 /* Given an address, look for it in the module exception tables. */
search_module_extables(unsigned long addr)4627 const struct exception_table_entry *search_module_extables(unsigned long addr)
4628 {
4629 	const struct exception_table_entry *e = NULL;
4630 	struct module *mod;
4631 
4632 	preempt_disable();
4633 	mod = __module_address(addr);
4634 	if (!mod)
4635 		goto out;
4636 
4637 	if (!mod->num_exentries)
4638 		goto out;
4639 
4640 	e = search_extable(mod->extable,
4641 			   mod->num_exentries,
4642 			   addr);
4643 out:
4644 	preempt_enable();
4645 
4646 	/*
4647 	 * Now, if we found one, we are running inside it now, hence
4648 	 * we cannot unload the module, hence no refcnt needed.
4649 	 */
4650 	return e;
4651 }
4652 
4653 /*
4654  * is_module_address - is this address inside a module?
4655  * @addr: the address to check.
4656  *
4657  * See is_module_text_address() if you simply want to see if the address
4658  * is code (not data).
4659  */
is_module_address(unsigned long addr)4660 bool is_module_address(unsigned long addr)
4661 {
4662 	bool ret;
4663 
4664 	preempt_disable();
4665 	ret = __module_address(addr) != NULL;
4666 	preempt_enable();
4667 
4668 	return ret;
4669 }
4670 
4671 /*
4672  * __module_address - get the module which contains an address.
4673  * @addr: the address.
4674  *
4675  * Must be called with preempt disabled or module mutex held so that
4676  * module doesn't get freed during this.
4677  */
__module_address(unsigned long addr)4678 struct module *__module_address(unsigned long addr)
4679 {
4680 	struct module *mod;
4681 
4682 	if (addr < module_addr_min || addr > module_addr_max)
4683 		return NULL;
4684 
4685 	module_assert_mutex_or_preempt();
4686 
4687 	mod = mod_find(addr);
4688 	if (mod) {
4689 		BUG_ON(!within_module(addr, mod));
4690 		if (mod->state == MODULE_STATE_UNFORMED)
4691 			mod = NULL;
4692 	}
4693 	return mod;
4694 }
4695 
4696 /*
4697  * is_module_text_address - is this address inside module code?
4698  * @addr: the address to check.
4699  *
4700  * See is_module_address() if you simply want to see if the address is
4701  * anywhere in a module.  See kernel_text_address() for testing if an
4702  * address corresponds to kernel or module code.
4703  */
is_module_text_address(unsigned long addr)4704 bool is_module_text_address(unsigned long addr)
4705 {
4706 	bool ret;
4707 
4708 	preempt_disable();
4709 	ret = __module_text_address(addr) != NULL;
4710 	preempt_enable();
4711 
4712 	return ret;
4713 }
4714 
4715 /*
4716  * __module_text_address - get the module whose code contains an address.
4717  * @addr: the address.
4718  *
4719  * Must be called with preempt disabled or module mutex held so that
4720  * module doesn't get freed during this.
4721  */
__module_text_address(unsigned long addr)4722 struct module *__module_text_address(unsigned long addr)
4723 {
4724 	struct module *mod = __module_address(addr);
4725 	if (mod) {
4726 		/* Make sure it's within the text section. */
4727 		if (!within(addr, mod->init_layout.base, mod->init_layout.text_size)
4728 		    && !within(addr, mod->core_layout.base, mod->core_layout.text_size))
4729 			mod = NULL;
4730 	}
4731 	return mod;
4732 }
4733 
4734 /* Don't grab lock, we're oopsing. */
print_modules(void)4735 void print_modules(void)
4736 {
4737 	struct module *mod;
4738 	char buf[MODULE_FLAGS_BUF_SIZE];
4739 
4740 	printk(KERN_DEFAULT "Modules linked in:");
4741 	/* Most callers should already have preempt disabled, but make sure */
4742 	preempt_disable();
4743 	list_for_each_entry_rcu(mod, &modules, list) {
4744 		if (mod->state == MODULE_STATE_UNFORMED)
4745 			continue;
4746 		pr_cont(" %s%s", mod->name, module_flags(mod, buf));
4747 	}
4748 	preempt_enable();
4749 	if (last_unloaded_module[0])
4750 		pr_cont(" [last unloaded: %s]", last_unloaded_module);
4751 	pr_cont("\n");
4752 }
4753 
4754 #ifdef CONFIG_MODVERSIONS
4755 /* Generate the signature for all relevant module structures here.
4756  * If these change, we don't want to try to parse the module. */
module_layout(struct module * mod,struct modversion_info * ver,struct kernel_param * kp,struct kernel_symbol * ks,struct tracepoint * const * tp)4757 void module_layout(struct module *mod,
4758 		   struct modversion_info *ver,
4759 		   struct kernel_param *kp,
4760 		   struct kernel_symbol *ks,
4761 		   struct tracepoint * const *tp)
4762 {
4763 }
4764 EXPORT_SYMBOL(module_layout);
4765 #endif
4766