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