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