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