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