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 const struct kernel_symbol *sym;
2289
2290 preempt_disable();
2291 sym = find_symbol(symbol, &owner, NULL, NULL, true, true);
2292 if (sym && strong_try_module_get(owner))
2293 sym = NULL;
2294 preempt_enable();
2295
2296 return sym ? (void *)kernel_symbol_value(sym) : NULL;
2297 }
2298 EXPORT_SYMBOL_GPL(__symbol_get);
2299
module_init_layout_section(const char * sname)2300 static bool module_init_layout_section(const char *sname)
2301 {
2302 #ifndef CONFIG_MODULE_UNLOAD
2303 if (module_exit_section(sname))
2304 return true;
2305 #endif
2306 return module_init_section(sname);
2307 }
2308
2309 /*
2310 * Ensure that an exported symbol [global namespace] does not already exist
2311 * in the kernel or in some other module's exported symbol table.
2312 *
2313 * You must hold the module_mutex.
2314 */
verify_exported_symbols(struct module * mod)2315 static int verify_exported_symbols(struct module *mod)
2316 {
2317 unsigned int i;
2318 struct module *owner;
2319 const struct kernel_symbol *s;
2320 struct {
2321 const struct kernel_symbol *sym;
2322 unsigned int num;
2323 } arr[] = {
2324 { mod->syms, mod->num_syms },
2325 { mod->gpl_syms, mod->num_gpl_syms },
2326 { mod->gpl_future_syms, mod->num_gpl_future_syms },
2327 #ifdef CONFIG_UNUSED_SYMBOLS
2328 { mod->unused_syms, mod->num_unused_syms },
2329 { mod->unused_gpl_syms, mod->num_unused_gpl_syms },
2330 #endif
2331 };
2332
2333 for (i = 0; i < ARRAY_SIZE(arr); i++) {
2334 for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
2335 if (find_symbol(kernel_symbol_name(s), &owner, NULL,
2336 NULL, true, false)) {
2337 pr_err("%s: exports duplicate symbol %s"
2338 " (owned by %s)\n",
2339 mod->name, kernel_symbol_name(s),
2340 module_name(owner));
2341 return -ENOEXEC;
2342 }
2343 }
2344 }
2345 return 0;
2346 }
2347
ignore_undef_symbol(Elf_Half emachine,const char * name)2348 static bool ignore_undef_symbol(Elf_Half emachine, const char *name)
2349 {
2350 /*
2351 * On x86, PIC code and Clang non-PIC code may have call foo@PLT. GNU as
2352 * before 2.37 produces an unreferenced _GLOBAL_OFFSET_TABLE_ on x86-64.
2353 * i386 has a similar problem but may not deserve a fix.
2354 *
2355 * If we ever have to ignore many symbols, consider refactoring the code to
2356 * only warn if referenced by a relocation.
2357 */
2358 if (emachine == EM_386 || emachine == EM_X86_64)
2359 return !strcmp(name, "_GLOBAL_OFFSET_TABLE_");
2360 return false;
2361 }
2362
2363 /* Change all symbols so that st_value encodes the pointer directly. */
simplify_symbols(struct module * mod,const struct load_info * info)2364 static int simplify_symbols(struct module *mod, const struct load_info *info)
2365 {
2366 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2367 Elf_Sym *sym = (void *)symsec->sh_addr;
2368 unsigned long secbase;
2369 unsigned int i;
2370 int ret = 0;
2371 const struct kernel_symbol *ksym;
2372
2373 for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
2374 const char *name = info->strtab + sym[i].st_name;
2375
2376 switch (sym[i].st_shndx) {
2377 case SHN_COMMON:
2378 /* Ignore common symbols */
2379 if (!strncmp(name, "__gnu_lto", 9))
2380 break;
2381
2382 /* We compiled with -fno-common. These are not
2383 supposed to happen. */
2384 pr_debug("Common symbol: %s\n", name);
2385 pr_warn("%s: please compile with -fno-common\n",
2386 mod->name);
2387 ret = -ENOEXEC;
2388 break;
2389
2390 case SHN_ABS:
2391 /* Don't need to do anything */
2392 pr_debug("Absolute symbol: 0x%08lx\n",
2393 (long)sym[i].st_value);
2394 break;
2395
2396 case SHN_LIVEPATCH:
2397 /* Livepatch symbols are resolved by livepatch */
2398 break;
2399
2400 case SHN_UNDEF:
2401 ksym = resolve_symbol_wait(mod, info, name);
2402 /* Ok if resolved. */
2403 if (ksym && !IS_ERR(ksym)) {
2404 sym[i].st_value = kernel_symbol_value(ksym);
2405 break;
2406 }
2407
2408 /* Ok if weak or ignored. */
2409 if (!ksym &&
2410 (ELF_ST_BIND(sym[i].st_info) == STB_WEAK ||
2411 ignore_undef_symbol(info->hdr->e_machine, name)))
2412 break;
2413
2414 ret = PTR_ERR(ksym) ?: -ENOENT;
2415 pr_warn("%s: Unknown symbol %s (err %d)\n",
2416 mod->name, name, ret);
2417 break;
2418
2419 default:
2420 /* Divert to percpu allocation if a percpu var. */
2421 if (sym[i].st_shndx == info->index.pcpu)
2422 secbase = (unsigned long)mod_percpu(mod);
2423 else
2424 secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
2425 sym[i].st_value += secbase;
2426 break;
2427 }
2428 }
2429
2430 return ret;
2431 }
2432
apply_relocations(struct module * mod,const struct load_info * info)2433 static int apply_relocations(struct module *mod, const struct load_info *info)
2434 {
2435 unsigned int i;
2436 int err = 0;
2437
2438 /* Now do relocations. */
2439 for (i = 1; i < info->hdr->e_shnum; i++) {
2440 unsigned int infosec = info->sechdrs[i].sh_info;
2441
2442 /* Not a valid relocation section? */
2443 if (infosec >= info->hdr->e_shnum)
2444 continue;
2445
2446 /* Don't bother with non-allocated sections */
2447 if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
2448 continue;
2449
2450 if (info->sechdrs[i].sh_flags & SHF_RELA_LIVEPATCH)
2451 err = klp_apply_section_relocs(mod, info->sechdrs,
2452 info->secstrings,
2453 info->strtab,
2454 info->index.sym, i,
2455 NULL);
2456 else if (info->sechdrs[i].sh_type == SHT_REL)
2457 err = apply_relocate(info->sechdrs, info->strtab,
2458 info->index.sym, i, mod);
2459 else if (info->sechdrs[i].sh_type == SHT_RELA)
2460 err = apply_relocate_add(info->sechdrs, info->strtab,
2461 info->index.sym, i, mod);
2462 if (err < 0)
2463 break;
2464 }
2465 return err;
2466 }
2467
2468 /* Additional bytes needed by arch in front of individual sections */
arch_mod_section_prepend(struct module * mod,unsigned int section)2469 unsigned int __weak arch_mod_section_prepend(struct module *mod,
2470 unsigned int section)
2471 {
2472 /* default implementation just returns zero */
2473 return 0;
2474 }
2475
2476 /* Update size with this section: return offset. */
get_offset(struct module * mod,unsigned int * size,Elf_Shdr * sechdr,unsigned int section)2477 static long get_offset(struct module *mod, unsigned int *size,
2478 Elf_Shdr *sechdr, unsigned int section)
2479 {
2480 long ret;
2481
2482 *size += arch_mod_section_prepend(mod, section);
2483 ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
2484 *size = ret + sechdr->sh_size;
2485 return ret;
2486 }
2487
2488 /* Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
2489 might -- code, read-only data, read-write data, small data. Tally
2490 sizes, and place the offsets into sh_entsize fields: high bit means it
2491 belongs in init. */
layout_sections(struct module * mod,struct load_info * info)2492 static void layout_sections(struct module *mod, struct load_info *info)
2493 {
2494 static unsigned long const masks[][2] = {
2495 /* NOTE: all executable code must be the first section
2496 * in this array; otherwise modify the text_size
2497 * finder in the two loops below */
2498 { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
2499 { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
2500 { SHF_RO_AFTER_INIT | SHF_ALLOC, ARCH_SHF_SMALL },
2501 { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
2502 { ARCH_SHF_SMALL | SHF_ALLOC, 0 }
2503 };
2504 unsigned int m, i;
2505
2506 for (i = 0; i < info->hdr->e_shnum; i++)
2507 info->sechdrs[i].sh_entsize = ~0UL;
2508
2509 pr_debug("Core section allocation order:\n");
2510 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2511 for (i = 0; i < info->hdr->e_shnum; ++i) {
2512 Elf_Shdr *s = &info->sechdrs[i];
2513 const char *sname = info->secstrings + s->sh_name;
2514
2515 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2516 || (s->sh_flags & masks[m][1])
2517 || s->sh_entsize != ~0UL
2518 || module_init_layout_section(sname))
2519 continue;
2520 s->sh_entsize = get_offset(mod, &mod->core_layout.size, s, i);
2521 pr_debug("\t%s\n", sname);
2522 }
2523 switch (m) {
2524 case 0: /* executable */
2525 mod->core_layout.size = debug_align(mod->core_layout.size);
2526 mod->core_layout.text_size = mod->core_layout.size;
2527 break;
2528 case 1: /* RO: text and ro-data */
2529 mod->core_layout.size = debug_align(mod->core_layout.size);
2530 mod->core_layout.ro_size = mod->core_layout.size;
2531 break;
2532 case 2: /* RO after init */
2533 mod->core_layout.size = debug_align(mod->core_layout.size);
2534 mod->core_layout.ro_after_init_size = mod->core_layout.size;
2535 break;
2536 case 4: /* whole core */
2537 mod->core_layout.size = debug_align(mod->core_layout.size);
2538 break;
2539 }
2540 }
2541
2542 pr_debug("Init section allocation order:\n");
2543 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2544 for (i = 0; i < info->hdr->e_shnum; ++i) {
2545 Elf_Shdr *s = &info->sechdrs[i];
2546 const char *sname = info->secstrings + s->sh_name;
2547
2548 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2549 || (s->sh_flags & masks[m][1])
2550 || s->sh_entsize != ~0UL
2551 || !module_init_layout_section(sname))
2552 continue;
2553 s->sh_entsize = (get_offset(mod, &mod->init_layout.size, s, i)
2554 | INIT_OFFSET_MASK);
2555 pr_debug("\t%s\n", sname);
2556 }
2557 switch (m) {
2558 case 0: /* executable */
2559 mod->init_layout.size = debug_align(mod->init_layout.size);
2560 mod->init_layout.text_size = mod->init_layout.size;
2561 break;
2562 case 1: /* RO: text and ro-data */
2563 mod->init_layout.size = debug_align(mod->init_layout.size);
2564 mod->init_layout.ro_size = mod->init_layout.size;
2565 break;
2566 case 2:
2567 /*
2568 * RO after init doesn't apply to init_layout (only
2569 * core_layout), so it just takes the value of ro_size.
2570 */
2571 mod->init_layout.ro_after_init_size = mod->init_layout.ro_size;
2572 break;
2573 case 4: /* whole init */
2574 mod->init_layout.size = debug_align(mod->init_layout.size);
2575 break;
2576 }
2577 }
2578 }
2579
set_license(struct module * mod,const char * license)2580 static void set_license(struct module *mod, const char *license)
2581 {
2582 if (!license)
2583 license = "unspecified";
2584
2585 if (!license_is_gpl_compatible(license)) {
2586 if (!test_taint(TAINT_PROPRIETARY_MODULE))
2587 pr_warn("%s: module license '%s' taints kernel.\n",
2588 mod->name, license);
2589 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2590 LOCKDEP_NOW_UNRELIABLE);
2591 }
2592 }
2593
2594 /* Parse tag=value strings from .modinfo section */
next_string(char * string,unsigned long * secsize)2595 static char *next_string(char *string, unsigned long *secsize)
2596 {
2597 /* Skip non-zero chars */
2598 while (string[0]) {
2599 string++;
2600 if ((*secsize)-- <= 1)
2601 return NULL;
2602 }
2603
2604 /* Skip any zero padding. */
2605 while (!string[0]) {
2606 string++;
2607 if ((*secsize)-- <= 1)
2608 return NULL;
2609 }
2610 return string;
2611 }
2612
get_next_modinfo(const struct load_info * info,const char * tag,char * prev)2613 static char *get_next_modinfo(const struct load_info *info, const char *tag,
2614 char *prev)
2615 {
2616 char *p;
2617 unsigned int taglen = strlen(tag);
2618 Elf_Shdr *infosec = &info->sechdrs[info->index.info];
2619 unsigned long size = infosec->sh_size;
2620
2621 /*
2622 * get_modinfo() calls made before rewrite_section_headers()
2623 * must use sh_offset, as sh_addr isn't set!
2624 */
2625 char *modinfo = (char *)info->hdr + infosec->sh_offset;
2626
2627 if (prev) {
2628 size -= prev - modinfo;
2629 modinfo = next_string(prev, &size);
2630 }
2631
2632 for (p = modinfo; p; p = next_string(p, &size)) {
2633 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
2634 return p + taglen + 1;
2635 }
2636 return NULL;
2637 }
2638
get_modinfo(const struct load_info * info,const char * tag)2639 static char *get_modinfo(const struct load_info *info, const char *tag)
2640 {
2641 return get_next_modinfo(info, tag, NULL);
2642 }
2643
setup_modinfo(struct module * mod,struct load_info * info)2644 static void setup_modinfo(struct module *mod, struct load_info *info)
2645 {
2646 struct module_attribute *attr;
2647 int i;
2648
2649 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2650 if (attr->setup)
2651 attr->setup(mod, get_modinfo(info, attr->attr.name));
2652 }
2653 }
2654
free_modinfo(struct module * mod)2655 static void free_modinfo(struct module *mod)
2656 {
2657 struct module_attribute *attr;
2658 int i;
2659
2660 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2661 if (attr->free)
2662 attr->free(mod);
2663 }
2664 }
2665
2666 #ifdef CONFIG_KALLSYMS
2667
2668 /* 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)2669 static const struct kernel_symbol *lookup_exported_symbol(const char *name,
2670 const struct kernel_symbol *start,
2671 const struct kernel_symbol *stop)
2672 {
2673 return bsearch(name, start, stop - start,
2674 sizeof(struct kernel_symbol), cmp_name);
2675 }
2676
is_exported(const char * name,unsigned long value,const struct module * mod)2677 static int is_exported(const char *name, unsigned long value,
2678 const struct module *mod)
2679 {
2680 const struct kernel_symbol *ks;
2681 if (!mod)
2682 ks = lookup_exported_symbol(name, __start___ksymtab, __stop___ksymtab);
2683 else
2684 ks = lookup_exported_symbol(name, mod->syms, mod->syms + mod->num_syms);
2685
2686 return ks != NULL && kernel_symbol_value(ks) == value;
2687 }
2688
2689 /* As per nm */
elf_type(const Elf_Sym * sym,const struct load_info * info)2690 static char elf_type(const Elf_Sym *sym, const struct load_info *info)
2691 {
2692 const Elf_Shdr *sechdrs = info->sechdrs;
2693
2694 if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
2695 if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT)
2696 return 'v';
2697 else
2698 return 'w';
2699 }
2700 if (sym->st_shndx == SHN_UNDEF)
2701 return 'U';
2702 if (sym->st_shndx == SHN_ABS || sym->st_shndx == info->index.pcpu)
2703 return 'a';
2704 if (sym->st_shndx >= SHN_LORESERVE)
2705 return '?';
2706 if (sechdrs[sym->st_shndx].sh_flags & SHF_EXECINSTR)
2707 return 't';
2708 if (sechdrs[sym->st_shndx].sh_flags & SHF_ALLOC
2709 && sechdrs[sym->st_shndx].sh_type != SHT_NOBITS) {
2710 if (!(sechdrs[sym->st_shndx].sh_flags & SHF_WRITE))
2711 return 'r';
2712 else if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2713 return 'g';
2714 else
2715 return 'd';
2716 }
2717 if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
2718 if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2719 return 's';
2720 else
2721 return 'b';
2722 }
2723 if (strstarts(info->secstrings + sechdrs[sym->st_shndx].sh_name,
2724 ".debug")) {
2725 return 'n';
2726 }
2727 return '?';
2728 }
2729
is_core_symbol(const Elf_Sym * src,const Elf_Shdr * sechdrs,unsigned int shnum,unsigned int pcpundx)2730 static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
2731 unsigned int shnum, unsigned int pcpundx)
2732 {
2733 const Elf_Shdr *sec;
2734
2735 if (src->st_shndx == SHN_UNDEF
2736 || src->st_shndx >= shnum
2737 || !src->st_name)
2738 return false;
2739
2740 #ifdef CONFIG_KALLSYMS_ALL
2741 if (src->st_shndx == pcpundx)
2742 return true;
2743 #endif
2744
2745 sec = sechdrs + src->st_shndx;
2746 if (!(sec->sh_flags & SHF_ALLOC)
2747 #ifndef CONFIG_KALLSYMS_ALL
2748 || !(sec->sh_flags & SHF_EXECINSTR)
2749 #endif
2750 || (sec->sh_entsize & INIT_OFFSET_MASK))
2751 return false;
2752
2753 return true;
2754 }
2755
2756 /*
2757 * We only allocate and copy the strings needed by the parts of symtab
2758 * we keep. This is simple, but has the effect of making multiple
2759 * copies of duplicates. We could be more sophisticated, see
2760 * linux-kernel thread starting with
2761 * <73defb5e4bca04a6431392cc341112b1@localhost>.
2762 */
layout_symtab(struct module * mod,struct load_info * info)2763 static void layout_symtab(struct module *mod, struct load_info *info)
2764 {
2765 Elf_Shdr *symsect = info->sechdrs + info->index.sym;
2766 Elf_Shdr *strsect = info->sechdrs + info->index.str;
2767 const Elf_Sym *src;
2768 unsigned int i, nsrc, ndst, strtab_size = 0;
2769
2770 /* Put symbol section at end of init part of module. */
2771 symsect->sh_flags |= SHF_ALLOC;
2772 symsect->sh_entsize = get_offset(mod, &mod->init_layout.size, symsect,
2773 info->index.sym) | INIT_OFFSET_MASK;
2774 pr_debug("\t%s\n", info->secstrings + symsect->sh_name);
2775
2776 src = (void *)info->hdr + symsect->sh_offset;
2777 nsrc = symsect->sh_size / sizeof(*src);
2778
2779 /* Compute total space required for the core symbols' strtab. */
2780 for (ndst = i = 0; i < nsrc; i++) {
2781 if (i == 0 || is_livepatch_module(mod) ||
2782 is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum,
2783 info->index.pcpu)) {
2784 strtab_size += strlen(&info->strtab[src[i].st_name])+1;
2785 ndst++;
2786 }
2787 }
2788
2789 /* Append room for core symbols at end of core part. */
2790 info->symoffs = ALIGN(mod->core_layout.size, symsect->sh_addralign ?: 1);
2791 info->stroffs = mod->core_layout.size = info->symoffs + ndst * sizeof(Elf_Sym);
2792 mod->core_layout.size += strtab_size;
2793 info->core_typeoffs = mod->core_layout.size;
2794 mod->core_layout.size += ndst * sizeof(char);
2795 mod->core_layout.size = debug_align(mod->core_layout.size);
2796
2797 /* Put string table section at end of init part of module. */
2798 strsect->sh_flags |= SHF_ALLOC;
2799 strsect->sh_entsize = get_offset(mod, &mod->init_layout.size, strsect,
2800 info->index.str) | INIT_OFFSET_MASK;
2801 pr_debug("\t%s\n", info->secstrings + strsect->sh_name);
2802
2803 /* We'll tack temporary mod_kallsyms on the end. */
2804 mod->init_layout.size = ALIGN(mod->init_layout.size,
2805 __alignof__(struct mod_kallsyms));
2806 info->mod_kallsyms_init_off = mod->init_layout.size;
2807 mod->init_layout.size += sizeof(struct mod_kallsyms);
2808 info->init_typeoffs = mod->init_layout.size;
2809 mod->init_layout.size += nsrc * sizeof(char);
2810 mod->init_layout.size = debug_align(mod->init_layout.size);
2811 }
2812
2813 /*
2814 * We use the full symtab and strtab which layout_symtab arranged to
2815 * be appended to the init section. Later we switch to the cut-down
2816 * core-only ones.
2817 */
add_kallsyms(struct module * mod,const struct load_info * info)2818 static void add_kallsyms(struct module *mod, const struct load_info *info)
2819 {
2820 unsigned int i, ndst;
2821 const Elf_Sym *src;
2822 Elf_Sym *dst;
2823 char *s;
2824 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2825
2826 /* Set up to point into init section. */
2827 mod->kallsyms = mod->init_layout.base + info->mod_kallsyms_init_off;
2828
2829 mod->kallsyms->symtab = (void *)symsec->sh_addr;
2830 mod->kallsyms->num_symtab = symsec->sh_size / sizeof(Elf_Sym);
2831 /* Make sure we get permanent strtab: don't use info->strtab. */
2832 mod->kallsyms->strtab = (void *)info->sechdrs[info->index.str].sh_addr;
2833 mod->kallsyms->typetab = mod->init_layout.base + info->init_typeoffs;
2834
2835 /*
2836 * Now populate the cut down core kallsyms for after init
2837 * and set types up while we still have access to sections.
2838 */
2839 mod->core_kallsyms.symtab = dst = mod->core_layout.base + info->symoffs;
2840 mod->core_kallsyms.strtab = s = mod->core_layout.base + info->stroffs;
2841 mod->core_kallsyms.typetab = mod->core_layout.base + info->core_typeoffs;
2842 src = mod->kallsyms->symtab;
2843 for (ndst = i = 0; i < mod->kallsyms->num_symtab; i++) {
2844 mod->kallsyms->typetab[i] = elf_type(src + i, info);
2845 if (i == 0 || is_livepatch_module(mod) ||
2846 is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum,
2847 info->index.pcpu)) {
2848 mod->core_kallsyms.typetab[ndst] =
2849 mod->kallsyms->typetab[i];
2850 dst[ndst] = src[i];
2851 dst[ndst++].st_name = s - mod->core_kallsyms.strtab;
2852 s += strlcpy(s, &mod->kallsyms->strtab[src[i].st_name],
2853 KSYM_NAME_LEN) + 1;
2854 }
2855 }
2856 mod->core_kallsyms.num_symtab = ndst;
2857 }
2858 #else
layout_symtab(struct module * mod,struct load_info * info)2859 static inline void layout_symtab(struct module *mod, struct load_info *info)
2860 {
2861 }
2862
add_kallsyms(struct module * mod,const struct load_info * info)2863 static void add_kallsyms(struct module *mod, const struct load_info *info)
2864 {
2865 }
2866 #endif /* CONFIG_KALLSYMS */
2867
dynamic_debug_setup(struct module * mod,struct _ddebug * debug,unsigned int num)2868 static void dynamic_debug_setup(struct module *mod, struct _ddebug *debug, unsigned int num)
2869 {
2870 if (!debug)
2871 return;
2872 ddebug_add_module(debug, num, mod->name);
2873 }
2874
dynamic_debug_remove(struct module * mod,struct _ddebug * debug)2875 static void dynamic_debug_remove(struct module *mod, struct _ddebug *debug)
2876 {
2877 if (debug)
2878 ddebug_remove_module(mod->name);
2879 }
2880
module_alloc(unsigned long size)2881 void * __weak module_alloc(unsigned long size)
2882 {
2883 return __vmalloc_node_range(size, 1, VMALLOC_START, VMALLOC_END,
2884 GFP_KERNEL, PAGE_KERNEL_EXEC, VM_FLUSH_RESET_PERMS,
2885 NUMA_NO_NODE, __builtin_return_address(0));
2886 }
2887
module_init_section(const char * name)2888 bool __weak module_init_section(const char *name)
2889 {
2890 return strstarts(name, ".init");
2891 }
2892
module_exit_section(const char * name)2893 bool __weak module_exit_section(const char *name)
2894 {
2895 return strstarts(name, ".exit");
2896 }
2897
2898 #ifdef CONFIG_DEBUG_KMEMLEAK
kmemleak_load_module(const struct module * mod,const struct load_info * info)2899 static void kmemleak_load_module(const struct module *mod,
2900 const struct load_info *info)
2901 {
2902 unsigned int i;
2903
2904 /* only scan the sections containing data */
2905 kmemleak_scan_area(mod, sizeof(struct module), GFP_KERNEL);
2906
2907 for (i = 1; i < info->hdr->e_shnum; i++) {
2908 /* Scan all writable sections that's not executable */
2909 if (!(info->sechdrs[i].sh_flags & SHF_ALLOC) ||
2910 !(info->sechdrs[i].sh_flags & SHF_WRITE) ||
2911 (info->sechdrs[i].sh_flags & SHF_EXECINSTR))
2912 continue;
2913
2914 kmemleak_scan_area((void *)info->sechdrs[i].sh_addr,
2915 info->sechdrs[i].sh_size, GFP_KERNEL);
2916 }
2917 }
2918 #else
kmemleak_load_module(const struct module * mod,const struct load_info * info)2919 static inline void kmemleak_load_module(const struct module *mod,
2920 const struct load_info *info)
2921 {
2922 }
2923 #endif
2924
2925 #ifdef CONFIG_MODULE_SIG
module_sig_check(struct load_info * info,int flags)2926 static int module_sig_check(struct load_info *info, int flags)
2927 {
2928 int err = -ENODATA;
2929 const unsigned long markerlen = sizeof(MODULE_SIG_STRING) - 1;
2930 const char *reason;
2931 const void *mod = info->hdr;
2932
2933 /*
2934 * Require flags == 0, as a module with version information
2935 * removed is no longer the module that was signed
2936 */
2937 if (flags == 0 &&
2938 info->len > markerlen &&
2939 memcmp(mod + info->len - markerlen, MODULE_SIG_STRING, markerlen) == 0) {
2940 /* We truncate the module to discard the signature */
2941 info->len -= markerlen;
2942 err = mod_verify_sig(mod, info);
2943 }
2944
2945 switch (err) {
2946 case 0:
2947 info->sig_ok = true;
2948 return 0;
2949
2950 /* We don't permit modules to be loaded into trusted kernels
2951 * without a valid signature on them, but if we're not
2952 * enforcing, certain errors are non-fatal.
2953 */
2954 case -ENODATA:
2955 reason = "unsigned module";
2956 break;
2957 case -ENOPKG:
2958 reason = "module with unsupported crypto";
2959 break;
2960 case -ENOKEY:
2961 reason = "module with unavailable key";
2962 break;
2963
2964 /* All other errors are fatal, including nomem, unparseable
2965 * signatures and signature check failures - even if signatures
2966 * aren't required.
2967 */
2968 default:
2969 return err;
2970 }
2971
2972 if (is_module_sig_enforced()) {
2973 pr_notice("Loading of %s is rejected\n", reason);
2974 return -EKEYREJECTED;
2975 }
2976
2977 return security_locked_down(LOCKDOWN_MODULE_SIGNATURE);
2978 }
2979 #else /* !CONFIG_MODULE_SIG */
module_sig_check(struct load_info * info,int flags)2980 static int module_sig_check(struct load_info *info, int flags)
2981 {
2982 return 0;
2983 }
2984 #endif /* !CONFIG_MODULE_SIG */
2985
validate_section_offset(struct load_info * info,Elf_Shdr * shdr)2986 static int validate_section_offset(struct load_info *info, Elf_Shdr *shdr)
2987 {
2988 unsigned long secend;
2989
2990 /*
2991 * Check for both overflow and offset/size being
2992 * too large.
2993 */
2994 secend = shdr->sh_offset + shdr->sh_size;
2995 if (secend < shdr->sh_offset || secend > info->len)
2996 return -ENOEXEC;
2997
2998 return 0;
2999 }
3000
3001 /*
3002 * Sanity checks against invalid binaries, wrong arch, weird elf version.
3003 *
3004 * Also do basic validity checks against section offsets and sizes, the
3005 * section name string table, and the indices used for it (sh_name).
3006 */
elf_validity_check(struct load_info * info)3007 static int elf_validity_check(struct load_info *info)
3008 {
3009 unsigned int i;
3010 Elf_Shdr *shdr, *strhdr;
3011 int err;
3012
3013 if (info->len < sizeof(*(info->hdr)))
3014 return -ENOEXEC;
3015
3016 if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0
3017 || info->hdr->e_type != ET_REL
3018 || !elf_check_arch(info->hdr)
3019 || info->hdr->e_shentsize != sizeof(Elf_Shdr))
3020 return -ENOEXEC;
3021
3022 /*
3023 * e_shnum is 16 bits, and sizeof(Elf_Shdr) is
3024 * known and small. So e_shnum * sizeof(Elf_Shdr)
3025 * will not overflow unsigned long on any platform.
3026 */
3027 if (info->hdr->e_shoff >= info->len
3028 || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
3029 info->len - info->hdr->e_shoff))
3030 return -ENOEXEC;
3031
3032 info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
3033
3034 /*
3035 * Verify if the section name table index is valid.
3036 */
3037 if (info->hdr->e_shstrndx == SHN_UNDEF
3038 || info->hdr->e_shstrndx >= info->hdr->e_shnum)
3039 return -ENOEXEC;
3040
3041 strhdr = &info->sechdrs[info->hdr->e_shstrndx];
3042 err = validate_section_offset(info, strhdr);
3043 if (err < 0)
3044 return err;
3045
3046 /*
3047 * The section name table must be NUL-terminated, as required
3048 * by the spec. This makes strcmp and pr_* calls that access
3049 * strings in the section safe.
3050 */
3051 info->secstrings = (void *)info->hdr + strhdr->sh_offset;
3052 if (info->secstrings[strhdr->sh_size - 1] != '\0')
3053 return -ENOEXEC;
3054
3055 /*
3056 * The code assumes that section 0 has a length of zero and
3057 * an addr of zero, so check for it.
3058 */
3059 if (info->sechdrs[0].sh_type != SHT_NULL
3060 || info->sechdrs[0].sh_size != 0
3061 || info->sechdrs[0].sh_addr != 0)
3062 return -ENOEXEC;
3063
3064 for (i = 1; i < info->hdr->e_shnum; i++) {
3065 shdr = &info->sechdrs[i];
3066 switch (shdr->sh_type) {
3067 case SHT_NULL:
3068 case SHT_NOBITS:
3069 continue;
3070 case SHT_SYMTAB:
3071 if (shdr->sh_link == SHN_UNDEF
3072 || shdr->sh_link >= info->hdr->e_shnum)
3073 return -ENOEXEC;
3074 fallthrough;
3075 default:
3076 err = validate_section_offset(info, shdr);
3077 if (err < 0) {
3078 pr_err("Invalid ELF section in module (section %u type %u)\n",
3079 i, shdr->sh_type);
3080 return err;
3081 }
3082
3083 if (shdr->sh_flags & SHF_ALLOC) {
3084 if (shdr->sh_name >= strhdr->sh_size) {
3085 pr_err("Invalid ELF section name in module (section %u type %u)\n",
3086 i, shdr->sh_type);
3087 return -ENOEXEC;
3088 }
3089 }
3090 break;
3091 }
3092 }
3093
3094 return 0;
3095 }
3096
3097 #define COPY_CHUNK_SIZE (16*PAGE_SIZE)
3098
copy_chunked_from_user(void * dst,const void __user * usrc,unsigned long len)3099 static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len)
3100 {
3101 do {
3102 unsigned long n = min(len, COPY_CHUNK_SIZE);
3103
3104 if (copy_from_user(dst, usrc, n) != 0)
3105 return -EFAULT;
3106 cond_resched();
3107 dst += n;
3108 usrc += n;
3109 len -= n;
3110 } while (len);
3111 return 0;
3112 }
3113
3114 #ifdef CONFIG_LIVEPATCH
check_modinfo_livepatch(struct module * mod,struct load_info * info)3115 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
3116 {
3117 if (get_modinfo(info, "livepatch")) {
3118 mod->klp = true;
3119 add_taint_module(mod, TAINT_LIVEPATCH, LOCKDEP_STILL_OK);
3120 pr_notice_once("%s: tainting kernel with TAINT_LIVEPATCH\n",
3121 mod->name);
3122 }
3123
3124 return 0;
3125 }
3126 #else /* !CONFIG_LIVEPATCH */
check_modinfo_livepatch(struct module * mod,struct load_info * info)3127 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
3128 {
3129 if (get_modinfo(info, "livepatch")) {
3130 pr_err("%s: module is marked as livepatch module, but livepatch support is disabled",
3131 mod->name);
3132 return -ENOEXEC;
3133 }
3134
3135 return 0;
3136 }
3137 #endif /* CONFIG_LIVEPATCH */
3138
check_modinfo_retpoline(struct module * mod,struct load_info * info)3139 static void check_modinfo_retpoline(struct module *mod, struct load_info *info)
3140 {
3141 if (retpoline_module_ok(get_modinfo(info, "retpoline")))
3142 return;
3143
3144 pr_warn("%s: loading module not compiled with retpoline compiler.\n",
3145 mod->name);
3146 }
3147
3148 /* Sets info->hdr and info->len. */
copy_module_from_user(const void __user * umod,unsigned long len,struct load_info * info)3149 static int copy_module_from_user(const void __user *umod, unsigned long len,
3150 struct load_info *info)
3151 {
3152 int err;
3153
3154 info->len = len;
3155 if (info->len < sizeof(*(info->hdr)))
3156 return -ENOEXEC;
3157
3158 err = security_kernel_load_data(LOADING_MODULE, true);
3159 if (err)
3160 return err;
3161
3162 /* Suck in entire file: we'll want most of it. */
3163 info->hdr = __vmalloc(info->len, GFP_KERNEL | __GFP_NOWARN);
3164 if (!info->hdr)
3165 return -ENOMEM;
3166
3167 if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) {
3168 err = -EFAULT;
3169 goto out;
3170 }
3171
3172 err = security_kernel_post_load_data((char *)info->hdr, info->len,
3173 LOADING_MODULE, "init_module");
3174 out:
3175 if (err)
3176 vfree(info->hdr);
3177
3178 return err;
3179 }
3180
free_copy(struct load_info * info)3181 static void free_copy(struct load_info *info)
3182 {
3183 vfree(info->hdr);
3184 }
3185
rewrite_section_headers(struct load_info * info,int flags)3186 static int rewrite_section_headers(struct load_info *info, int flags)
3187 {
3188 unsigned int i;
3189
3190 /* This should always be true, but let's be sure. */
3191 info->sechdrs[0].sh_addr = 0;
3192
3193 for (i = 1; i < info->hdr->e_shnum; i++) {
3194 Elf_Shdr *shdr = &info->sechdrs[i];
3195
3196 /* Mark all sections sh_addr with their address in the
3197 temporary image. */
3198 shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
3199
3200 }
3201
3202 /* Track but don't keep modinfo and version sections. */
3203 info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
3204 info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
3205
3206 return 0;
3207 }
3208
3209 /*
3210 * Set up our basic convenience variables (pointers to section headers,
3211 * search for module section index etc), and do some basic section
3212 * verification.
3213 *
3214 * Set info->mod to the temporary copy of the module in info->hdr. The final one
3215 * will be allocated in move_module().
3216 */
setup_load_info(struct load_info * info,int flags)3217 static int setup_load_info(struct load_info *info, int flags)
3218 {
3219 unsigned int i;
3220
3221 /* Try to find a name early so we can log errors with a module name */
3222 info->index.info = find_sec(info, ".modinfo");
3223 if (info->index.info)
3224 info->name = get_modinfo(info, "name");
3225
3226 /* Find internal symbols and strings. */
3227 for (i = 1; i < info->hdr->e_shnum; i++) {
3228 if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
3229 info->index.sym = i;
3230 info->index.str = info->sechdrs[i].sh_link;
3231 info->strtab = (char *)info->hdr
3232 + info->sechdrs[info->index.str].sh_offset;
3233 break;
3234 }
3235 }
3236
3237 if (info->index.sym == 0) {
3238 pr_warn("%s: module has no symbols (stripped?)\n",
3239 info->name ?: "(missing .modinfo section or name field)");
3240 return -ENOEXEC;
3241 }
3242
3243 info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
3244 if (!info->index.mod) {
3245 pr_warn("%s: No module found in object\n",
3246 info->name ?: "(missing .modinfo section or name field)");
3247 return -ENOEXEC;
3248 }
3249 /* This is temporary: point mod into copy of data. */
3250 info->mod = (void *)info->hdr + info->sechdrs[info->index.mod].sh_offset;
3251
3252 /*
3253 * If we didn't load the .modinfo 'name' field earlier, fall back to
3254 * on-disk struct mod 'name' field.
3255 */
3256 if (!info->name)
3257 info->name = info->mod->name;
3258
3259 if (flags & MODULE_INIT_IGNORE_MODVERSIONS)
3260 info->index.vers = 0; /* Pretend no __versions section! */
3261 else
3262 info->index.vers = find_sec(info, "__versions");
3263
3264 info->index.pcpu = find_pcpusec(info);
3265
3266 return 0;
3267 }
3268
check_modinfo(struct module * mod,struct load_info * info,int flags)3269 static int check_modinfo(struct module *mod, struct load_info *info, int flags)
3270 {
3271 const char *modmagic = get_modinfo(info, "vermagic");
3272 int err;
3273
3274 if (flags & MODULE_INIT_IGNORE_VERMAGIC)
3275 modmagic = NULL;
3276
3277 /* This is allowed: modprobe --force will invalidate it. */
3278 if (!modmagic) {
3279 err = try_to_force_load(mod, "bad vermagic");
3280 if (err)
3281 return err;
3282 } else if (!same_magic(modmagic, vermagic, info->index.vers)) {
3283 pr_err("%s: version magic '%s' should be '%s'\n",
3284 info->name, modmagic, vermagic);
3285 return -ENOEXEC;
3286 }
3287
3288 if (!get_modinfo(info, "intree")) {
3289 if (!test_taint(TAINT_OOT_MODULE))
3290 pr_warn("%s: loading out-of-tree module taints kernel.\n",
3291 mod->name);
3292 add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
3293 }
3294
3295 check_modinfo_retpoline(mod, info);
3296
3297 if (get_modinfo(info, "staging")) {
3298 add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
3299 pr_warn("%s: module is from the staging directory, the quality "
3300 "is unknown, you have been warned.\n", mod->name);
3301 }
3302
3303 err = check_modinfo_livepatch(mod, info);
3304 if (err)
3305 return err;
3306
3307 /* Set up license info based on the info section */
3308 set_license(mod, get_modinfo(info, "license"));
3309
3310 return 0;
3311 }
3312
find_module_sections(struct module * mod,struct load_info * info)3313 static int find_module_sections(struct module *mod, struct load_info *info)
3314 {
3315 mod->kp = section_objs(info, "__param",
3316 sizeof(*mod->kp), &mod->num_kp);
3317 mod->syms = section_objs(info, "__ksymtab",
3318 sizeof(*mod->syms), &mod->num_syms);
3319 mod->crcs = section_addr(info, "__kcrctab");
3320 mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
3321 sizeof(*mod->gpl_syms),
3322 &mod->num_gpl_syms);
3323 mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
3324 mod->gpl_future_syms = section_objs(info,
3325 "__ksymtab_gpl_future",
3326 sizeof(*mod->gpl_future_syms),
3327 &mod->num_gpl_future_syms);
3328 mod->gpl_future_crcs = section_addr(info, "__kcrctab_gpl_future");
3329
3330 #ifdef CONFIG_UNUSED_SYMBOLS
3331 mod->unused_syms = section_objs(info, "__ksymtab_unused",
3332 sizeof(*mod->unused_syms),
3333 &mod->num_unused_syms);
3334 mod->unused_crcs = section_addr(info, "__kcrctab_unused");
3335 mod->unused_gpl_syms = section_objs(info, "__ksymtab_unused_gpl",
3336 sizeof(*mod->unused_gpl_syms),
3337 &mod->num_unused_gpl_syms);
3338 mod->unused_gpl_crcs = section_addr(info, "__kcrctab_unused_gpl");
3339 #endif
3340 #ifdef CONFIG_CONSTRUCTORS
3341 mod->ctors = section_objs(info, ".ctors",
3342 sizeof(*mod->ctors), &mod->num_ctors);
3343 if (!mod->ctors)
3344 mod->ctors = section_objs(info, ".init_array",
3345 sizeof(*mod->ctors), &mod->num_ctors);
3346 else if (find_sec(info, ".init_array")) {
3347 /*
3348 * This shouldn't happen with same compiler and binutils
3349 * building all parts of the module.
3350 */
3351 pr_warn("%s: has both .ctors and .init_array.\n",
3352 mod->name);
3353 return -EINVAL;
3354 }
3355 #endif
3356
3357 mod->noinstr_text_start = section_objs(info, ".noinstr.text", 1,
3358 &mod->noinstr_text_size);
3359
3360 #ifdef CONFIG_TRACEPOINTS
3361 mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
3362 sizeof(*mod->tracepoints_ptrs),
3363 &mod->num_tracepoints);
3364 #endif
3365 #ifdef CONFIG_TREE_SRCU
3366 mod->srcu_struct_ptrs = section_objs(info, "___srcu_struct_ptrs",
3367 sizeof(*mod->srcu_struct_ptrs),
3368 &mod->num_srcu_structs);
3369 #endif
3370 #ifdef CONFIG_BPF_EVENTS
3371 mod->bpf_raw_events = section_objs(info, "__bpf_raw_tp_map",
3372 sizeof(*mod->bpf_raw_events),
3373 &mod->num_bpf_raw_events);
3374 #endif
3375 #ifdef CONFIG_JUMP_LABEL
3376 mod->jump_entries = section_objs(info, "__jump_table",
3377 sizeof(*mod->jump_entries),
3378 &mod->num_jump_entries);
3379 #endif
3380 #ifdef CONFIG_EVENT_TRACING
3381 mod->trace_events = section_objs(info, "_ftrace_events",
3382 sizeof(*mod->trace_events),
3383 &mod->num_trace_events);
3384 mod->trace_evals = section_objs(info, "_ftrace_eval_map",
3385 sizeof(*mod->trace_evals),
3386 &mod->num_trace_evals);
3387 #endif
3388 #ifdef CONFIG_TRACING
3389 mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
3390 sizeof(*mod->trace_bprintk_fmt_start),
3391 &mod->num_trace_bprintk_fmt);
3392 #endif
3393 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
3394 /* sechdrs[0].sh_size is always zero */
3395 mod->ftrace_callsites = section_objs(info, FTRACE_CALLSITE_SECTION,
3396 sizeof(*mod->ftrace_callsites),
3397 &mod->num_ftrace_callsites);
3398 #endif
3399 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
3400 mod->ei_funcs = section_objs(info, "_error_injection_whitelist",
3401 sizeof(*mod->ei_funcs),
3402 &mod->num_ei_funcs);
3403 #endif
3404 #ifdef CONFIG_KPROBES
3405 mod->kprobes_text_start = section_objs(info, ".kprobes.text", 1,
3406 &mod->kprobes_text_size);
3407 mod->kprobe_blacklist = section_objs(info, "_kprobe_blacklist",
3408 sizeof(unsigned long),
3409 &mod->num_kprobe_blacklist);
3410 #endif
3411 #ifdef CONFIG_HAVE_STATIC_CALL_INLINE
3412 mod->static_call_sites = section_objs(info, ".static_call_sites",
3413 sizeof(*mod->static_call_sites),
3414 &mod->num_static_call_sites);
3415 #endif
3416 mod->extable = section_objs(info, "__ex_table",
3417 sizeof(*mod->extable), &mod->num_exentries);
3418
3419 if (section_addr(info, "__obsparm"))
3420 pr_warn("%s: Ignoring obsolete parameters\n", mod->name);
3421
3422 info->debug = section_objs(info, "__dyndbg",
3423 sizeof(*info->debug), &info->num_debug);
3424
3425 return 0;
3426 }
3427
move_module(struct module * mod,struct load_info * info)3428 static int move_module(struct module *mod, struct load_info *info)
3429 {
3430 int i;
3431 void *ptr;
3432
3433 /* Do the allocs. */
3434 ptr = module_alloc(mod->core_layout.size);
3435 /*
3436 * The pointer to this block is stored in the module structure
3437 * which is inside the block. Just mark it as not being a
3438 * leak.
3439 */
3440 kmemleak_not_leak(ptr);
3441 if (!ptr)
3442 return -ENOMEM;
3443
3444 memset(ptr, 0, mod->core_layout.size);
3445 mod->core_layout.base = ptr;
3446
3447 if (mod->init_layout.size) {
3448 ptr = module_alloc(mod->init_layout.size);
3449 /*
3450 * The pointer to this block is stored in the module structure
3451 * which is inside the block. This block doesn't need to be
3452 * scanned as it contains data and code that will be freed
3453 * after the module is initialized.
3454 */
3455 kmemleak_ignore(ptr);
3456 if (!ptr) {
3457 module_memfree(mod->core_layout.base);
3458 return -ENOMEM;
3459 }
3460 memset(ptr, 0, mod->init_layout.size);
3461 mod->init_layout.base = ptr;
3462 } else
3463 mod->init_layout.base = NULL;
3464
3465 /* Transfer each section which specifies SHF_ALLOC */
3466 pr_debug("final section addresses:\n");
3467 for (i = 0; i < info->hdr->e_shnum; i++) {
3468 void *dest;
3469 Elf_Shdr *shdr = &info->sechdrs[i];
3470
3471 if (!(shdr->sh_flags & SHF_ALLOC))
3472 continue;
3473
3474 if (shdr->sh_entsize & INIT_OFFSET_MASK)
3475 dest = mod->init_layout.base
3476 + (shdr->sh_entsize & ~INIT_OFFSET_MASK);
3477 else
3478 dest = mod->core_layout.base + shdr->sh_entsize;
3479
3480 if (shdr->sh_type != SHT_NOBITS)
3481 memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
3482 /* Update sh_addr to point to copy in image. */
3483 shdr->sh_addr = (unsigned long)dest;
3484 pr_debug("\t0x%lx %s\n",
3485 (long)shdr->sh_addr, info->secstrings + shdr->sh_name);
3486 }
3487
3488 return 0;
3489 }
3490
check_module_license_and_versions(struct module * mod)3491 static int check_module_license_and_versions(struct module *mod)
3492 {
3493 int prev_taint = test_taint(TAINT_PROPRIETARY_MODULE);
3494
3495 /*
3496 * ndiswrapper is under GPL by itself, but loads proprietary modules.
3497 * Don't use add_taint_module(), as it would prevent ndiswrapper from
3498 * using GPL-only symbols it needs.
3499 */
3500 if (strcmp(mod->name, "ndiswrapper") == 0)
3501 add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
3502
3503 /* driverloader was caught wrongly pretending to be under GPL */
3504 if (strcmp(mod->name, "driverloader") == 0)
3505 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
3506 LOCKDEP_NOW_UNRELIABLE);
3507
3508 /* lve claims to be GPL but upstream won't provide source */
3509 if (strcmp(mod->name, "lve") == 0)
3510 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
3511 LOCKDEP_NOW_UNRELIABLE);
3512
3513 if (!prev_taint && test_taint(TAINT_PROPRIETARY_MODULE))
3514 pr_warn("%s: module license taints kernel.\n", mod->name);
3515
3516 #ifdef CONFIG_MODVERSIONS
3517 if ((mod->num_syms && !mod->crcs)
3518 || (mod->num_gpl_syms && !mod->gpl_crcs)
3519 || (mod->num_gpl_future_syms && !mod->gpl_future_crcs)
3520 #ifdef CONFIG_UNUSED_SYMBOLS
3521 || (mod->num_unused_syms && !mod->unused_crcs)
3522 || (mod->num_unused_gpl_syms && !mod->unused_gpl_crcs)
3523 #endif
3524 ) {
3525 return try_to_force_load(mod,
3526 "no versions for exported symbols");
3527 }
3528 #endif
3529 return 0;
3530 }
3531
flush_module_icache(const struct module * mod)3532 static void flush_module_icache(const struct module *mod)
3533 {
3534 /*
3535 * Flush the instruction cache, since we've played with text.
3536 * Do it before processing of module parameters, so the module
3537 * can provide parameter accessor functions of its own.
3538 */
3539 if (mod->init_layout.base)
3540 flush_icache_range((unsigned long)mod->init_layout.base,
3541 (unsigned long)mod->init_layout.base
3542 + mod->init_layout.size);
3543 flush_icache_range((unsigned long)mod->core_layout.base,
3544 (unsigned long)mod->core_layout.base + mod->core_layout.size);
3545 }
3546
module_frob_arch_sections(Elf_Ehdr * hdr,Elf_Shdr * sechdrs,char * secstrings,struct module * mod)3547 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
3548 Elf_Shdr *sechdrs,
3549 char *secstrings,
3550 struct module *mod)
3551 {
3552 return 0;
3553 }
3554
3555 /* module_blacklist is a comma-separated list of module names */
3556 static char *module_blacklist;
blacklisted(const char * module_name)3557 static bool blacklisted(const char *module_name)
3558 {
3559 const char *p;
3560 size_t len;
3561
3562 if (!module_blacklist)
3563 return false;
3564
3565 for (p = module_blacklist; *p; p += len) {
3566 len = strcspn(p, ",");
3567 if (strlen(module_name) == len && !memcmp(module_name, p, len))
3568 return true;
3569 if (p[len] == ',')
3570 len++;
3571 }
3572 return false;
3573 }
3574 core_param(module_blacklist, module_blacklist, charp, 0400);
3575
layout_and_allocate(struct load_info * info,int flags)3576 static struct module *layout_and_allocate(struct load_info *info, int flags)
3577 {
3578 struct module *mod;
3579 unsigned int ndx;
3580 int err;
3581
3582 err = check_modinfo(info->mod, info, flags);
3583 if (err)
3584 return ERR_PTR(err);
3585
3586 /* Allow arches to frob section contents and sizes. */
3587 err = module_frob_arch_sections(info->hdr, info->sechdrs,
3588 info->secstrings, info->mod);
3589 if (err < 0)
3590 return ERR_PTR(err);
3591
3592 err = module_enforce_rwx_sections(info->hdr, info->sechdrs,
3593 info->secstrings, info->mod);
3594 if (err < 0)
3595 return ERR_PTR(err);
3596
3597 /* We will do a special allocation for per-cpu sections later. */
3598 info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
3599
3600 /*
3601 * Mark ro_after_init section with SHF_RO_AFTER_INIT so that
3602 * layout_sections() can put it in the right place.
3603 * Note: ro_after_init sections also have SHF_{WRITE,ALLOC} set.
3604 */
3605 ndx = find_sec(info, ".data..ro_after_init");
3606 if (ndx)
3607 info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
3608 /*
3609 * Mark the __jump_table section as ro_after_init as well: these data
3610 * structures are never modified, with the exception of entries that
3611 * refer to code in the __init section, which are annotated as such
3612 * at module load time.
3613 */
3614 ndx = find_sec(info, "__jump_table");
3615 if (ndx)
3616 info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
3617
3618 /* Determine total sizes, and put offsets in sh_entsize. For now
3619 this is done generically; there doesn't appear to be any
3620 special cases for the architectures. */
3621 layout_sections(info->mod, info);
3622 layout_symtab(info->mod, info);
3623
3624 /* Allocate and move to the final place */
3625 err = move_module(info->mod, info);
3626 if (err)
3627 return ERR_PTR(err);
3628
3629 /* Module has been copied to its final place now: return it. */
3630 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
3631 kmemleak_load_module(mod, info);
3632 return mod;
3633 }
3634
3635 /* mod is no longer valid after this! */
module_deallocate(struct module * mod,struct load_info * info)3636 static void module_deallocate(struct module *mod, struct load_info *info)
3637 {
3638 percpu_modfree(mod);
3639 module_arch_freeing_init(mod);
3640 trace_android_vh_set_memory_rw((unsigned long)mod->init_layout.base,
3641 (mod->init_layout.size)>>PAGE_SHIFT);
3642 trace_android_vh_set_memory_nx((unsigned long)mod->init_layout.base,
3643 (mod->init_layout.size)>>PAGE_SHIFT);
3644 module_memfree(mod->init_layout.base);
3645 trace_android_vh_set_memory_rw((unsigned long)mod->core_layout.base,
3646 (mod->core_layout.size)>>PAGE_SHIFT);
3647 trace_android_vh_set_memory_nx((unsigned long)mod->core_layout.base,
3648 (mod->core_layout.size)>>PAGE_SHIFT);
3649 module_memfree(mod->core_layout.base);
3650 }
3651
module_finalize(const Elf_Ehdr * hdr,const Elf_Shdr * sechdrs,struct module * me)3652 int __weak module_finalize(const Elf_Ehdr *hdr,
3653 const Elf_Shdr *sechdrs,
3654 struct module *me)
3655 {
3656 return 0;
3657 }
3658
post_relocation(struct module * mod,const struct load_info * info)3659 static int post_relocation(struct module *mod, const struct load_info *info)
3660 {
3661 /* Sort exception table now relocations are done. */
3662 sort_extable(mod->extable, mod->extable + mod->num_exentries);
3663
3664 /* Copy relocated percpu area over. */
3665 percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
3666 info->sechdrs[info->index.pcpu].sh_size);
3667
3668 /* Setup kallsyms-specific fields. */
3669 add_kallsyms(mod, info);
3670
3671 /* Arch-specific module finalizing. */
3672 return module_finalize(info->hdr, info->sechdrs, mod);
3673 }
3674
3675 /* Is this module of this name done loading? No locks held. */
finished_loading(const char * name)3676 static bool finished_loading(const char *name)
3677 {
3678 struct module *mod;
3679 bool ret;
3680
3681 /*
3682 * The module_mutex should not be a heavily contended lock;
3683 * if we get the occasional sleep here, we'll go an extra iteration
3684 * in the wait_event_interruptible(), which is harmless.
3685 */
3686 sched_annotate_sleep();
3687 mutex_lock(&module_mutex);
3688 mod = find_module_all(name, strlen(name), true);
3689 ret = !mod || mod->state == MODULE_STATE_LIVE;
3690 mutex_unlock(&module_mutex);
3691
3692 return ret;
3693 }
3694
3695 /* Call module constructors. */
do_mod_ctors(struct module * mod)3696 static void do_mod_ctors(struct module *mod)
3697 {
3698 #ifdef CONFIG_CONSTRUCTORS
3699 unsigned long i;
3700
3701 for (i = 0; i < mod->num_ctors; i++)
3702 mod->ctors[i]();
3703 #endif
3704 }
3705
3706 /* For freeing module_init on success, in case kallsyms traversing */
3707 struct mod_initfree {
3708 struct llist_node node;
3709 void *module_init;
3710 };
3711
do_free_init(struct work_struct * w)3712 static void do_free_init(struct work_struct *w)
3713 {
3714 struct llist_node *pos, *n, *list;
3715 struct mod_initfree *initfree;
3716
3717 list = llist_del_all(&init_free_list);
3718
3719 synchronize_rcu();
3720
3721 llist_for_each_safe(pos, n, list) {
3722 initfree = container_of(pos, struct mod_initfree, node);
3723 module_memfree(initfree->module_init);
3724 kfree(initfree);
3725 }
3726 }
3727
3728 /*
3729 * This is where the real work happens.
3730 *
3731 * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb
3732 * helper command 'lx-symbols'.
3733 */
do_init_module(struct module * mod)3734 static noinline int do_init_module(struct module *mod)
3735 {
3736 int ret = 0;
3737 struct mod_initfree *freeinit;
3738
3739 freeinit = kmalloc(sizeof(*freeinit), GFP_KERNEL);
3740 if (!freeinit) {
3741 ret = -ENOMEM;
3742 goto fail;
3743 }
3744 freeinit->module_init = mod->init_layout.base;
3745
3746 do_mod_ctors(mod);
3747 /* Start the module */
3748 if (mod->init != NULL)
3749 ret = do_one_initcall(mod->init);
3750 if (ret < 0) {
3751 goto fail_free_freeinit;
3752 }
3753 if (ret > 0) {
3754 pr_warn("%s: '%s'->init suspiciously returned %d, it should "
3755 "follow 0/-E convention\n"
3756 "%s: loading module anyway...\n",
3757 __func__, mod->name, ret, __func__);
3758 dump_stack();
3759 }
3760
3761 /* Now it's a first class citizen! */
3762 mod->state = MODULE_STATE_LIVE;
3763 blocking_notifier_call_chain(&module_notify_list,
3764 MODULE_STATE_LIVE, mod);
3765
3766 /* Delay uevent until module has finished its init routine */
3767 kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
3768
3769 /*
3770 * We need to finish all async code before the module init sequence
3771 * is done. This has potential to deadlock if synchronous module
3772 * loading is requested from async (which is not allowed!).
3773 *
3774 * See commit 0fdff3ec6d87 ("async, kmod: warn on synchronous
3775 * request_module() from async workers") for more details.
3776 */
3777 if (!mod->async_probe_requested)
3778 async_synchronize_full();
3779
3780 ftrace_free_mem(mod, mod->init_layout.base, mod->init_layout.base +
3781 mod->init_layout.size);
3782 mutex_lock(&module_mutex);
3783 /* Drop initial reference. */
3784 module_put(mod);
3785 trim_init_extable(mod);
3786 #ifdef CONFIG_KALLSYMS
3787 /* Switch to core kallsyms now init is done: kallsyms may be walking! */
3788 rcu_assign_pointer(mod->kallsyms, &mod->core_kallsyms);
3789 #endif
3790 module_enable_ro(mod, true);
3791 trace_android_vh_set_module_permit_after_init(mod);
3792 mod_tree_remove_init(mod);
3793 module_arch_freeing_init(mod);
3794 trace_android_vh_set_memory_rw((unsigned long)mod->init_layout.base,
3795 (mod->init_layout.size)>>PAGE_SHIFT);
3796 trace_android_vh_set_memory_nx((unsigned long)mod->init_layout.base,
3797 (mod->init_layout.size)>>PAGE_SHIFT);
3798 mod->init_layout.base = NULL;
3799 mod->init_layout.size = 0;
3800 mod->init_layout.ro_size = 0;
3801 mod->init_layout.ro_after_init_size = 0;
3802 mod->init_layout.text_size = 0;
3803 /*
3804 * We want to free module_init, but be aware that kallsyms may be
3805 * walking this with preempt disabled. In all the failure paths, we
3806 * call synchronize_rcu(), but we don't want to slow down the success
3807 * path. module_memfree() cannot be called in an interrupt, so do the
3808 * work and call synchronize_rcu() in a work queue.
3809 *
3810 * Note that module_alloc() on most architectures creates W+X page
3811 * mappings which won't be cleaned up until do_free_init() runs. Any
3812 * code such as mark_rodata_ro() which depends on those mappings to
3813 * be cleaned up needs to sync with the queued work - ie
3814 * rcu_barrier()
3815 */
3816 if (llist_add(&freeinit->node, &init_free_list))
3817 schedule_work(&init_free_wq);
3818
3819 mutex_unlock(&module_mutex);
3820 wake_up_all(&module_wq);
3821
3822 return 0;
3823
3824 fail_free_freeinit:
3825 kfree(freeinit);
3826 fail:
3827 /* Try to protect us from buggy refcounters. */
3828 mod->state = MODULE_STATE_GOING;
3829 synchronize_rcu();
3830 module_put(mod);
3831 blocking_notifier_call_chain(&module_notify_list,
3832 MODULE_STATE_GOING, mod);
3833 klp_module_going(mod);
3834 ftrace_release_mod(mod);
3835 free_module(mod);
3836 wake_up_all(&module_wq);
3837 return ret;
3838 }
3839
may_init_module(void)3840 static int may_init_module(void)
3841 {
3842 if (!capable(CAP_SYS_MODULE) || modules_disabled)
3843 return -EPERM;
3844
3845 return 0;
3846 }
3847
3848 /*
3849 * We try to place it in the list now to make sure it's unique before
3850 * we dedicate too many resources. In particular, temporary percpu
3851 * memory exhaustion.
3852 */
add_unformed_module(struct module * mod)3853 static int add_unformed_module(struct module *mod)
3854 {
3855 int err;
3856 struct module *old;
3857
3858 mod->state = MODULE_STATE_UNFORMED;
3859
3860 again:
3861 mutex_lock(&module_mutex);
3862 old = find_module_all(mod->name, strlen(mod->name), true);
3863 if (old != NULL) {
3864 if (old->state != MODULE_STATE_LIVE) {
3865 /* Wait in case it fails to load. */
3866 mutex_unlock(&module_mutex);
3867 err = wait_event_interruptible(module_wq,
3868 finished_loading(mod->name));
3869 if (err)
3870 goto out_unlocked;
3871 goto again;
3872 }
3873 err = -EEXIST;
3874 goto out;
3875 }
3876 mod_update_bounds(mod);
3877 list_add_rcu(&mod->list, &modules);
3878 mod_tree_insert(mod);
3879 err = 0;
3880
3881 out:
3882 mutex_unlock(&module_mutex);
3883 out_unlocked:
3884 return err;
3885 }
3886
complete_formation(struct module * mod,struct load_info * info)3887 static int complete_formation(struct module *mod, struct load_info *info)
3888 {
3889 int err;
3890
3891 mutex_lock(&module_mutex);
3892
3893 /* Find duplicate symbols (must be called under lock). */
3894 err = verify_exported_symbols(mod);
3895 if (err < 0)
3896 goto out;
3897
3898 /* This relies on module_mutex for list integrity. */
3899 module_bug_finalize(info->hdr, info->sechdrs, mod);
3900
3901 module_enable_ro(mod, false);
3902 module_enable_nx(mod);
3903 module_enable_x(mod);
3904 trace_android_vh_set_module_permit_before_init(mod);
3905
3906 /* Mark state as coming so strong_try_module_get() ignores us,
3907 * but kallsyms etc. can see us. */
3908 mod->state = MODULE_STATE_COMING;
3909 mutex_unlock(&module_mutex);
3910
3911 return 0;
3912
3913 out:
3914 mutex_unlock(&module_mutex);
3915 return err;
3916 }
3917
prepare_coming_module(struct module * mod)3918 static int prepare_coming_module(struct module *mod)
3919 {
3920 int err;
3921
3922 ftrace_module_enable(mod);
3923 err = klp_module_coming(mod);
3924 if (err)
3925 return err;
3926
3927 err = blocking_notifier_call_chain_robust(&module_notify_list,
3928 MODULE_STATE_COMING, MODULE_STATE_GOING, mod);
3929 err = notifier_to_errno(err);
3930 if (err)
3931 klp_module_going(mod);
3932
3933 return err;
3934 }
3935
unknown_module_param_cb(char * param,char * val,const char * modname,void * arg)3936 static int unknown_module_param_cb(char *param, char *val, const char *modname,
3937 void *arg)
3938 {
3939 struct module *mod = arg;
3940 int ret;
3941
3942 if (strcmp(param, "async_probe") == 0) {
3943 mod->async_probe_requested = true;
3944 return 0;
3945 }
3946
3947 /* Check for magic 'dyndbg' arg */
3948 ret = ddebug_dyndbg_module_param_cb(param, val, modname);
3949 if (ret != 0)
3950 pr_warn("%s: unknown parameter '%s' ignored\n", modname, param);
3951 return 0;
3952 }
3953
3954 static void cfi_init(struct module *mod);
3955
3956 /* Allocate and load the module: note that size of section 0 is always
3957 zero, and we rely on this for optional sections. */
load_module(struct load_info * info,const char __user * uargs,int flags)3958 static int load_module(struct load_info *info, const char __user *uargs,
3959 int flags)
3960 {
3961 struct module *mod;
3962 long err = 0;
3963 char *after_dashes;
3964
3965 /*
3966 * Do the signature check (if any) first. All that
3967 * the signature check needs is info->len, it does
3968 * not need any of the section info. That can be
3969 * set up later. This will minimize the chances
3970 * of a corrupt module causing problems before
3971 * we even get to the signature check.
3972 *
3973 * The check will also adjust info->len by stripping
3974 * off the sig length at the end of the module, making
3975 * checks against info->len more correct.
3976 */
3977 err = module_sig_check(info, flags);
3978 if (err)
3979 goto free_copy;
3980
3981 /*
3982 * Do basic sanity checks against the ELF header and
3983 * sections.
3984 */
3985 err = elf_validity_check(info);
3986 if (err) {
3987 pr_err("Module has invalid ELF structures\n");
3988 goto free_copy;
3989 }
3990
3991 /*
3992 * Everything checks out, so set up the section info
3993 * in the info structure.
3994 */
3995 err = setup_load_info(info, flags);
3996 if (err)
3997 goto free_copy;
3998
3999 /*
4000 * Now that we know we have the correct module name, check
4001 * if it's blacklisted.
4002 */
4003 if (blacklisted(info->name)) {
4004 err = -EPERM;
4005 pr_err("Module %s is blacklisted\n", info->name);
4006 goto free_copy;
4007 }
4008
4009 err = rewrite_section_headers(info, flags);
4010 if (err)
4011 goto free_copy;
4012
4013 /* Check module struct version now, before we try to use module. */
4014 if (!check_modstruct_version(info, info->mod)) {
4015 err = -ENOEXEC;
4016 goto free_copy;
4017 }
4018
4019 /* Figure out module layout, and allocate all the memory. */
4020 mod = layout_and_allocate(info, flags);
4021 if (IS_ERR(mod)) {
4022 err = PTR_ERR(mod);
4023 goto free_copy;
4024 }
4025
4026 audit_log_kern_module(mod->name);
4027
4028 /* Reserve our place in the list. */
4029 err = add_unformed_module(mod);
4030 if (err)
4031 goto free_module;
4032
4033 #ifdef CONFIG_MODULE_SIG
4034 mod->sig_ok = info->sig_ok;
4035 if (!mod->sig_ok) {
4036 pr_notice_once("%s: module verification failed: signature "
4037 "and/or required key missing - tainting "
4038 "kernel\n", mod->name);
4039 add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
4040 }
4041 #endif
4042
4043 /* To avoid stressing percpu allocator, do this once we're unique. */
4044 err = percpu_modalloc(mod, info);
4045 if (err)
4046 goto unlink_mod;
4047
4048 /* Now module is in final location, initialize linked lists, etc. */
4049 err = module_unload_init(mod);
4050 if (err)
4051 goto unlink_mod;
4052
4053 init_param_lock(mod);
4054
4055 /* Now we've got everything in the final locations, we can
4056 * find optional sections. */
4057 err = find_module_sections(mod, info);
4058 if (err)
4059 goto free_unload;
4060
4061 err = check_module_license_and_versions(mod);
4062 if (err)
4063 goto free_unload;
4064
4065 /* Set up MODINFO_ATTR fields */
4066 setup_modinfo(mod, info);
4067
4068 /* Fix up syms, so that st_value is a pointer to location. */
4069 err = simplify_symbols(mod, info);
4070 if (err < 0)
4071 goto free_modinfo;
4072
4073 err = apply_relocations(mod, info);
4074 if (err < 0)
4075 goto free_modinfo;
4076
4077 err = post_relocation(mod, info);
4078 if (err < 0)
4079 goto free_modinfo;
4080
4081 flush_module_icache(mod);
4082
4083 /* Setup CFI for the module. */
4084 cfi_init(mod);
4085
4086 /* Now copy in args */
4087 mod->args = strndup_user(uargs, ~0UL >> 1);
4088 if (IS_ERR(mod->args)) {
4089 err = PTR_ERR(mod->args);
4090 goto free_arch_cleanup;
4091 }
4092
4093 dynamic_debug_setup(mod, info->debug, info->num_debug);
4094
4095 /* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
4096 ftrace_module_init(mod);
4097
4098 /* Finally it's fully formed, ready to start executing. */
4099 err = complete_formation(mod, info);
4100 if (err)
4101 goto ddebug_cleanup;
4102
4103 err = prepare_coming_module(mod);
4104 if (err)
4105 goto bug_cleanup;
4106
4107 /* Module is ready to execute: parsing args may do that. */
4108 after_dashes = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
4109 -32768, 32767, mod,
4110 unknown_module_param_cb);
4111 if (IS_ERR(after_dashes)) {
4112 err = PTR_ERR(after_dashes);
4113 goto coming_cleanup;
4114 } else if (after_dashes) {
4115 pr_warn("%s: parameters '%s' after `--' ignored\n",
4116 mod->name, after_dashes);
4117 }
4118
4119 /* Link in to sysfs. */
4120 err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
4121 if (err < 0)
4122 goto coming_cleanup;
4123
4124 if (is_livepatch_module(mod)) {
4125 err = copy_module_elf(mod, info);
4126 if (err < 0)
4127 goto sysfs_cleanup;
4128 }
4129
4130 /* Get rid of temporary copy. */
4131 free_copy(info);
4132
4133 /* Done! */
4134 trace_module_load(mod);
4135
4136 return do_init_module(mod);
4137
4138 sysfs_cleanup:
4139 mod_sysfs_teardown(mod);
4140 coming_cleanup:
4141 mod->state = MODULE_STATE_GOING;
4142 destroy_params(mod->kp, mod->num_kp);
4143 blocking_notifier_call_chain(&module_notify_list,
4144 MODULE_STATE_GOING, mod);
4145 klp_module_going(mod);
4146 bug_cleanup:
4147 mod->state = MODULE_STATE_GOING;
4148 /* module_bug_cleanup needs module_mutex protection */
4149 mutex_lock(&module_mutex);
4150 module_bug_cleanup(mod);
4151 mutex_unlock(&module_mutex);
4152
4153 ddebug_cleanup:
4154 ftrace_release_mod(mod);
4155 dynamic_debug_remove(mod, info->debug);
4156 synchronize_rcu();
4157 kfree(mod->args);
4158 free_arch_cleanup:
4159 cfi_cleanup(mod);
4160 module_arch_cleanup(mod);
4161 free_modinfo:
4162 free_modinfo(mod);
4163 free_unload:
4164 module_unload_free(mod);
4165 unlink_mod:
4166 mutex_lock(&module_mutex);
4167 /* Unlink carefully: kallsyms could be walking list. */
4168 list_del_rcu(&mod->list);
4169 mod_tree_remove(mod);
4170 wake_up_all(&module_wq);
4171 /* Wait for RCU-sched synchronizing before releasing mod->list. */
4172 synchronize_rcu();
4173 mutex_unlock(&module_mutex);
4174 free_module:
4175 /* Free lock-classes; relies on the preceding sync_rcu() */
4176 lockdep_free_key_range(mod->core_layout.base, mod->core_layout.size);
4177
4178 module_deallocate(mod, info);
4179 free_copy:
4180 free_copy(info);
4181 return err;
4182 }
4183
SYSCALL_DEFINE3(init_module,void __user *,umod,unsigned long,len,const char __user *,uargs)4184 SYSCALL_DEFINE3(init_module, void __user *, umod,
4185 unsigned long, len, const char __user *, uargs)
4186 {
4187 int err;
4188 struct load_info info = { };
4189
4190 err = may_init_module();
4191 if (err)
4192 return err;
4193
4194 pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
4195 umod, len, uargs);
4196
4197 err = copy_module_from_user(umod, len, &info);
4198 if (err)
4199 return err;
4200
4201 return load_module(&info, uargs, 0);
4202 }
4203
SYSCALL_DEFINE3(finit_module,int,fd,const char __user *,uargs,int,flags)4204 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
4205 {
4206 struct load_info info = { };
4207 void *hdr = NULL;
4208 int err;
4209
4210 err = may_init_module();
4211 if (err)
4212 return err;
4213
4214 pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
4215
4216 if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
4217 |MODULE_INIT_IGNORE_VERMAGIC))
4218 return -EINVAL;
4219
4220 err = kernel_read_file_from_fd(fd, 0, &hdr, INT_MAX, NULL,
4221 READING_MODULE);
4222 if (err < 0)
4223 return err;
4224 info.hdr = hdr;
4225 info.len = err;
4226
4227 return load_module(&info, uargs, flags);
4228 }
4229
within(unsigned long addr,void * start,unsigned long size)4230 static inline int within(unsigned long addr, void *start, unsigned long size)
4231 {
4232 return ((void *)addr >= start && (void *)addr < start + size);
4233 }
4234
4235 #ifdef CONFIG_KALLSYMS
4236 /*
4237 * This ignores the intensely annoying "mapping symbols" found
4238 * in ARM ELF files: $a, $t and $d.
4239 */
is_arm_mapping_symbol(const char * str)4240 static inline int is_arm_mapping_symbol(const char *str)
4241 {
4242 if (str[0] == '.' && str[1] == 'L')
4243 return true;
4244 return str[0] == '$' && strchr("axtd", str[1])
4245 && (str[2] == '\0' || str[2] == '.');
4246 }
4247
is_cfi_typeid_symbol(const char * str)4248 static inline int is_cfi_typeid_symbol(const char *str)
4249 {
4250 return !strncmp(str, "__typeid__", 10);
4251 }
4252
kallsyms_symbol_name(struct mod_kallsyms * kallsyms,unsigned int symnum)4253 static const char *kallsyms_symbol_name(struct mod_kallsyms *kallsyms, unsigned int symnum)
4254 {
4255 return kallsyms->strtab + kallsyms->symtab[symnum].st_name;
4256 }
4257
4258 /*
4259 * Given a module and address, find the corresponding symbol and return its name
4260 * while providing its size and offset if needed.
4261 */
find_kallsyms_symbol(struct module * mod,unsigned long addr,unsigned long * size,unsigned long * offset)4262 static const char *find_kallsyms_symbol(struct module *mod,
4263 unsigned long addr,
4264 unsigned long *size,
4265 unsigned long *offset)
4266 {
4267 unsigned int i, best = 0;
4268 unsigned long nextval, bestval;
4269 struct mod_kallsyms *kallsyms = rcu_dereference_sched(mod->kallsyms);
4270
4271 /* At worse, next value is at end of module */
4272 if (within_module_init(addr, mod))
4273 nextval = (unsigned long)mod->init_layout.base+mod->init_layout.text_size;
4274 else
4275 nextval = (unsigned long)mod->core_layout.base+mod->core_layout.text_size;
4276
4277 bestval = kallsyms_symbol_value(&kallsyms->symtab[best]);
4278
4279 /* Scan for closest preceding symbol, and next symbol. (ELF
4280 starts real symbols at 1). */
4281 for (i = 1; i < kallsyms->num_symtab; i++) {
4282 const Elf_Sym *sym = &kallsyms->symtab[i];
4283 unsigned long thisval = kallsyms_symbol_value(sym);
4284
4285 if (sym->st_shndx == SHN_UNDEF)
4286 continue;
4287
4288 /* We ignore unnamed symbols: they're uninformative
4289 * and inserted at a whim. */
4290 if (*kallsyms_symbol_name(kallsyms, i) == '\0'
4291 || is_arm_mapping_symbol(kallsyms_symbol_name(kallsyms, i))
4292 || is_cfi_typeid_symbol(kallsyms_symbol_name(kallsyms, i)))
4293 continue;
4294
4295 if (thisval <= addr && thisval > bestval) {
4296 best = i;
4297 bestval = thisval;
4298 }
4299 if (thisval > addr && thisval < nextval)
4300 nextval = thisval;
4301 }
4302
4303 if (!best)
4304 return NULL;
4305
4306 if (size)
4307 *size = nextval - bestval;
4308 if (offset)
4309 *offset = addr - bestval;
4310
4311 return kallsyms_symbol_name(kallsyms, best);
4312 }
4313
dereference_module_function_descriptor(struct module * mod,void * ptr)4314 void * __weak dereference_module_function_descriptor(struct module *mod,
4315 void *ptr)
4316 {
4317 return ptr;
4318 }
4319
4320 /* For kallsyms to ask for address resolution. NULL means not found. Careful
4321 * 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)4322 const char *module_address_lookup(unsigned long addr,
4323 unsigned long *size,
4324 unsigned long *offset,
4325 char **modname,
4326 char *namebuf)
4327 {
4328 const char *ret = NULL;
4329 struct module *mod;
4330
4331 preempt_disable();
4332 mod = __module_address(addr);
4333 if (mod) {
4334 if (modname)
4335 *modname = mod->name;
4336
4337 ret = find_kallsyms_symbol(mod, addr, size, offset);
4338 }
4339 /* Make a copy in here where it's safe */
4340 if (ret) {
4341 strncpy(namebuf, ret, KSYM_NAME_LEN - 1);
4342 ret = namebuf;
4343 }
4344 preempt_enable();
4345
4346 return ret;
4347 }
4348
lookup_module_symbol_name(unsigned long addr,char * symname)4349 int lookup_module_symbol_name(unsigned long addr, char *symname)
4350 {
4351 struct module *mod;
4352
4353 preempt_disable();
4354 list_for_each_entry_rcu(mod, &modules, list) {
4355 if (mod->state == MODULE_STATE_UNFORMED)
4356 continue;
4357 if (within_module(addr, mod)) {
4358 const char *sym;
4359
4360 sym = find_kallsyms_symbol(mod, addr, NULL, NULL);
4361 if (!sym)
4362 goto out;
4363
4364 strlcpy(symname, sym, KSYM_NAME_LEN);
4365 preempt_enable();
4366 return 0;
4367 }
4368 }
4369 out:
4370 preempt_enable();
4371 return -ERANGE;
4372 }
4373
lookup_module_symbol_attrs(unsigned long addr,unsigned long * size,unsigned long * offset,char * modname,char * name)4374 int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size,
4375 unsigned long *offset, char *modname, char *name)
4376 {
4377 struct module *mod;
4378
4379 preempt_disable();
4380 list_for_each_entry_rcu(mod, &modules, list) {
4381 if (mod->state == MODULE_STATE_UNFORMED)
4382 continue;
4383 if (within_module(addr, mod)) {
4384 const char *sym;
4385
4386 sym = find_kallsyms_symbol(mod, addr, size, offset);
4387 if (!sym)
4388 goto out;
4389 if (modname)
4390 strlcpy(modname, mod->name, MODULE_NAME_LEN);
4391 if (name)
4392 strlcpy(name, sym, KSYM_NAME_LEN);
4393 preempt_enable();
4394 return 0;
4395 }
4396 }
4397 out:
4398 preempt_enable();
4399 return -ERANGE;
4400 }
4401
module_get_kallsym(unsigned int symnum,unsigned long * value,char * type,char * name,char * module_name,int * exported)4402 int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
4403 char *name, char *module_name, int *exported)
4404 {
4405 struct module *mod;
4406
4407 preempt_disable();
4408 list_for_each_entry_rcu(mod, &modules, list) {
4409 struct mod_kallsyms *kallsyms;
4410
4411 if (mod->state == MODULE_STATE_UNFORMED)
4412 continue;
4413 kallsyms = rcu_dereference_sched(mod->kallsyms);
4414 if (symnum < kallsyms->num_symtab) {
4415 const Elf_Sym *sym = &kallsyms->symtab[symnum];
4416
4417 *value = kallsyms_symbol_value(sym);
4418 *type = kallsyms->typetab[symnum];
4419 strlcpy(name, kallsyms_symbol_name(kallsyms, symnum), KSYM_NAME_LEN);
4420 strlcpy(module_name, mod->name, MODULE_NAME_LEN);
4421 *exported = is_exported(name, *value, mod);
4422 preempt_enable();
4423 return 0;
4424 }
4425 symnum -= kallsyms->num_symtab;
4426 }
4427 preempt_enable();
4428 return -ERANGE;
4429 }
4430
4431 /* Given a module and name of symbol, find and return the symbol's value */
find_kallsyms_symbol_value(struct module * mod,const char * name)4432 static unsigned long find_kallsyms_symbol_value(struct module *mod, const char *name)
4433 {
4434 unsigned int i;
4435 struct mod_kallsyms *kallsyms = rcu_dereference_sched(mod->kallsyms);
4436
4437 for (i = 0; i < kallsyms->num_symtab; i++) {
4438 const Elf_Sym *sym = &kallsyms->symtab[i];
4439
4440 if (strcmp(name, kallsyms_symbol_name(kallsyms, i)) == 0 &&
4441 sym->st_shndx != SHN_UNDEF)
4442 return kallsyms_symbol_value(sym);
4443 }
4444 return 0;
4445 }
4446
4447 /* Look for this name: can be of form module:name. */
module_kallsyms_lookup_name(const char * name)4448 unsigned long module_kallsyms_lookup_name(const char *name)
4449 {
4450 struct module *mod;
4451 char *colon;
4452 unsigned long ret = 0;
4453
4454 /* Don't lock: we're in enough trouble already. */
4455 preempt_disable();
4456 if ((colon = strnchr(name, MODULE_NAME_LEN, ':')) != NULL) {
4457 if ((mod = find_module_all(name, colon - name, false)) != NULL)
4458 ret = find_kallsyms_symbol_value(mod, colon+1);
4459 } else {
4460 list_for_each_entry_rcu(mod, &modules, list) {
4461 if (mod->state == MODULE_STATE_UNFORMED)
4462 continue;
4463 if ((ret = find_kallsyms_symbol_value(mod, name)) != 0)
4464 break;
4465 }
4466 }
4467 preempt_enable();
4468 return ret;
4469 }
4470
module_kallsyms_on_each_symbol(int (* fn)(void *,const char *,struct module *,unsigned long),void * data)4471 int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
4472 struct module *, unsigned long),
4473 void *data)
4474 {
4475 struct module *mod;
4476 unsigned int i;
4477 int ret;
4478
4479 module_assert_mutex();
4480
4481 list_for_each_entry(mod, &modules, list) {
4482 /* We hold module_mutex: no need for rcu_dereference_sched */
4483 struct mod_kallsyms *kallsyms = mod->kallsyms;
4484
4485 if (mod->state == MODULE_STATE_UNFORMED)
4486 continue;
4487 for (i = 0; i < kallsyms->num_symtab; i++) {
4488 const Elf_Sym *sym = &kallsyms->symtab[i];
4489
4490 if (sym->st_shndx == SHN_UNDEF)
4491 continue;
4492
4493 ret = fn(data, kallsyms_symbol_name(kallsyms, i),
4494 mod, kallsyms_symbol_value(sym));
4495 if (ret != 0)
4496 return ret;
4497 }
4498 }
4499 return 0;
4500 }
4501 #endif /* CONFIG_KALLSYMS */
4502
cfi_init(struct module * mod)4503 static void cfi_init(struct module *mod)
4504 {
4505 #ifdef CONFIG_CFI_CLANG
4506 initcall_t *init;
4507 exitcall_t *exit;
4508
4509 rcu_read_lock_sched();
4510 mod->cfi_check = (cfi_check_fn)
4511 find_kallsyms_symbol_value(mod, "__cfi_check");
4512 init = (initcall_t *)
4513 find_kallsyms_symbol_value(mod, "__cfi_jt_init_module");
4514 exit = (exitcall_t *)
4515 find_kallsyms_symbol_value(mod, "__cfi_jt_cleanup_module");
4516 rcu_read_unlock_sched();
4517
4518 /* Fix init/exit functions to point to the CFI jump table */
4519 if (init) mod->init = *init;
4520 if (exit) mod->exit = *exit;
4521
4522 cfi_module_add(mod, module_addr_min);
4523 #endif
4524 }
4525
cfi_cleanup(struct module * mod)4526 static void cfi_cleanup(struct module *mod)
4527 {
4528 #ifdef CONFIG_CFI_CLANG
4529 cfi_module_remove(mod, module_addr_min);
4530 #endif
4531 }
4532
4533 /* Maximum number of characters written by module_flags() */
4534 #define MODULE_FLAGS_BUF_SIZE (TAINT_FLAGS_COUNT + 4)
4535
4536 /* Keep in sync with MODULE_FLAGS_BUF_SIZE !!! */
module_flags(struct module * mod,char * buf)4537 static char *module_flags(struct module *mod, char *buf)
4538 {
4539 int bx = 0;
4540
4541 BUG_ON(mod->state == MODULE_STATE_UNFORMED);
4542 if (mod->taints ||
4543 mod->state == MODULE_STATE_GOING ||
4544 mod->state == MODULE_STATE_COMING) {
4545 buf[bx++] = '(';
4546 bx += module_flags_taint(mod, buf + bx);
4547 /* Show a - for module-is-being-unloaded */
4548 if (mod->state == MODULE_STATE_GOING)
4549 buf[bx++] = '-';
4550 /* Show a + for module-is-being-loaded */
4551 if (mod->state == MODULE_STATE_COMING)
4552 buf[bx++] = '+';
4553 buf[bx++] = ')';
4554 }
4555 buf[bx] = '\0';
4556
4557 return buf;
4558 }
4559
4560 #ifdef CONFIG_PROC_FS
4561 /* Called by the /proc file system to return a list of modules. */
m_start(struct seq_file * m,loff_t * pos)4562 static void *m_start(struct seq_file *m, loff_t *pos)
4563 {
4564 mutex_lock(&module_mutex);
4565 return seq_list_start(&modules, *pos);
4566 }
4567
m_next(struct seq_file * m,void * p,loff_t * pos)4568 static void *m_next(struct seq_file *m, void *p, loff_t *pos)
4569 {
4570 return seq_list_next(p, &modules, pos);
4571 }
4572
m_stop(struct seq_file * m,void * p)4573 static void m_stop(struct seq_file *m, void *p)
4574 {
4575 mutex_unlock(&module_mutex);
4576 }
4577
m_show(struct seq_file * m,void * p)4578 static int m_show(struct seq_file *m, void *p)
4579 {
4580 struct module *mod = list_entry(p, struct module, list);
4581 char buf[MODULE_FLAGS_BUF_SIZE];
4582 void *value;
4583
4584 /* We always ignore unformed modules. */
4585 if (mod->state == MODULE_STATE_UNFORMED)
4586 return 0;
4587
4588 seq_printf(m, "%s %u",
4589 mod->name, mod->init_layout.size + mod->core_layout.size);
4590 print_unload_info(m, mod);
4591
4592 /* Informative for users. */
4593 seq_printf(m, " %s",
4594 mod->state == MODULE_STATE_GOING ? "Unloading" :
4595 mod->state == MODULE_STATE_COMING ? "Loading" :
4596 "Live");
4597 /* Used by oprofile and other similar tools. */
4598 value = m->private ? NULL : mod->core_layout.base;
4599 seq_printf(m, " 0x%px", value);
4600
4601 /* Taints info */
4602 if (mod->taints)
4603 seq_printf(m, " %s", module_flags(mod, buf));
4604
4605 seq_puts(m, "\n");
4606 return 0;
4607 }
4608
4609 /* Format: modulename size refcount deps address
4610
4611 Where refcount is a number or -, and deps is a comma-separated list
4612 of depends or -.
4613 */
4614 static const struct seq_operations modules_op = {
4615 .start = m_start,
4616 .next = m_next,
4617 .stop = m_stop,
4618 .show = m_show
4619 };
4620
4621 /*
4622 * This also sets the "private" pointer to non-NULL if the
4623 * kernel pointers should be hidden (so you can just test
4624 * "m->private" to see if you should keep the values private).
4625 *
4626 * We use the same logic as for /proc/kallsyms.
4627 */
modules_open(struct inode * inode,struct file * file)4628 static int modules_open(struct inode *inode, struct file *file)
4629 {
4630 int err = seq_open(file, &modules_op);
4631
4632 if (!err) {
4633 struct seq_file *m = file->private_data;
4634 m->private = kallsyms_show_value(file->f_cred) ? NULL : (void *)8ul;
4635 }
4636
4637 return err;
4638 }
4639
4640 static const struct proc_ops modules_proc_ops = {
4641 .proc_flags = PROC_ENTRY_PERMANENT,
4642 .proc_open = modules_open,
4643 .proc_read = seq_read,
4644 .proc_lseek = seq_lseek,
4645 .proc_release = seq_release,
4646 };
4647
proc_modules_init(void)4648 static int __init proc_modules_init(void)
4649 {
4650 proc_create("modules", 0, NULL, &modules_proc_ops);
4651 return 0;
4652 }
4653 module_init(proc_modules_init);
4654 #endif
4655
4656 /* Given an address, look for it in the module exception tables. */
search_module_extables(unsigned long addr)4657 const struct exception_table_entry *search_module_extables(unsigned long addr)
4658 {
4659 const struct exception_table_entry *e = NULL;
4660 struct module *mod;
4661
4662 preempt_disable();
4663 mod = __module_address(addr);
4664 if (!mod)
4665 goto out;
4666
4667 if (!mod->num_exentries)
4668 goto out;
4669
4670 e = search_extable(mod->extable,
4671 mod->num_exentries,
4672 addr);
4673 out:
4674 preempt_enable();
4675
4676 /*
4677 * Now, if we found one, we are running inside it now, hence
4678 * we cannot unload the module, hence no refcnt needed.
4679 */
4680 return e;
4681 }
4682
4683 /*
4684 * is_module_address - is this address inside a module?
4685 * @addr: the address to check.
4686 *
4687 * See is_module_text_address() if you simply want to see if the address
4688 * is code (not data).
4689 */
is_module_address(unsigned long addr)4690 bool is_module_address(unsigned long addr)
4691 {
4692 bool ret;
4693
4694 preempt_disable();
4695 ret = __module_address(addr) != NULL;
4696 preempt_enable();
4697
4698 return ret;
4699 }
4700
4701 /*
4702 * __module_address - get the module which contains an address.
4703 * @addr: the address.
4704 *
4705 * Must be called with preempt disabled or module mutex held so that
4706 * module doesn't get freed during this.
4707 */
__module_address(unsigned long addr)4708 struct module *__module_address(unsigned long addr)
4709 {
4710 struct module *mod;
4711
4712 if (addr < module_addr_min || addr > module_addr_max)
4713 return NULL;
4714
4715 module_assert_mutex_or_preempt();
4716
4717 mod = mod_find(addr);
4718 if (mod) {
4719 BUG_ON(!within_module(addr, mod));
4720 if (mod->state == MODULE_STATE_UNFORMED)
4721 mod = NULL;
4722 }
4723 return mod;
4724 }
4725
4726 /*
4727 * is_module_text_address - is this address inside module code?
4728 * @addr: the address to check.
4729 *
4730 * See is_module_address() if you simply want to see if the address is
4731 * anywhere in a module. See kernel_text_address() for testing if an
4732 * address corresponds to kernel or module code.
4733 */
is_module_text_address(unsigned long addr)4734 bool is_module_text_address(unsigned long addr)
4735 {
4736 bool ret;
4737
4738 preempt_disable();
4739 ret = __module_text_address(addr) != NULL;
4740 preempt_enable();
4741
4742 return ret;
4743 }
4744
4745 /*
4746 * __module_text_address - get the module whose code contains an address.
4747 * @addr: the address.
4748 *
4749 * Must be called with preempt disabled or module mutex held so that
4750 * module doesn't get freed during this.
4751 */
__module_text_address(unsigned long addr)4752 struct module *__module_text_address(unsigned long addr)
4753 {
4754 struct module *mod = __module_address(addr);
4755 if (mod) {
4756 /* Make sure it's within the text section. */
4757 if (!within(addr, mod->init_layout.base, mod->init_layout.text_size)
4758 && !within(addr, mod->core_layout.base, mod->core_layout.text_size))
4759 mod = NULL;
4760 }
4761 return mod;
4762 }
4763
4764 /* Don't grab lock, we're oopsing. */
print_modules(void)4765 void print_modules(void)
4766 {
4767 struct module *mod;
4768 char buf[MODULE_FLAGS_BUF_SIZE];
4769
4770 printk(KERN_DEFAULT "Modules linked in:");
4771 /* Most callers should already have preempt disabled, but make sure */
4772 preempt_disable();
4773 list_for_each_entry_rcu(mod, &modules, list) {
4774 if (mod->state == MODULE_STATE_UNFORMED)
4775 continue;
4776 pr_cont(" %s%s", mod->name, module_flags(mod, buf));
4777 }
4778 preempt_enable();
4779 if (last_unloaded_module[0])
4780 pr_cont(" [last unloaded: %s]", last_unloaded_module);
4781 pr_cont("\n");
4782 }
4783
4784 #ifdef CONFIG_ANDROID_DEBUG_SYMBOLS
android_debug_for_each_module(int (* fn)(const char * mod_name,void * mod_addr,void * data),void * data)4785 void android_debug_for_each_module(int (*fn)(const char *mod_name, void *mod_addr, void *data),
4786 void *data)
4787 {
4788 struct module *module;
4789
4790 preempt_disable();
4791 list_for_each_entry_rcu(module, &modules, list) {
4792 if (fn(module->name, module->core_layout.base, data))
4793 goto out;
4794 }
4795 out:
4796 preempt_enable();
4797 }
4798 EXPORT_SYMBOL_GPL(android_debug_for_each_module);
4799 #endif
4800
4801 #ifdef CONFIG_MODVERSIONS
4802 /* Generate the signature for all relevant module structures here.
4803 * 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)4804 void module_layout(struct module *mod,
4805 struct modversion_info *ver,
4806 struct kernel_param *kp,
4807 struct kernel_symbol *ks,
4808 struct tracepoint * const *tp)
4809 {
4810 }
4811 EXPORT_SYMBOL(module_layout);
4812 #endif
4813