module: Move module_enable_x() and frob_text() in strict_rwx.c
[linux-2.6-block.git] / kernel / module / main.c
CommitLineData
1a59d1b8 1// SPDX-License-Identifier: GPL-2.0-or-later
f71d20e9 2/*
24b9f0d2
SS
3 * Copyright (C) 2002 Richard Henderson
4 * Copyright (C) 2001 Rusty Russell, 2002, 2010 Rusty Russell IBM.
5 */
51161bfc
LR
6
7#define INCLUDE_VERMAGIC
8
9984de1a 9#include <linux/export.h>
8a293be0 10#include <linux/extable.h>
1da177e4 11#include <linux/moduleloader.h>
c8424e77 12#include <linux/module_signature.h>
af658dca 13#include <linux/trace_events.h>
1da177e4 14#include <linux/init.h>
ae84e324 15#include <linux/kallsyms.h>
9294523e 16#include <linux/buildid.h>
3b5d5c6b 17#include <linux/fs.h>
9f158333 18#include <linux/kernel.h>
b89999d0 19#include <linux/kernel_read_file.h>
1da177e4
LT
20#include <linux/slab.h>
21#include <linux/vmalloc.h>
22#include <linux/elf.h>
23#include <linux/seq_file.h>
24#include <linux/syscalls.h>
25#include <linux/fcntl.h>
26#include <linux/rcupdate.h>
c59ede7b 27#include <linux/capability.h>
1da177e4
LT
28#include <linux/cpu.h>
29#include <linux/moduleparam.h>
30#include <linux/errno.h>
31#include <linux/err.h>
32#include <linux/vermagic.h>
33#include <linux/notifier.h>
f6a57033 34#include <linux/sched.h>
1da177e4 35#include <linux/device.h>
c988d2b2 36#include <linux/string.h>
97d1f15b 37#include <linux/mutex.h>
d72b3751 38#include <linux/rculist.h>
7c0f6ba6 39#include <linux/uaccess.h>
1da177e4 40#include <asm/cacheflush.h>
563ec5cb 41#include <linux/set_memory.h>
eb8cdec4 42#include <asm/mmu_context.h>
b817f6fe 43#include <linux/license.h>
6d762394 44#include <asm/sections.h>
97e1c18e 45#include <linux/tracepoint.h>
90d595fe 46#include <linux/ftrace.h>
7e545d6e 47#include <linux/livepatch.h>
22a9d645 48#include <linux/async.h>
fbf59bc9 49#include <linux/percpu.h>
4f2294b6 50#include <linux/kmemleak.h>
bf5438fc 51#include <linux/jump_label.h>
84e1c6bb 52#include <linux/pfn.h>
403ed278 53#include <linux/bsearch.h>
9d5059c9 54#include <linux/dynamic_debug.h>
ca86cad7 55#include <linux/audit.h>
2f3238ae 56#include <uapi/linux/module.h>
cfc1d277 57#include "internal.h"
1da177e4 58
7ead8b83
LZ
59#define CREATE_TRACE_POINTS
60#include <trace/events/module.h>
61
75676500
RR
62/*
63 * Mutex protects:
64 * 1) List of modules (also safely readable with preempt_disable),
65 * 2) module_use links,
66 * 3) module_addr_min/module_addr_max.
24b9f0d2
SS
67 * (delete and add uses RCU list operations).
68 */
8ab4ed08
AT
69DEFINE_MUTEX(module_mutex);
70LIST_HEAD(modules);
67fc4e0c 71
1a7b7d92 72/* Work queue for freeing init sections in success case */
fdf09ab8
DJ
73static void do_free_init(struct work_struct *w);
74static DECLARE_WORK(init_free_wq, do_free_init);
75static LLIST_HEAD(init_free_list);
1a7b7d92 76
6c9692e2 77#ifdef CONFIG_MODULES_TREE_LOOKUP
58d208de 78struct mod_tree_root mod_tree __cacheline_aligned = {
4f666546 79 .addr_min = -1UL,
106a4ee2 80};
106a4ee2 81
4f666546
PZ
82#define module_addr_min mod_tree.addr_min
83#define module_addr_max mod_tree.addr_max
84
58d208de
AT
85#else /* !CONFIG_MODULES_TREE_LOOKUP */
86static unsigned long module_addr_min = -1UL, module_addr_max;
87#endif /* CONFIG_MODULES_TREE_LOOKUP */
6c9692e2 88
47889798
AT
89struct symsearch {
90 const struct kernel_symbol *start, *stop;
91 const s32 *crcs;
92 enum mod_license license;
93};
94
4f666546
PZ
95/*
96 * Bounds of module text, for speeding up __module_address.
97 * Protected by module_mutex.
98 */
99static void __mod_update_bounds(void *base, unsigned int size)
100{
101 unsigned long min = (unsigned long)base;
102 unsigned long max = min + size;
103
104 if (min < module_addr_min)
105 module_addr_min = min;
106 if (max > module_addr_max)
107 module_addr_max = max;
108}
109
110static void mod_update_bounds(struct module *mod)
111{
7523e4dc
RR
112 __mod_update_bounds(mod->core_layout.base, mod->core_layout.size);
113 if (mod->init_layout.size)
114 __mod_update_bounds(mod->init_layout.base, mod->init_layout.size);
4f666546
PZ
115}
116
0be964be
PZ
117static void module_assert_mutex_or_preempt(void)
118{
119#ifdef CONFIG_LOCKDEP
120 if (unlikely(!debug_locks))
121 return;
122
9502514f 123 WARN_ON_ONCE(!rcu_read_lock_sched_held() &&
0be964be
PZ
124 !lockdep_is_held(&module_mutex));
125#endif
126}
127
19e4529e
SR
128/* Block module loading/unloading? */
129int modules_disabled = 0;
02608bef 130core_param(nomodule, modules_disabled, bint, 0);
19e4529e 131
c9a3ba55
RR
132/* Waiting for a module to finish initializing? */
133static DECLARE_WAIT_QUEUE_HEAD(module_wq);
134
e041c683 135static BLOCKING_NOTIFIER_HEAD(module_notify_list);
1da177e4 136
6da0b565 137int register_module_notifier(struct notifier_block *nb)
1da177e4 138{
e041c683 139 return blocking_notifier_chain_register(&module_notify_list, nb);
1da177e4
LT
140}
141EXPORT_SYMBOL(register_module_notifier);
142
6da0b565 143int unregister_module_notifier(struct notifier_block *nb)
1da177e4 144{
e041c683 145 return blocking_notifier_chain_unregister(&module_notify_list, nb);
1da177e4
LT
146}
147EXPORT_SYMBOL(unregister_module_notifier);
148
71d9f507
MB
149/*
150 * We require a truly strong try_module_get(): 0 means success.
151 * Otherwise an error is returned due to ongoing or failed
152 * initialization etc.
153 */
1da177e4
LT
154static inline int strong_try_module_get(struct module *mod)
155{
0d21b0e3 156 BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED);
1da177e4 157 if (mod && mod->state == MODULE_STATE_COMING)
c9a3ba55
RR
158 return -EBUSY;
159 if (try_module_get(mod))
1da177e4 160 return 0;
c9a3ba55
RR
161 else
162 return -ENOENT;
1da177e4
LT
163}
164
373d4d09
RR
165static inline void add_taint_module(struct module *mod, unsigned flag,
166 enum lockdep_ok lockdep_ok)
fa3ba2e8 167{
373d4d09 168 add_taint(flag, lockdep_ok);
7fd8329b 169 set_bit(flag, &mod->taints);
fa3ba2e8
FM
170}
171
02a3e59a
RD
172/*
173 * A thread that wants to hold a reference to a module only while it
f49169c9 174 * is running can call this to safely exit.
1da177e4 175 */
ca3574bd 176void __noreturn __module_put_and_kthread_exit(struct module *mod, long code)
1da177e4
LT
177{
178 module_put(mod);
ca3574bd 179 kthread_exit(code);
1da177e4 180}
ca3574bd 181EXPORT_SYMBOL(__module_put_and_kthread_exit);
22a8bdeb 182
1da177e4 183/* Find a module section: 0 means not found. */
49668688 184static unsigned int find_sec(const struct load_info *info, const char *name)
1da177e4
LT
185{
186 unsigned int i;
187
49668688
RR
188 for (i = 1; i < info->hdr->e_shnum; i++) {
189 Elf_Shdr *shdr = &info->sechdrs[i];
1da177e4 190 /* Alloc bit cleared means "ignore it." */
49668688
RR
191 if ((shdr->sh_flags & SHF_ALLOC)
192 && strcmp(info->secstrings + shdr->sh_name, name) == 0)
1da177e4 193 return i;
49668688 194 }
1da177e4
LT
195 return 0;
196}
197
5e458cc0 198/* Find a module section, or NULL. */
49668688 199static void *section_addr(const struct load_info *info, const char *name)
5e458cc0
RR
200{
201 /* Section 0 has sh_addr 0. */
49668688 202 return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
5e458cc0
RR
203}
204
205/* Find a module section, or NULL. Fill in number of "objects" in section. */
49668688 206static void *section_objs(const struct load_info *info,
5e458cc0
RR
207 const char *name,
208 size_t object_size,
209 unsigned int *num)
210{
49668688 211 unsigned int sec = find_sec(info, name);
5e458cc0
RR
212
213 /* Section 0 has sh_addr 0 and sh_size 0. */
49668688
RR
214 *num = info->sechdrs[sec].sh_size / object_size;
215 return (void *)info->sechdrs[sec].sh_addr;
5e458cc0
RR
216}
217
36e68442
AN
218/* Find a module section: 0 means not found. Ignores SHF_ALLOC flag. */
219static unsigned int find_any_sec(const struct load_info *info, const char *name)
220{
221 unsigned int i;
222
223 for (i = 1; i < info->hdr->e_shnum; i++) {
224 Elf_Shdr *shdr = &info->sechdrs[i];
225 if (strcmp(info->secstrings + shdr->sh_name, name) == 0)
226 return i;
227 }
228 return 0;
229}
230
231/*
232 * Find a module section, or NULL. Fill in number of "objects" in section.
233 * Ignores SHF_ALLOC flag.
234 */
235static __maybe_unused void *any_section_objs(const struct load_info *info,
236 const char *name,
237 size_t object_size,
238 unsigned int *num)
239{
240 unsigned int sec = find_any_sec(info, name);
241
242 /* Section 0 has sh_addr 0 and sh_size 0. */
243 *num = info->sechdrs[sec].sh_size / object_size;
244 return (void *)info->sechdrs[sec].sh_addr;
245}
246
1da177e4
LT
247#ifndef CONFIG_MODVERSIONS
248#define symversion(base, idx) NULL
249#else
f83ca9fe 250#define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
1da177e4
LT
251#endif
252
2d25bc55
JY
253static bool check_exported_symbol(const struct symsearch *syms,
254 struct module *owner,
255 unsigned int symnum, void *data)
dafd0940
RR
256{
257 struct find_symbol_arg *fsa = data;
258
f1c3d73e
CH
259 if (!fsa->gplok && syms->license == GPL_ONLY)
260 return false;
dafd0940
RR
261 fsa->owner = owner;
262 fsa->crc = symversion(syms->crcs, symnum);
414fd31b 263 fsa->sym = &syms->start[symnum];
ef1dac60 264 fsa->license = syms->license;
dafd0940
RR
265 return true;
266}
267
7290d580
AB
268static const char *kernel_symbol_name(const struct kernel_symbol *sym)
269{
270#ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
271 return offset_to_ptr(&sym->name_offset);
272#else
273 return sym->name;
274#endif
275}
276
8651ec01
MM
277static const char *kernel_symbol_namespace(const struct kernel_symbol *sym)
278{
279#ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
069e1c07
WD
280 if (!sym->namespace_offset)
281 return NULL;
8651ec01
MM
282 return offset_to_ptr(&sym->namespace_offset);
283#else
284 return sym->namespace;
285#endif
286}
287
91fb02f3 288int cmp_name(const void *name, const void *sym)
403ed278 289{
b605be65 290 return strcmp(name, kernel_symbol_name(sym));
403ed278
AIB
291}
292
2d25bc55
JY
293static bool find_exported_symbol_in_section(const struct symsearch *syms,
294 struct module *owner,
295 void *data)
de4d8d53
RR
296{
297 struct find_symbol_arg *fsa = data;
403ed278
AIB
298 struct kernel_symbol *sym;
299
300 sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
301 sizeof(struct kernel_symbol), cmp_name);
302
2d25bc55
JY
303 if (sym != NULL && check_exported_symbol(syms, owner,
304 sym - syms->start, data))
403ed278 305 return true;
de4d8d53 306
de4d8d53
RR
307 return false;
308}
309
24b9f0d2
SS
310/*
311 * Find an exported symbol and return it, along with, (optional) crc and
312 * (optional) module which owns it. Needs preempt disabled or module_mutex.
313 */
47889798 314bool find_symbol(struct find_symbol_arg *fsa)
dafd0940 315{
71e4b309
CH
316 static const struct symsearch arr[] = {
317 { __start___ksymtab, __stop___ksymtab, __start___kcrctab,
36794822 318 NOT_GPL_ONLY },
71e4b309
CH
319 { __start___ksymtab_gpl, __stop___ksymtab_gpl,
320 __start___kcrctab_gpl,
36794822 321 GPL_ONLY },
71e4b309 322 };
71e4b309
CH
323 struct module *mod;
324 unsigned int i;
dafd0940 325
71e4b309 326 module_assert_mutex_or_preempt();
dafd0940 327
71e4b309 328 for (i = 0; i < ARRAY_SIZE(arr); i++)
0b96615c
CH
329 if (find_exported_symbol_in_section(&arr[i], NULL, fsa))
330 return true;
71e4b309
CH
331
332 list_for_each_entry_rcu(mod, &modules, list,
333 lockdep_is_held(&module_mutex)) {
334 struct symsearch arr[] = {
335 { mod->syms, mod->syms + mod->num_syms, mod->crcs,
36794822 336 NOT_GPL_ONLY },
71e4b309
CH
337 { mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
338 mod->gpl_crcs,
36794822 339 GPL_ONLY },
71e4b309
CH
340 };
341
342 if (mod->state == MODULE_STATE_UNFORMED)
343 continue;
344
345 for (i = 0; i < ARRAY_SIZE(arr); i++)
0b96615c
CH
346 if (find_exported_symbol_in_section(&arr[i], mod, fsa))
347 return true;
dafd0940
RR
348 }
349
0b96615c
CH
350 pr_debug("Failed to find symbol %s\n", fsa->name);
351 return false;
1da177e4
LT
352}
353
fe0d34d2
RR
354/*
355 * Search for module by name: must hold module_mutex (or preempt disabled
356 * for read-only access).
357 */
91fb02f3
AT
358struct module *find_module_all(const char *name, size_t len,
359 bool even_unformed)
1da177e4
LT
360{
361 struct module *mod;
362
fe0d34d2 363 module_assert_mutex_or_preempt();
0be964be 364
bf08949c
MH
365 list_for_each_entry_rcu(mod, &modules, list,
366 lockdep_is_held(&module_mutex)) {
0d21b0e3
RR
367 if (!even_unformed && mod->state == MODULE_STATE_UNFORMED)
368 continue;
4f6de4d5 369 if (strlen(mod->name) == len && !memcmp(mod->name, name, len))
1da177e4
LT
370 return mod;
371 }
372 return NULL;
373}
0d21b0e3
RR
374
375struct module *find_module(const char *name)
376{
4f6de4d5 377 return find_module_all(name, strlen(name), false);
0d21b0e3 378}
1da177e4
LT
379
380#ifdef CONFIG_SMP
fbf59bc9 381
259354de 382static inline void __percpu *mod_percpu(struct module *mod)
fbf59bc9 383{
259354de
TH
384 return mod->percpu;
385}
fbf59bc9 386
9eb76d77 387static int percpu_modalloc(struct module *mod, struct load_info *info)
259354de 388{
9eb76d77
RR
389 Elf_Shdr *pcpusec = &info->sechdrs[info->index.pcpu];
390 unsigned long align = pcpusec->sh_addralign;
391
392 if (!pcpusec->sh_size)
393 return 0;
394
fbf59bc9 395 if (align > PAGE_SIZE) {
bddb12b3
AM
396 pr_warn("%s: per-cpu alignment %li > %li\n",
397 mod->name, align, PAGE_SIZE);
fbf59bc9
TH
398 align = PAGE_SIZE;
399 }
400
9eb76d77 401 mod->percpu = __alloc_reserved_percpu(pcpusec->sh_size, align);
259354de 402 if (!mod->percpu) {
bddb12b3
AM
403 pr_warn("%s: Could not allocate %lu bytes percpu data\n",
404 mod->name, (unsigned long)pcpusec->sh_size);
259354de
TH
405 return -ENOMEM;
406 }
9eb76d77 407 mod->percpu_size = pcpusec->sh_size;
259354de 408 return 0;
fbf59bc9
TH
409}
410
259354de 411static void percpu_modfree(struct module *mod)
fbf59bc9 412{
259354de 413 free_percpu(mod->percpu);
fbf59bc9
TH
414}
415
49668688 416static unsigned int find_pcpusec(struct load_info *info)
6b588c18 417{
49668688 418 return find_sec(info, ".data..percpu");
6b588c18
TH
419}
420
259354de
TH
421static void percpu_modcopy(struct module *mod,
422 const void *from, unsigned long size)
6b588c18
TH
423{
424 int cpu;
425
426 for_each_possible_cpu(cpu)
259354de 427 memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
6b588c18
TH
428}
429
383776fa 430bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
10fad5e4
TH
431{
432 struct module *mod;
433 unsigned int cpu;
434
435 preempt_disable();
436
437 list_for_each_entry_rcu(mod, &modules, list) {
0d21b0e3
RR
438 if (mod->state == MODULE_STATE_UNFORMED)
439 continue;
10fad5e4
TH
440 if (!mod->percpu_size)
441 continue;
442 for_each_possible_cpu(cpu) {
443 void *start = per_cpu_ptr(mod->percpu, cpu);
383776fa 444 void *va = (void *)addr;
10fad5e4 445
383776fa 446 if (va >= start && va < start + mod->percpu_size) {
8ce371f9 447 if (can_addr) {
383776fa 448 *can_addr = (unsigned long) (va - start);
8ce371f9
PZ
449 *can_addr += (unsigned long)
450 per_cpu_ptr(mod->percpu,
451 get_boot_cpu_id());
452 }
10fad5e4
TH
453 preempt_enable();
454 return true;
455 }
456 }
457 }
458
459 preempt_enable();
460 return false;
6b588c18
TH
461}
462
383776fa 463/**
24389b61 464 * is_module_percpu_address() - test whether address is from module static percpu
383776fa
TG
465 * @addr: address to test
466 *
467 * Test whether @addr belongs to module static percpu area.
468 *
24389b61 469 * Return: %true if @addr is from module static percpu area
383776fa
TG
470 */
471bool is_module_percpu_address(unsigned long addr)
472{
473 return __is_module_percpu_address(addr, NULL);
474}
475
1da177e4 476#else /* ... !CONFIG_SMP */
6b588c18 477
259354de 478static inline void __percpu *mod_percpu(struct module *mod)
1da177e4
LT
479{
480 return NULL;
481}
9eb76d77 482static int percpu_modalloc(struct module *mod, struct load_info *info)
259354de 483{
9eb76d77
RR
484 /* UP modules shouldn't have this section: ENOMEM isn't quite right */
485 if (info->sechdrs[info->index.pcpu].sh_size != 0)
486 return -ENOMEM;
487 return 0;
259354de
TH
488}
489static inline void percpu_modfree(struct module *mod)
1da177e4 490{
1da177e4 491}
49668688 492static unsigned int find_pcpusec(struct load_info *info)
1da177e4
LT
493{
494 return 0;
495}
259354de
TH
496static inline void percpu_modcopy(struct module *mod,
497 const void *from, unsigned long size)
1da177e4
LT
498{
499 /* pcpusec should be 0, and size of that section should be 0. */
500 BUG_ON(size != 0);
501}
10fad5e4
TH
502bool is_module_percpu_address(unsigned long addr)
503{
504 return false;
505}
6b588c18 506
383776fa
TG
507bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
508{
509 return false;
510}
511
1da177e4
LT
512#endif /* CONFIG_SMP */
513
c988d2b2
MD
514#define MODINFO_ATTR(field) \
515static void setup_modinfo_##field(struct module *mod, const char *s) \
516{ \
517 mod->field = kstrdup(s, GFP_KERNEL); \
518} \
519static ssize_t show_modinfo_##field(struct module_attribute *mattr, \
4befb026 520 struct module_kobject *mk, char *buffer) \
c988d2b2 521{ \
cc56ded3 522 return scnprintf(buffer, PAGE_SIZE, "%s\n", mk->mod->field); \
c988d2b2
MD
523} \
524static int modinfo_##field##_exists(struct module *mod) \
525{ \
526 return mod->field != NULL; \
527} \
528static void free_modinfo_##field(struct module *mod) \
529{ \
22a8bdeb
DW
530 kfree(mod->field); \
531 mod->field = NULL; \
c988d2b2
MD
532} \
533static struct module_attribute modinfo_##field = { \
7b595756 534 .attr = { .name = __stringify(field), .mode = 0444 }, \
c988d2b2
MD
535 .show = show_modinfo_##field, \
536 .setup = setup_modinfo_##field, \
537 .test = modinfo_##field##_exists, \
538 .free = free_modinfo_##field, \
539};
540
541MODINFO_ATTR(version);
542MODINFO_ATTR(srcversion);
543
e14af7ee
AV
544static char last_unloaded_module[MODULE_NAME_LEN+1];
545
03e88ae1 546#ifdef CONFIG_MODULE_UNLOAD
eb0c5377
SR
547
548EXPORT_TRACEPOINT_SYMBOL(module_get);
549
e513cc1c
MH
550/* MODULE_REF_BASE is the base reference count by kmodule loader. */
551#define MODULE_REF_BASE 1
552
1da177e4 553/* Init the unload section of the module. */
9f85a4bb 554static int module_unload_init(struct module *mod)
1da177e4 555{
e513cc1c
MH
556 /*
557 * Initialize reference counter to MODULE_REF_BASE.
558 * refcnt == 0 means module is going.
559 */
560 atomic_set(&mod->refcnt, MODULE_REF_BASE);
9f85a4bb 561
2c02dfe7
LT
562 INIT_LIST_HEAD(&mod->source_list);
563 INIT_LIST_HEAD(&mod->target_list);
e1783a24 564
1da177e4 565 /* Hold reference count during initialization. */
e513cc1c 566 atomic_inc(&mod->refcnt);
9f85a4bb
RR
567
568 return 0;
1da177e4
LT
569}
570
1da177e4
LT
571/* Does a already use b? */
572static int already_uses(struct module *a, struct module *b)
573{
574 struct module_use *use;
575
2c02dfe7
LT
576 list_for_each_entry(use, &b->source_list, source_list) {
577 if (use->source == a) {
5e124169 578 pr_debug("%s uses %s!\n", a->name, b->name);
1da177e4
LT
579 return 1;
580 }
581 }
5e124169 582 pr_debug("%s does not use %s!\n", a->name, b->name);
1da177e4
LT
583 return 0;
584}
585
2c02dfe7
LT
586/*
587 * Module a uses b
588 * - we add 'a' as a "source", 'b' as a "target" of module use
589 * - the module_use is added to the list of 'b' sources (so
590 * 'b' can walk the list to see who sourced them), and of 'a'
591 * targets (so 'a' can see what modules it targets).
592 */
593static int add_module_usage(struct module *a, struct module *b)
594{
2c02dfe7
LT
595 struct module_use *use;
596
5e124169 597 pr_debug("Allocating new usage for %s.\n", a->name);
2c02dfe7 598 use = kmalloc(sizeof(*use), GFP_ATOMIC);
9ad04574 599 if (!use)
2c02dfe7 600 return -ENOMEM;
2c02dfe7
LT
601
602 use->source = a;
603 use->target = b;
604 list_add(&use->source_list, &b->source_list);
605 list_add(&use->target_list, &a->target_list);
2c02dfe7
LT
606 return 0;
607}
608
75676500 609/* Module a uses b: caller needs module_mutex() */
7ef5264d 610static int ref_module(struct module *a, struct module *b)
1da177e4 611{
c8e21ced 612 int err;
270a6c4c 613
9bea7f23 614 if (b == NULL || already_uses(a, b))
218ce735 615 return 0;
218ce735 616
9bea7f23
RR
617 /* If module isn't available, we fail. */
618 err = strong_try_module_get(b);
c9a3ba55 619 if (err)
9bea7f23 620 return err;
1da177e4 621
2c02dfe7
LT
622 err = add_module_usage(a, b);
623 if (err) {
1da177e4 624 module_put(b);
9bea7f23 625 return err;
1da177e4 626 }
9bea7f23 627 return 0;
1da177e4
LT
628}
629
630/* Clear the unload stuff of the module. */
631static void module_unload_free(struct module *mod)
632{
2c02dfe7 633 struct module_use *use, *tmp;
1da177e4 634
75676500 635 mutex_lock(&module_mutex);
2c02dfe7
LT
636 list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
637 struct module *i = use->target;
5e124169 638 pr_debug("%s unusing %s\n", mod->name, i->name);
2c02dfe7
LT
639 module_put(i);
640 list_del(&use->source_list);
641 list_del(&use->target_list);
642 kfree(use);
1da177e4 643 }
75676500 644 mutex_unlock(&module_mutex);
1da177e4
LT
645}
646
647#ifdef CONFIG_MODULE_FORCE_UNLOAD
fb169793 648static inline int try_force_unload(unsigned int flags)
1da177e4
LT
649{
650 int ret = (flags & O_TRUNC);
651 if (ret)
373d4d09 652 add_taint(TAINT_FORCED_RMMOD, LOCKDEP_NOW_UNRELIABLE);
1da177e4
LT
653 return ret;
654}
655#else
fb169793 656static inline int try_force_unload(unsigned int flags)
1da177e4
LT
657{
658 return 0;
659}
660#endif /* CONFIG_MODULE_FORCE_UNLOAD */
661
e513cc1c
MH
662/* Try to release refcount of module, 0 means success. */
663static int try_release_module_ref(struct module *mod)
1da177e4 664{
e513cc1c 665 int ret;
1da177e4 666
e513cc1c
MH
667 /* Try to decrement refcnt which we set at loading */
668 ret = atomic_sub_return(MODULE_REF_BASE, &mod->refcnt);
669 BUG_ON(ret < 0);
670 if (ret)
671 /* Someone can put this right now, recover with checking */
672 ret = atomic_add_unless(&mod->refcnt, MODULE_REF_BASE, 0);
1da177e4 673
e513cc1c
MH
674 return ret;
675}
1da177e4 676
e513cc1c
MH
677static int try_stop_module(struct module *mod, int flags, int *forced)
678{
da39ba5e 679 /* If it's not unused, quit unless we're forcing. */
e513cc1c
MH
680 if (try_release_module_ref(mod) != 0) {
681 *forced = try_force_unload(flags);
682 if (!(*forced))
1da177e4
LT
683 return -EWOULDBLOCK;
684 }
685
686 /* Mark it as dying. */
e513cc1c 687 mod->state = MODULE_STATE_GOING;
1da177e4 688
e513cc1c 689 return 0;
1da177e4
LT
690}
691
d5db139a 692/**
24389b61 693 * module_refcount() - return the refcount or -1 if unloading
d5db139a
RR
694 * @mod: the module we're checking
695 *
24389b61 696 * Return:
d5db139a
RR
697 * -1 if the module is in the process of unloading
698 * otherwise the number of references in the kernel to the module
699 */
700int module_refcount(struct module *mod)
1da177e4 701{
d5db139a 702 return atomic_read(&mod->refcnt) - MODULE_REF_BASE;
1da177e4
LT
703}
704EXPORT_SYMBOL(module_refcount);
705
706/* This exists whether we can unload or not */
707static void free_module(struct module *mod);
708
17da2bd9
HC
709SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
710 unsigned int, flags)
1da177e4
LT
711{
712 struct module *mod;
dfff0a06 713 char name[MODULE_NAME_LEN];
1da177e4
LT
714 int ret, forced = 0;
715
3d43321b 716 if (!capable(CAP_SYS_MODULE) || modules_disabled)
dfff0a06
GKH
717 return -EPERM;
718
719 if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
720 return -EFAULT;
721 name[MODULE_NAME_LEN-1] = '\0';
722
f6276ac9
RGB
723 audit_log_kern_module(name);
724
3fc1f1e2
TH
725 if (mutex_lock_interruptible(&module_mutex) != 0)
726 return -EINTR;
1da177e4
LT
727
728 mod = find_module(name);
729 if (!mod) {
730 ret = -ENOENT;
731 goto out;
732 }
733
2c02dfe7 734 if (!list_empty(&mod->source_list)) {
1da177e4
LT
735 /* Other modules depend on us: get rid of them first. */
736 ret = -EWOULDBLOCK;
737 goto out;
738 }
739
740 /* Doing init or already dying? */
741 if (mod->state != MODULE_STATE_LIVE) {
3f2b9c9c 742 /* FIXME: if (force), slam module count damn the torpedoes */
5e124169 743 pr_debug("%s already dying\n", mod->name);
1da177e4
LT
744 ret = -EBUSY;
745 goto out;
746 }
747
748 /* If it has an init func, it must have an exit func to unload */
af49d924 749 if (mod->init && !mod->exit) {
fb169793 750 forced = try_force_unload(flags);
1da177e4
LT
751 if (!forced) {
752 /* This module can't be removed */
753 ret = -EBUSY;
754 goto out;
755 }
756 }
757
1da177e4
LT
758 ret = try_stop_module(mod, flags, &forced);
759 if (ret != 0)
760 goto out;
761
df4b565e 762 mutex_unlock(&module_mutex);
25985edc 763 /* Final destruction now no one is using it. */
df4b565e 764 if (mod->exit != NULL)
1da177e4 765 mod->exit();
df4b565e
PO
766 blocking_notifier_call_chain(&module_notify_list,
767 MODULE_STATE_GOING, mod);
7e545d6e 768 klp_module_going(mod);
7dcd182b
JY
769 ftrace_release_mod(mod);
770
22a9d645 771 async_synchronize_full();
75676500 772
e14af7ee 773 /* Store the name of the last unloaded module for diagnostic purposes */
efa5345e 774 strlcpy(last_unloaded_module, mod->name, sizeof(last_unloaded_module));
1da177e4 775
75676500 776 free_module(mod);
5d603311
KK
777 /* someone could wait for the module in add_unformed_module() */
778 wake_up_all(&module_wq);
75676500
RR
779 return 0;
780out:
6389a385 781 mutex_unlock(&module_mutex);
1da177e4
LT
782 return ret;
783}
784
1da177e4
LT
785void __symbol_put(const char *symbol)
786{
0b96615c
CH
787 struct find_symbol_arg fsa = {
788 .name = symbol,
789 .gplok = true,
790 };
1da177e4 791
24da1cbf 792 preempt_disable();
02b2fb45 793 BUG_ON(!find_symbol(&fsa));
0b96615c 794 module_put(fsa.owner);
24da1cbf 795 preempt_enable();
1da177e4
LT
796}
797EXPORT_SYMBOL(__symbol_put);
798
7d1d16e4 799/* Note this assumes addr is a function, which it currently always is. */
1da177e4
LT
800void symbol_put_addr(void *addr)
801{
5e376613 802 struct module *modaddr;
7d1d16e4 803 unsigned long a = (unsigned long)dereference_function_descriptor(addr);
1da177e4 804
7d1d16e4 805 if (core_kernel_text(a))
5e376613 806 return;
1da177e4 807
275d7d44
PZ
808 /*
809 * Even though we hold a reference on the module; we still need to
810 * disable preemption in order to safely traverse the data structure.
811 */
812 preempt_disable();
7d1d16e4 813 modaddr = __module_text_address(a);
a6e6abd5 814 BUG_ON(!modaddr);
5e376613 815 module_put(modaddr);
275d7d44 816 preempt_enable();
1da177e4
LT
817}
818EXPORT_SYMBOL_GPL(symbol_put_addr);
819
820static ssize_t show_refcnt(struct module_attribute *mattr,
4befb026 821 struct module_kobject *mk, char *buffer)
1da177e4 822{
d5db139a 823 return sprintf(buffer, "%i\n", module_refcount(mk->mod));
1da177e4
LT
824}
825
cca3e707
KS
826static struct module_attribute modinfo_refcnt =
827 __ATTR(refcnt, 0444, show_refcnt, NULL);
1da177e4 828
d53799be
SR
829void __module_get(struct module *module)
830{
831 if (module) {
832 preempt_disable();
2f35c41f 833 atomic_inc(&module->refcnt);
d53799be
SR
834 trace_module_get(module, _RET_IP_);
835 preempt_enable();
836 }
837}
838EXPORT_SYMBOL(__module_get);
839
840bool try_module_get(struct module *module)
841{
842 bool ret = true;
843
844 if (module) {
845 preempt_disable();
e513cc1c
MH
846 /* Note: here, we can fail to get a reference */
847 if (likely(module_is_live(module) &&
848 atomic_inc_not_zero(&module->refcnt) != 0))
d53799be 849 trace_module_get(module, _RET_IP_);
e513cc1c 850 else
d53799be
SR
851 ret = false;
852
853 preempt_enable();
854 }
855 return ret;
856}
857EXPORT_SYMBOL(try_module_get);
858
f6a57033
AV
859void module_put(struct module *module)
860{
e513cc1c
MH
861 int ret;
862
f6a57033 863 if (module) {
e1783a24 864 preempt_disable();
e513cc1c
MH
865 ret = atomic_dec_if_positive(&module->refcnt);
866 WARN_ON(ret < 0); /* Failed to put refcount */
ae832d1e 867 trace_module_put(module, _RET_IP_);
e1783a24 868 preempt_enable();
f6a57033
AV
869 }
870}
871EXPORT_SYMBOL(module_put);
872
1da177e4 873#else /* !CONFIG_MODULE_UNLOAD */
1da177e4
LT
874static inline void module_unload_free(struct module *mod)
875{
876}
877
7ef5264d 878static int ref_module(struct module *a, struct module *b)
1da177e4 879{
9bea7f23 880 return strong_try_module_get(b);
1da177e4
LT
881}
882
9f85a4bb 883static inline int module_unload_init(struct module *mod)
1da177e4 884{
9f85a4bb 885 return 0;
1da177e4
LT
886}
887#endif /* CONFIG_MODULE_UNLOAD */
888
53999bf3
KW
889static size_t module_flags_taint(struct module *mod, char *buf)
890{
891 size_t l = 0;
7fd8329b
PM
892 int i;
893
894 for (i = 0; i < TAINT_FLAGS_COUNT; i++) {
895 if (taint_flags[i].module && test_bit(i, &mod->taints))
5eb7c0d0 896 buf[l++] = taint_flags[i].c_true;
7fd8329b 897 }
53999bf3 898
53999bf3
KW
899 return l;
900}
901
1f71740a 902static ssize_t show_initstate(struct module_attribute *mattr,
4befb026 903 struct module_kobject *mk, char *buffer)
1f71740a
KS
904{
905 const char *state = "unknown";
906
4befb026 907 switch (mk->mod->state) {
1f71740a
KS
908 case MODULE_STATE_LIVE:
909 state = "live";
910 break;
911 case MODULE_STATE_COMING:
912 state = "coming";
913 break;
914 case MODULE_STATE_GOING:
915 state = "going";
916 break;
0d21b0e3
RR
917 default:
918 BUG();
1f71740a
KS
919 }
920 return sprintf(buffer, "%s\n", state);
921}
922
cca3e707
KS
923static struct module_attribute modinfo_initstate =
924 __ATTR(initstate, 0444, show_initstate, NULL);
1f71740a 925
88bfa324
KS
926static ssize_t store_uevent(struct module_attribute *mattr,
927 struct module_kobject *mk,
928 const char *buffer, size_t count)
929{
df44b479
PR
930 int rc;
931
932 rc = kobject_synth_uevent(&mk->kobj, buffer, count);
933 return rc ? rc : count;
88bfa324
KS
934}
935
cca3e707
KS
936struct module_attribute module_uevent =
937 __ATTR(uevent, 0200, NULL, store_uevent);
938
939static ssize_t show_coresize(struct module_attribute *mattr,
940 struct module_kobject *mk, char *buffer)
941{
7523e4dc 942 return sprintf(buffer, "%u\n", mk->mod->core_layout.size);
cca3e707
KS
943}
944
945static struct module_attribute modinfo_coresize =
946 __ATTR(coresize, 0444, show_coresize, NULL);
947
948static ssize_t show_initsize(struct module_attribute *mattr,
949 struct module_kobject *mk, char *buffer)
950{
7523e4dc 951 return sprintf(buffer, "%u\n", mk->mod->init_layout.size);
cca3e707
KS
952}
953
954static struct module_attribute modinfo_initsize =
955 __ATTR(initsize, 0444, show_initsize, NULL);
956
957static ssize_t show_taint(struct module_attribute *mattr,
958 struct module_kobject *mk, char *buffer)
959{
960 size_t l;
961
962 l = module_flags_taint(mk->mod, buffer);
963 buffer[l++] = '\n';
964 return l;
965}
966
967static struct module_attribute modinfo_taint =
968 __ATTR(taint, 0444, show_taint, NULL);
88bfa324 969
44c09535 970struct module_attribute *modinfo_attrs[] = {
cca3e707 971 &module_uevent,
03e88ae1
GKH
972 &modinfo_version,
973 &modinfo_srcversion,
cca3e707
KS
974 &modinfo_initstate,
975 &modinfo_coresize,
976 &modinfo_initsize,
977 &modinfo_taint,
03e88ae1 978#ifdef CONFIG_MODULE_UNLOAD
cca3e707 979 &modinfo_refcnt,
03e88ae1
GKH
980#endif
981 NULL,
982};
983
44c09535
AT
984size_t modinfo_attrs_count = ARRAY_SIZE(modinfo_attrs);
985
1da177e4
LT
986static const char vermagic[] = VERMAGIC_STRING;
987
47889798 988int try_to_force_load(struct module *mod, const char *reason)
826e4506
LT
989{
990#ifdef CONFIG_MODULE_FORCE_LOAD
25ddbb18 991 if (!test_taint(TAINT_FORCED_MODULE))
bddb12b3 992 pr_warn("%s: %s: kernel tainted.\n", mod->name, reason);
373d4d09 993 add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE);
826e4506
LT
994 return 0;
995#else
996 return -ENOEXEC;
997#endif
998}
999
8651ec01
MM
1000static char *get_modinfo(const struct load_info *info, const char *tag);
1001static char *get_next_modinfo(const struct load_info *info, const char *tag,
1002 char *prev);
1003
1004static int verify_namespace_is_imported(const struct load_info *info,
1005 const struct kernel_symbol *sym,
1006 struct module *mod)
1007{
1008 const char *namespace;
1009 char *imported_namespace;
1010
1011 namespace = kernel_symbol_namespace(sym);
c3a6cf19 1012 if (namespace && namespace[0]) {
8651ec01
MM
1013 imported_namespace = get_modinfo(info, "import_ns");
1014 while (imported_namespace) {
1015 if (strcmp(namespace, imported_namespace) == 0)
1016 return 0;
1017 imported_namespace = get_next_modinfo(
1018 info, "import_ns", imported_namespace);
1019 }
3d52ec5e
MM
1020#ifdef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1021 pr_warn(
1022#else
1023 pr_err(
1024#endif
1025 "%s: module uses symbol (%s) from namespace %s, but does not import it.\n",
1026 mod->name, kernel_symbol_name(sym), namespace);
1027#ifndef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
8651ec01 1028 return -EINVAL;
3d52ec5e 1029#endif
8651ec01
MM
1030 }
1031 return 0;
1032}
1033
262e6ae7
CH
1034static bool inherit_taint(struct module *mod, struct module *owner)
1035{
1036 if (!owner || !test_bit(TAINT_PROPRIETARY_MODULE, &owner->taints))
1037 return true;
1038
1039 if (mod->using_gplonly_symbols) {
1040 pr_err("%s: module using GPL-only symbols uses symbols from proprietary module %s.\n",
1041 mod->name, owner->name);
1042 return false;
1043 }
1044
1045 if (!test_bit(TAINT_PROPRIETARY_MODULE, &mod->taints)) {
1046 pr_warn("%s: module uses symbols from proprietary module %s, inheriting taint.\n",
1047 mod->name, owner->name);
1048 set_bit(TAINT_PROPRIETARY_MODULE, &mod->taints);
1049 }
1050 return true;
1051}
8651ec01 1052
75676500 1053/* Resolve a symbol for this module. I.e. if we find one, record usage. */
49668688
RR
1054static const struct kernel_symbol *resolve_symbol(struct module *mod,
1055 const struct load_info *info,
414fd31b 1056 const char *name,
9bea7f23 1057 char ownername[])
1da177e4 1058{
0b96615c
CH
1059 struct find_symbol_arg fsa = {
1060 .name = name,
1061 .gplok = !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)),
1062 .warn = true,
1063 };
9bea7f23 1064 int err;
1da177e4 1065
d64810f5
PZ
1066 /*
1067 * The module_mutex should not be a heavily contended lock;
1068 * if we get the occasional sleep here, we'll go an extra iteration
1069 * in the wait_event_interruptible(), which is harmless.
1070 */
1071 sched_annotate_sleep();
75676500 1072 mutex_lock(&module_mutex);
0b96615c 1073 if (!find_symbol(&fsa))
9bea7f23
RR
1074 goto unlock;
1075
0b96615c 1076 if (fsa.license == GPL_ONLY)
262e6ae7
CH
1077 mod->using_gplonly_symbols = true;
1078
0b96615c
CH
1079 if (!inherit_taint(mod, fsa.owner)) {
1080 fsa.sym = NULL;
262e6ae7
CH
1081 goto getname;
1082 }
1083
0b96615c
CH
1084 if (!check_version(info, name, mod, fsa.crc)) {
1085 fsa.sym = ERR_PTR(-EINVAL);
9bea7f23 1086 goto getname;
1da177e4 1087 }
9bea7f23 1088
0b96615c 1089 err = verify_namespace_is_imported(info, fsa.sym, mod);
8651ec01 1090 if (err) {
0b96615c 1091 fsa.sym = ERR_PTR(err);
8651ec01
MM
1092 goto getname;
1093 }
1094
0b96615c 1095 err = ref_module(mod, fsa.owner);
9bea7f23 1096 if (err) {
0b96615c 1097 fsa.sym = ERR_PTR(err);
9bea7f23
RR
1098 goto getname;
1099 }
1100
1101getname:
1102 /* We must make copy under the lock if we failed to get ref. */
0b96615c 1103 strncpy(ownername, module_name(fsa.owner), MODULE_NAME_LEN);
9bea7f23 1104unlock:
75676500 1105 mutex_unlock(&module_mutex);
0b96615c 1106 return fsa.sym;
1da177e4
LT
1107}
1108
49668688
RR
1109static const struct kernel_symbol *
1110resolve_symbol_wait(struct module *mod,
1111 const struct load_info *info,
1112 const char *name)
9bea7f23
RR
1113{
1114 const struct kernel_symbol *ksym;
49668688 1115 char owner[MODULE_NAME_LEN];
9bea7f23
RR
1116
1117 if (wait_event_interruptible_timeout(module_wq,
49668688
RR
1118 !IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1119 || PTR_ERR(ksym) != -EBUSY,
9bea7f23 1120 30 * HZ) <= 0) {
bddb12b3
AM
1121 pr_warn("%s: gave up waiting for init of module %s.\n",
1122 mod->name, owner);
9bea7f23
RR
1123 }
1124 return ksym;
1125}
1126
be1f221c 1127void __weak module_memfree(void *module_region)
74e08fcf 1128{
1a7b7d92
RE
1129 /*
1130 * This memory may be RO, and freeing RO memory in an interrupt is not
1131 * supported by vmalloc.
1132 */
1133 WARN_ON(in_interrupt());
74e08fcf
JB
1134 vfree(module_region);
1135}
1136
1137void __weak module_arch_cleanup(struct module *mod)
1138{
1139}
1140
d453cded
RR
1141void __weak module_arch_freeing_init(struct module *mod)
1142{
1143}
1144
cf68fffb
ST
1145static void cfi_cleanup(struct module *mod);
1146
75676500 1147/* Free a module, remove from lists, etc. */
1da177e4
LT
1148static void free_module(struct module *mod)
1149{
7ead8b83
LZ
1150 trace_module_free(mod);
1151
36b0360d 1152 mod_sysfs_teardown(mod);
1da177e4 1153
24b9f0d2
SS
1154 /*
1155 * We leave it in list to prevent duplicate loads, but make sure
1156 * that noone uses it while it's being deconstructed.
1157 */
d3051b48 1158 mutex_lock(&module_mutex);
944a1fa0 1159 mod->state = MODULE_STATE_UNFORMED;
d3051b48 1160 mutex_unlock(&module_mutex);
944a1fa0 1161
b82bab4b
JB
1162 /* Remove dynamic debug info */
1163 ddebug_remove_module(mod->name);
1164
1da177e4
LT
1165 /* Arch-specific cleanup. */
1166 module_arch_cleanup(mod);
1167
1168 /* Module unload stuff */
1169 module_unload_free(mod);
1170
e180a6b7
RR
1171 /* Free any allocated parameters. */
1172 destroy_params(mod->kp, mod->num_kp);
1173
1ce15ef4
JY
1174 if (is_livepatch_module(mod))
1175 free_module_elf(mod);
1176
944a1fa0
RR
1177 /* Now we can delete it from the lists */
1178 mutex_lock(&module_mutex);
461e34ae
MH
1179 /* Unlink carefully: kallsyms could be walking list. */
1180 list_del_rcu(&mod->list);
93c2e105 1181 mod_tree_remove(mod);
0286b5ea 1182 /* Remove this module from bug list, this uses list_del_rcu */
461e34ae 1183 module_bug_cleanup(mod);
0be964be 1184 /* Wait for RCU-sched synchronizing before releasing mod->list and buglist. */
cb2f5536 1185 synchronize_rcu();
944a1fa0
RR
1186 mutex_unlock(&module_mutex);
1187
cf68fffb
ST
1188 /* Clean up CFI for the module. */
1189 cfi_cleanup(mod);
1190
85c898db 1191 /* This may be empty, but that's OK */
d453cded 1192 module_arch_freeing_init(mod);
7523e4dc 1193 module_memfree(mod->init_layout.base);
1da177e4 1194 kfree(mod->args);
259354de 1195 percpu_modfree(mod);
9f85a4bb 1196
35a9393c 1197 /* Free lock-classes; relies on the preceding sync_rcu(). */
7523e4dc 1198 lockdep_free_key_range(mod->core_layout.base, mod->core_layout.size);
fbb9ce95 1199
1da177e4 1200 /* Finally, free the core (containing the module structure) */
7523e4dc 1201 module_memfree(mod->core_layout.base);
1da177e4
LT
1202}
1203
1204void *__symbol_get(const char *symbol)
1205{
0b96615c
CH
1206 struct find_symbol_arg fsa = {
1207 .name = symbol,
1208 .gplok = true,
1209 .warn = true,
1210 };
1da177e4 1211
24da1cbf 1212 preempt_disable();
0b96615c
CH
1213 if (!find_symbol(&fsa) || strong_try_module_get(fsa.owner)) {
1214 preempt_enable();
1215 return NULL;
1216 }
24da1cbf 1217 preempt_enable();
0b96615c 1218 return (void *)kernel_symbol_value(fsa.sym);
1da177e4
LT
1219}
1220EXPORT_SYMBOL_GPL(__symbol_get);
1221
eea8b54d
AN
1222/*
1223 * Ensure that an exported symbol [global namespace] does not already exist
02a3e59a 1224 * in the kernel or in some other module's exported symbol table.
be593f4c
RR
1225 *
1226 * You must hold the module_mutex.
eea8b54d 1227 */
2d25bc55 1228static int verify_exported_symbols(struct module *mod)
eea8b54d 1229{
b211104d 1230 unsigned int i;
b211104d
RR
1231 const struct kernel_symbol *s;
1232 struct {
1233 const struct kernel_symbol *sym;
1234 unsigned int num;
1235 } arr[] = {
1236 { mod->syms, mod->num_syms },
1237 { mod->gpl_syms, mod->num_gpl_syms },
b211104d 1238 };
eea8b54d 1239
b211104d
RR
1240 for (i = 0; i < ARRAY_SIZE(arr); i++) {
1241 for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
0b96615c
CH
1242 struct find_symbol_arg fsa = {
1243 .name = kernel_symbol_name(s),
1244 .gplok = true,
1245 };
1246 if (find_symbol(&fsa)) {
bddb12b3 1247 pr_err("%s: exports duplicate symbol %s"
b211104d 1248 " (owned by %s)\n",
7290d580 1249 mod->name, kernel_symbol_name(s),
0b96615c 1250 module_name(fsa.owner));
b211104d
RR
1251 return -ENOEXEC;
1252 }
eea8b54d 1253 }
b211104d
RR
1254 }
1255 return 0;
eea8b54d
AN
1256}
1257
ebfac7b7
FS
1258static bool ignore_undef_symbol(Elf_Half emachine, const char *name)
1259{
1260 /*
1261 * On x86, PIC code and Clang non-PIC code may have call foo@PLT. GNU as
1262 * before 2.37 produces an unreferenced _GLOBAL_OFFSET_TABLE_ on x86-64.
1263 * i386 has a similar problem but may not deserve a fix.
1264 *
1265 * If we ever have to ignore many symbols, consider refactoring the code to
1266 * only warn if referenced by a relocation.
1267 */
1268 if (emachine == EM_386 || emachine == EM_X86_64)
1269 return !strcmp(name, "_GLOBAL_OFFSET_TABLE_");
1270 return false;
1271}
1272
9a4b9708 1273/* Change all symbols so that st_value encodes the pointer directly. */
49668688
RR
1274static int simplify_symbols(struct module *mod, const struct load_info *info)
1275{
1276 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
1277 Elf_Sym *sym = (void *)symsec->sh_addr;
1da177e4 1278 unsigned long secbase;
49668688 1279 unsigned int i;
1da177e4 1280 int ret = 0;
414fd31b 1281 const struct kernel_symbol *ksym;
1da177e4 1282
49668688
RR
1283 for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
1284 const char *name = info->strtab + sym[i].st_name;
1285
1da177e4
LT
1286 switch (sym[i].st_shndx) {
1287 case SHN_COMMON:
80375980
JM
1288 /* Ignore common symbols */
1289 if (!strncmp(name, "__gnu_lto", 9))
1290 break;
1291
24b9f0d2
SS
1292 /*
1293 * We compiled with -fno-common. These are not
1294 * supposed to happen.
1295 */
5e124169 1296 pr_debug("Common symbol: %s\n", name);
6da0b565 1297 pr_warn("%s: please compile with -fno-common\n",
1da177e4
LT
1298 mod->name);
1299 ret = -ENOEXEC;
1300 break;
1301
1302 case SHN_ABS:
1303 /* Don't need to do anything */
5e124169 1304 pr_debug("Absolute symbol: 0x%08lx\n",
1da177e4
LT
1305 (long)sym[i].st_value);
1306 break;
1307
1ce15ef4
JY
1308 case SHN_LIVEPATCH:
1309 /* Livepatch symbols are resolved by livepatch */
1310 break;
1311
1da177e4 1312 case SHN_UNDEF:
49668688 1313 ksym = resolve_symbol_wait(mod, info, name);
1da177e4 1314 /* Ok if resolved. */
9bea7f23 1315 if (ksym && !IS_ERR(ksym)) {
7290d580 1316 sym[i].st_value = kernel_symbol_value(ksym);
1da177e4 1317 break;
414fd31b
TA
1318 }
1319
ebfac7b7
FS
1320 /* Ok if weak or ignored. */
1321 if (!ksym &&
1322 (ELF_ST_BIND(sym[i].st_info) == STB_WEAK ||
1323 ignore_undef_symbol(info->hdr->e_machine, name)))
1da177e4
LT
1324 break;
1325
9bea7f23 1326 ret = PTR_ERR(ksym) ?: -ENOENT;
62267e0e
JD
1327 pr_warn("%s: Unknown symbol %s (err %d)\n",
1328 mod->name, name, ret);
1da177e4
LT
1329 break;
1330
1331 default:
1332 /* Divert to percpu allocation if a percpu var. */
49668688 1333 if (sym[i].st_shndx == info->index.pcpu)
259354de 1334 secbase = (unsigned long)mod_percpu(mod);
1da177e4 1335 else
49668688 1336 secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
1da177e4
LT
1337 sym[i].st_value += secbase;
1338 break;
1339 }
1340 }
1341
1342 return ret;
1343}
1344
49668688 1345static int apply_relocations(struct module *mod, const struct load_info *info)
22e268eb
RR
1346{
1347 unsigned int i;
1348 int err = 0;
1349
1350 /* Now do relocations. */
49668688
RR
1351 for (i = 1; i < info->hdr->e_shnum; i++) {
1352 unsigned int infosec = info->sechdrs[i].sh_info;
22e268eb
RR
1353
1354 /* Not a valid relocation section? */
49668688 1355 if (infosec >= info->hdr->e_shnum)
22e268eb
RR
1356 continue;
1357
1358 /* Don't bother with non-allocated sections */
49668688 1359 if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
22e268eb
RR
1360 continue;
1361
1ce15ef4 1362 if (info->sechdrs[i].sh_flags & SHF_RELA_LIVEPATCH)
7c8e2bdd
JP
1363 err = klp_apply_section_relocs(mod, info->sechdrs,
1364 info->secstrings,
1365 info->strtab,
1366 info->index.sym, i,
1367 NULL);
1368 else if (info->sechdrs[i].sh_type == SHT_REL)
49668688
RR
1369 err = apply_relocate(info->sechdrs, info->strtab,
1370 info->index.sym, i, mod);
1371 else if (info->sechdrs[i].sh_type == SHT_RELA)
1372 err = apply_relocate_add(info->sechdrs, info->strtab,
1373 info->index.sym, i, mod);
22e268eb
RR
1374 if (err < 0)
1375 break;
1376 }
1377 return err;
1378}
1379
088af9a6
HD
1380/* Additional bytes needed by arch in front of individual sections */
1381unsigned int __weak arch_mod_section_prepend(struct module *mod,
1382 unsigned int section)
1383{
1384 /* default implementation just returns zero */
1385 return 0;
1386}
1387
1da177e4 1388/* Update size with this section: return offset. */
91fb02f3 1389long module_get_offset(struct module *mod, unsigned int *size,
088af9a6 1390 Elf_Shdr *sechdr, unsigned int section)
1da177e4
LT
1391{
1392 long ret;
1393
088af9a6 1394 *size += arch_mod_section_prepend(mod, section);
1da177e4
LT
1395 ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
1396 *size = ret + sechdr->sh_size;
1397 return ret;
1398}
1399
055f23b7
JY
1400static bool module_init_layout_section(const char *sname)
1401{
1402#ifndef CONFIG_MODULE_UNLOAD
1403 if (module_exit_section(sname))
1404 return true;
1405#endif
1406 return module_init_section(sname);
1407}
1408
24b9f0d2
SS
1409/*
1410 * Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
1411 * might -- code, read-only data, read-write data, small data. Tally
1412 * sizes, and place the offsets into sh_entsize fields: high bit means it
1413 * belongs in init.
1414 */
49668688 1415static void layout_sections(struct module *mod, struct load_info *info)
1da177e4
LT
1416{
1417 static unsigned long const masks[][2] = {
24b9f0d2
SS
1418 /*
1419 * NOTE: all executable code must be the first section
1da177e4 1420 * in this array; otherwise modify the text_size
24b9f0d2
SS
1421 * finder in the two loops below
1422 */
1da177e4
LT
1423 { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
1424 { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
444d13ff 1425 { SHF_RO_AFTER_INIT | SHF_ALLOC, ARCH_SHF_SMALL },
1da177e4
LT
1426 { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
1427 { ARCH_SHF_SMALL | SHF_ALLOC, 0 }
1428 };
1429 unsigned int m, i;
1430
49668688
RR
1431 for (i = 0; i < info->hdr->e_shnum; i++)
1432 info->sechdrs[i].sh_entsize = ~0UL;
1da177e4 1433
5e124169 1434 pr_debug("Core section allocation order:\n");
1da177e4 1435 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
49668688
RR
1436 for (i = 0; i < info->hdr->e_shnum; ++i) {
1437 Elf_Shdr *s = &info->sechdrs[i];
1438 const char *sname = info->secstrings + s->sh_name;
1da177e4
LT
1439
1440 if ((s->sh_flags & masks[m][0]) != masks[m][0]
1441 || (s->sh_flags & masks[m][1])
1442 || s->sh_entsize != ~0UL
055f23b7 1443 || module_init_layout_section(sname))
1da177e4 1444 continue;
91fb02f3 1445 s->sh_entsize = module_get_offset(mod, &mod->core_layout.size, s, i);
5e124169 1446 pr_debug("\t%s\n", sname);
1da177e4 1447 }
84e1c6bb 1448 switch (m) {
1449 case 0: /* executable */
7523e4dc
RR
1450 mod->core_layout.size = debug_align(mod->core_layout.size);
1451 mod->core_layout.text_size = mod->core_layout.size;
84e1c6bb 1452 break;
1453 case 1: /* RO: text and ro-data */
7523e4dc
RR
1454 mod->core_layout.size = debug_align(mod->core_layout.size);
1455 mod->core_layout.ro_size = mod->core_layout.size;
84e1c6bb 1456 break;
444d13ff
JY
1457 case 2: /* RO after init */
1458 mod->core_layout.size = debug_align(mod->core_layout.size);
1459 mod->core_layout.ro_after_init_size = mod->core_layout.size;
1460 break;
1461 case 4: /* whole core */
7523e4dc 1462 mod->core_layout.size = debug_align(mod->core_layout.size);
84e1c6bb 1463 break;
1464 }
1da177e4
LT
1465 }
1466
5e124169 1467 pr_debug("Init section allocation order:\n");
1da177e4 1468 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
49668688
RR
1469 for (i = 0; i < info->hdr->e_shnum; ++i) {
1470 Elf_Shdr *s = &info->sechdrs[i];
1471 const char *sname = info->secstrings + s->sh_name;
1da177e4
LT
1472
1473 if ((s->sh_flags & masks[m][0]) != masks[m][0]
1474 || (s->sh_flags & masks[m][1])
1475 || s->sh_entsize != ~0UL
055f23b7 1476 || !module_init_layout_section(sname))
1da177e4 1477 continue;
91fb02f3 1478 s->sh_entsize = (module_get_offset(mod, &mod->init_layout.size, s, i)
1da177e4 1479 | INIT_OFFSET_MASK);
5e124169 1480 pr_debug("\t%s\n", sname);
1da177e4 1481 }
84e1c6bb 1482 switch (m) {
1483 case 0: /* executable */
7523e4dc
RR
1484 mod->init_layout.size = debug_align(mod->init_layout.size);
1485 mod->init_layout.text_size = mod->init_layout.size;
84e1c6bb 1486 break;
1487 case 1: /* RO: text and ro-data */
7523e4dc
RR
1488 mod->init_layout.size = debug_align(mod->init_layout.size);
1489 mod->init_layout.ro_size = mod->init_layout.size;
84e1c6bb 1490 break;
444d13ff
JY
1491 case 2:
1492 /*
1493 * RO after init doesn't apply to init_layout (only
1494 * core_layout), so it just takes the value of ro_size.
1495 */
1496 mod->init_layout.ro_after_init_size = mod->init_layout.ro_size;
1497 break;
1498 case 4: /* whole init */
7523e4dc 1499 mod->init_layout.size = debug_align(mod->init_layout.size);
84e1c6bb 1500 break;
1501 }
1da177e4
LT
1502 }
1503}
1504
1da177e4
LT
1505static void set_license(struct module *mod, const char *license)
1506{
1507 if (!license)
1508 license = "unspecified";
1509
fa3ba2e8 1510 if (!license_is_gpl_compatible(license)) {
25ddbb18 1511 if (!test_taint(TAINT_PROPRIETARY_MODULE))
bddb12b3
AM
1512 pr_warn("%s: module license '%s' taints kernel.\n",
1513 mod->name, license);
373d4d09
RR
1514 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
1515 LOCKDEP_NOW_UNRELIABLE);
1da177e4
LT
1516 }
1517}
1518
1519/* Parse tag=value strings from .modinfo section */
1520static char *next_string(char *string, unsigned long *secsize)
1521{
1522 /* Skip non-zero chars */
1523 while (string[0]) {
1524 string++;
1525 if ((*secsize)-- <= 1)
1526 return NULL;
1527 }
1528
1529 /* Skip any zero padding. */
1530 while (!string[0]) {
1531 string++;
1532 if ((*secsize)-- <= 1)
1533 return NULL;
1534 }
1535 return string;
1536}
1537
c5e4a062
MM
1538static char *get_next_modinfo(const struct load_info *info, const char *tag,
1539 char *prev)
1da177e4
LT
1540{
1541 char *p;
1542 unsigned int taglen = strlen(tag);
49668688
RR
1543 Elf_Shdr *infosec = &info->sechdrs[info->index.info];
1544 unsigned long size = infosec->sh_size;
1da177e4 1545
5fdc7db6
JY
1546 /*
1547 * get_modinfo() calls made before rewrite_section_headers()
1548 * must use sh_offset, as sh_addr isn't set!
1549 */
c5e4a062
MM
1550 char *modinfo = (char *)info->hdr + infosec->sh_offset;
1551
1552 if (prev) {
1553 size -= prev - modinfo;
1554 modinfo = next_string(prev, &size);
1555 }
1556
1557 for (p = modinfo; p; p = next_string(p, &size)) {
1da177e4
LT
1558 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
1559 return p + taglen + 1;
1560 }
1561 return NULL;
1562}
1563
c5e4a062
MM
1564static char *get_modinfo(const struct load_info *info, const char *tag)
1565{
1566 return get_next_modinfo(info, tag, NULL);
1567}
1568
49668688 1569static void setup_modinfo(struct module *mod, struct load_info *info)
c988d2b2
MD
1570{
1571 struct module_attribute *attr;
1572 int i;
1573
1574 for (i = 0; (attr = modinfo_attrs[i]); i++) {
1575 if (attr->setup)
49668688 1576 attr->setup(mod, get_modinfo(info, attr->attr.name));
c988d2b2
MD
1577 }
1578}
c988d2b2 1579
a263f776
RR
1580static void free_modinfo(struct module *mod)
1581{
1582 struct module_attribute *attr;
1583 int i;
1584
1585 for (i = 0; (attr = modinfo_attrs[i]); i++) {
1586 if (attr->free)
1587 attr->free(mod);
1588 }
1589}
1590
52796312 1591static void dynamic_debug_setup(struct module *mod, struct _ddebug *debug, unsigned int num)
346e15be 1592{
811d66a0
RR
1593 if (!debug)
1594 return;
513770f5 1595 ddebug_add_module(debug, num, mod->name);
5e458cc0 1596}
346e15be 1597
52796312 1598static void dynamic_debug_remove(struct module *mod, struct _ddebug *debug)
ff49d74a
YS
1599{
1600 if (debug)
52796312 1601 ddebug_remove_module(mod->name);
ff49d74a
YS
1602}
1603
74e08fcf
JB
1604void * __weak module_alloc(unsigned long size)
1605{
7a0e27b2
CH
1606 return __vmalloc_node_range(size, 1, VMALLOC_START, VMALLOC_END,
1607 GFP_KERNEL, PAGE_KERNEL_EXEC, VM_FLUSH_RESET_PERMS,
a3a66c38 1608 NUMA_NO_NODE, __builtin_return_address(0));
74e08fcf
JB
1609}
1610
23189766
VW
1611bool __weak module_init_section(const char *name)
1612{
1613 return strstarts(name, ".init");
1614}
1615
38b37d63
MS
1616bool __weak module_exit_section(const char *name)
1617{
1618 return strstarts(name, ".exit");
1619}
1620
ec2a2959 1621static int validate_section_offset(struct load_info *info, Elf_Shdr *shdr)
40dd2560 1622{
d83d42d0
SK
1623#if defined(CONFIG_64BIT)
1624 unsigned long long secend;
1625#else
ec2a2959 1626 unsigned long secend;
d83d42d0 1627#endif
ec2a2959
FL
1628
1629 /*
1630 * Check for both overflow and offset/size being
1631 * too large.
1632 */
1633 secend = shdr->sh_offset + shdr->sh_size;
1634 if (secend < shdr->sh_offset || secend > info->len)
1635 return -ENOEXEC;
1636
1637 return 0;
1638}
1639
1640/*
1641 * Sanity checks against invalid binaries, wrong arch, weird elf version.
1642 *
1643 * Also do basic validity checks against section offsets and sizes, the
1644 * section name string table, and the indices used for it (sh_name).
1645 */
1646static int elf_validity_check(struct load_info *info)
1647{
1648 unsigned int i;
1649 Elf_Shdr *shdr, *strhdr;
1650 int err;
1651
7fd982f3
SK
1652 if (info->len < sizeof(*(info->hdr))) {
1653 pr_err("Invalid ELF header len %lu\n", info->len);
1654 goto no_exec;
1655 }
34e1169d 1656
7fd982f3
SK
1657 if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0) {
1658 pr_err("Invalid ELF header magic: != %s\n", ELFMAG);
1659 goto no_exec;
1660 }
1661 if (info->hdr->e_type != ET_REL) {
1662 pr_err("Invalid ELF header type: %u != %u\n",
1663 info->hdr->e_type, ET_REL);
1664 goto no_exec;
1665 }
1666 if (!elf_check_arch(info->hdr)) {
1667 pr_err("Invalid architecture in ELF header: %u\n",
1668 info->hdr->e_machine);
1669 goto no_exec;
1670 }
1671 if (info->hdr->e_shentsize != sizeof(Elf_Shdr)) {
1672 pr_err("Invalid ELF section header size\n");
1673 goto no_exec;
1674 }
34e1169d 1675
ec2a2959
FL
1676 /*
1677 * e_shnum is 16 bits, and sizeof(Elf_Shdr) is
1678 * known and small. So e_shnum * sizeof(Elf_Shdr)
1679 * will not overflow unsigned long on any platform.
1680 */
34e1169d
KC
1681 if (info->hdr->e_shoff >= info->len
1682 || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
7fd982f3
SK
1683 info->len - info->hdr->e_shoff)) {
1684 pr_err("Invalid ELF section header overflow\n");
1685 goto no_exec;
1686 }
40dd2560 1687
ec2a2959
FL
1688 info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
1689
1690 /*
1691 * Verify if the section name table index is valid.
1692 */
1693 if (info->hdr->e_shstrndx == SHN_UNDEF
7fd982f3
SK
1694 || info->hdr->e_shstrndx >= info->hdr->e_shnum) {
1695 pr_err("Invalid ELF section name index: %d || e_shstrndx (%d) >= e_shnum (%d)\n",
1696 info->hdr->e_shstrndx, info->hdr->e_shstrndx,
1697 info->hdr->e_shnum);
1698 goto no_exec;
1699 }
ec2a2959
FL
1700
1701 strhdr = &info->sechdrs[info->hdr->e_shstrndx];
1702 err = validate_section_offset(info, strhdr);
7fd982f3
SK
1703 if (err < 0) {
1704 pr_err("Invalid ELF section hdr(type %u)\n", strhdr->sh_type);
ec2a2959 1705 return err;
7fd982f3 1706 }
ec2a2959
FL
1707
1708 /*
1709 * The section name table must be NUL-terminated, as required
1710 * by the spec. This makes strcmp and pr_* calls that access
1711 * strings in the section safe.
1712 */
1713 info->secstrings = (void *)info->hdr + strhdr->sh_offset;
7fd982f3
SK
1714 if (info->secstrings[strhdr->sh_size - 1] != '\0') {
1715 pr_err("ELF Spec violation: section name table isn't null terminated\n");
1716 goto no_exec;
1717 }
ec2a2959
FL
1718
1719 /*
1720 * The code assumes that section 0 has a length of zero and
1721 * an addr of zero, so check for it.
1722 */
1723 if (info->sechdrs[0].sh_type != SHT_NULL
1724 || info->sechdrs[0].sh_size != 0
7fd982f3
SK
1725 || info->sechdrs[0].sh_addr != 0) {
1726 pr_err("ELF Spec violation: section 0 type(%d)!=SH_NULL or non-zero len or addr\n",
1727 info->sechdrs[0].sh_type);
1728 goto no_exec;
1729 }
ec2a2959
FL
1730
1731 for (i = 1; i < info->hdr->e_shnum; i++) {
1732 shdr = &info->sechdrs[i];
1733 switch (shdr->sh_type) {
1734 case SHT_NULL:
1735 case SHT_NOBITS:
1736 continue;
1737 case SHT_SYMTAB:
1738 if (shdr->sh_link == SHN_UNDEF
7fd982f3
SK
1739 || shdr->sh_link >= info->hdr->e_shnum) {
1740 pr_err("Invalid ELF sh_link!=SHN_UNDEF(%d) or (sh_link(%d) >= hdr->e_shnum(%d)\n",
1741 shdr->sh_link, shdr->sh_link,
1742 info->hdr->e_shnum);
1743 goto no_exec;
1744 }
ec2a2959
FL
1745 fallthrough;
1746 default:
1747 err = validate_section_offset(info, shdr);
1748 if (err < 0) {
1749 pr_err("Invalid ELF section in module (section %u type %u)\n",
1750 i, shdr->sh_type);
1751 return err;
1752 }
1753
1754 if (shdr->sh_flags & SHF_ALLOC) {
1755 if (shdr->sh_name >= strhdr->sh_size) {
1756 pr_err("Invalid ELF section name in module (section %u type %u)\n",
1757 i, shdr->sh_type);
1758 return -ENOEXEC;
1759 }
1760 }
1761 break;
1762 }
1763 }
1764
34e1169d 1765 return 0;
7fd982f3
SK
1766
1767no_exec:
1768 return -ENOEXEC;
34e1169d
KC
1769}
1770
3afe9f84
LT
1771#define COPY_CHUNK_SIZE (16*PAGE_SIZE)
1772
1773static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len)
1774{
1775 do {
1776 unsigned long n = min(len, COPY_CHUNK_SIZE);
1777
1778 if (copy_from_user(dst, usrc, n) != 0)
1779 return -EFAULT;
1780 cond_resched();
1781 dst += n;
1782 usrc += n;
1783 len -= n;
1784 } while (len);
1785 return 0;
1786}
1787
2992ef29 1788static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
1ce15ef4 1789{
1be9473e
AT
1790 if (!get_modinfo(info, "livepatch"))
1791 /* Nothing more to do */
1792 return 0;
1793
1794 if (set_livepatch_module(mod)) {
2992ef29 1795 add_taint_module(mod, TAINT_LIVEPATCH, LOCKDEP_STILL_OK);
7598d167 1796 pr_notice_once("%s: tainting kernel with TAINT_LIVEPATCH\n",
1be9473e
AT
1797 mod->name);
1798 return 0;
1ce15ef4
JY
1799 }
1800
1be9473e
AT
1801 pr_err("%s: module is marked as livepatch module, but livepatch support is disabled",
1802 mod->name);
1803 return -ENOEXEC;
1ce15ef4 1804}
1ce15ef4 1805
caf7501a
AK
1806static void check_modinfo_retpoline(struct module *mod, struct load_info *info)
1807{
1808 if (retpoline_module_ok(get_modinfo(info, "retpoline")))
1809 return;
1810
1811 pr_warn("%s: loading module not compiled with retpoline compiler.\n",
1812 mod->name);
1813}
1814
34e1169d
KC
1815/* Sets info->hdr and info->len. */
1816static int copy_module_from_user(const void __user *umod, unsigned long len,
1817 struct load_info *info)
40dd2560
RR
1818{
1819 int err;
40dd2560 1820
34e1169d
KC
1821 info->len = len;
1822 if (info->len < sizeof(*(info->hdr)))
40dd2560
RR
1823 return -ENOEXEC;
1824
38f90173 1825 err = security_kernel_load_data(LOADING_MODULE, true);
2e72d51b
KC
1826 if (err)
1827 return err;
1828
40dd2560 1829 /* Suck in entire file: we'll want most of it. */
88dca4ca 1830 info->hdr = __vmalloc(info->len, GFP_KERNEL | __GFP_NOWARN);
34e1169d 1831 if (!info->hdr)
40dd2560
RR
1832 return -ENOMEM;
1833
3afe9f84 1834 if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) {
38f90173
KC
1835 err = -EFAULT;
1836 goto out;
40dd2560
RR
1837 }
1838
38f90173
KC
1839 err = security_kernel_post_load_data((char *)info->hdr, info->len,
1840 LOADING_MODULE, "init_module");
1841out:
1842 if (err)
1843 vfree(info->hdr);
1844
1845 return err;
34e1169d
KC
1846}
1847
b1ae6dc4 1848static void free_copy(struct load_info *info, int flags)
d913188c 1849{
b1ae6dc4
DT
1850 if (flags & MODULE_INIT_COMPRESSED_FILE)
1851 module_decompress_cleanup(info);
1852 else
1853 vfree(info->hdr);
d913188c
RR
1854}
1855
2f3238ae 1856static int rewrite_section_headers(struct load_info *info, int flags)
8b5f61a7
RR
1857{
1858 unsigned int i;
1859
1860 /* This should always be true, but let's be sure. */
1861 info->sechdrs[0].sh_addr = 0;
1862
1863 for (i = 1; i < info->hdr->e_shnum; i++) {
1864 Elf_Shdr *shdr = &info->sechdrs[i];
8b5f61a7 1865
24b9f0d2
SS
1866 /*
1867 * Mark all sections sh_addr with their address in the
1868 * temporary image.
1869 */
8b5f61a7
RR
1870 shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
1871
8b5f61a7 1872 }
d6df72a0
RR
1873
1874 /* Track but don't keep modinfo and version sections. */
3e2e857f 1875 info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
d6df72a0 1876 info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
3e2e857f 1877
8b5f61a7
RR
1878 return 0;
1879}
1880
3264d3f9
LT
1881/*
1882 * Set up our basic convenience variables (pointers to section headers,
1883 * search for module section index etc), and do some basic section
1884 * verification.
1885 *
81a0abd9
JY
1886 * Set info->mod to the temporary copy of the module in info->hdr. The final one
1887 * will be allocated in move_module().
3264d3f9 1888 */
81a0abd9 1889static int setup_load_info(struct load_info *info, int flags)
3264d3f9
LT
1890{
1891 unsigned int i;
3264d3f9 1892
5fdc7db6
JY
1893 /* Try to find a name early so we can log errors with a module name */
1894 info->index.info = find_sec(info, ".modinfo");
708e0ada 1895 if (info->index.info)
5fdc7db6 1896 info->name = get_modinfo(info, "name");
3264d3f9 1897
8b5f61a7
RR
1898 /* Find internal symbols and strings. */
1899 for (i = 1; i < info->hdr->e_shnum; i++) {
3264d3f9
LT
1900 if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
1901 info->index.sym = i;
1902 info->index.str = info->sechdrs[i].sh_link;
8b5f61a7
RR
1903 info->strtab = (char *)info->hdr
1904 + info->sechdrs[info->index.str].sh_offset;
1905 break;
3264d3f9 1906 }
3264d3f9
LT
1907 }
1908
5fdc7db6 1909 if (info->index.sym == 0) {
708e0ada
JY
1910 pr_warn("%s: module has no symbols (stripped?)\n",
1911 info->name ?: "(missing .modinfo section or name field)");
5fdc7db6
JY
1912 return -ENOEXEC;
1913 }
1914
49668688 1915 info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
3264d3f9 1916 if (!info->index.mod) {
3e2e857f 1917 pr_warn("%s: No module found in object\n",
708e0ada 1918 info->name ?: "(missing .modinfo section or name field)");
81a0abd9 1919 return -ENOEXEC;
3264d3f9
LT
1920 }
1921 /* This is temporary: point mod into copy of data. */
5fdc7db6 1922 info->mod = (void *)info->hdr + info->sechdrs[info->index.mod].sh_offset;
3264d3f9 1923
3e2e857f 1924 /*
5fdc7db6 1925 * If we didn't load the .modinfo 'name' field earlier, fall back to
3e2e857f
KC
1926 * on-disk struct mod 'name' field.
1927 */
1928 if (!info->name)
81a0abd9 1929 info->name = info->mod->name;
3e2e857f 1930
5fdc7db6
JY
1931 if (flags & MODULE_INIT_IGNORE_MODVERSIONS)
1932 info->index.vers = 0; /* Pretend no __versions section! */
1933 else
1934 info->index.vers = find_sec(info, "__versions");
3264d3f9 1935
49668688 1936 info->index.pcpu = find_pcpusec(info);
3264d3f9 1937
81a0abd9 1938 return 0;
3264d3f9
LT
1939}
1940
2f3238ae 1941static int check_modinfo(struct module *mod, struct load_info *info, int flags)
40dd2560 1942{
49668688 1943 const char *modmagic = get_modinfo(info, "vermagic");
40dd2560
RR
1944 int err;
1945
2f3238ae
RR
1946 if (flags & MODULE_INIT_IGNORE_VERMAGIC)
1947 modmagic = NULL;
1948
40dd2560
RR
1949 /* This is allowed: modprobe --force will invalidate it. */
1950 if (!modmagic) {
1951 err = try_to_force_load(mod, "bad vermagic");
1952 if (err)
1953 return err;
49668688 1954 } else if (!same_magic(modmagic, vermagic, info->index.vers)) {
bddb12b3 1955 pr_err("%s: version magic '%s' should be '%s'\n",
3e2e857f 1956 info->name, modmagic, vermagic);
40dd2560
RR
1957 return -ENOEXEC;
1958 }
1959
3205c36c
LP
1960 if (!get_modinfo(info, "intree")) {
1961 if (!test_taint(TAINT_OOT_MODULE))
1962 pr_warn("%s: loading out-of-tree module taints kernel.\n",
1963 mod->name);
373d4d09 1964 add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
3205c36c 1965 }
2449b8ba 1966
caf7501a
AK
1967 check_modinfo_retpoline(mod, info);
1968
49668688 1969 if (get_modinfo(info, "staging")) {
373d4d09 1970 add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
bddb12b3
AM
1971 pr_warn("%s: module is from the staging directory, the quality "
1972 "is unknown, you have been warned.\n", mod->name);
40dd2560 1973 }
22e268eb 1974
2992ef29 1975 err = check_modinfo_livepatch(mod, info);
1ce15ef4
JY
1976 if (err)
1977 return err;
1978
22e268eb 1979 /* Set up license info based on the info section */
49668688 1980 set_license(mod, get_modinfo(info, "license"));
22e268eb 1981
40dd2560
RR
1982 return 0;
1983}
1984
eb3057df 1985static int find_module_sections(struct module *mod, struct load_info *info)
f91a13bb 1986{
49668688 1987 mod->kp = section_objs(info, "__param",
f91a13bb 1988 sizeof(*mod->kp), &mod->num_kp);
49668688 1989 mod->syms = section_objs(info, "__ksymtab",
f91a13bb 1990 sizeof(*mod->syms), &mod->num_syms);
49668688
RR
1991 mod->crcs = section_addr(info, "__kcrctab");
1992 mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
f91a13bb
LT
1993 sizeof(*mod->gpl_syms),
1994 &mod->num_gpl_syms);
49668688 1995 mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
f91a13bb 1996
f91a13bb 1997#ifdef CONFIG_CONSTRUCTORS
49668688 1998 mod->ctors = section_objs(info, ".ctors",
f91a13bb 1999 sizeof(*mod->ctors), &mod->num_ctors);
eb3057df
FH
2000 if (!mod->ctors)
2001 mod->ctors = section_objs(info, ".init_array",
2002 sizeof(*mod->ctors), &mod->num_ctors);
2003 else if (find_sec(info, ".init_array")) {
2004 /*
2005 * This shouldn't happen with same compiler and binutils
2006 * building all parts of the module.
2007 */
6da0b565 2008 pr_warn("%s: has both .ctors and .init_array.\n",
eb3057df
FH
2009 mod->name);
2010 return -EINVAL;
2011 }
f91a13bb
LT
2012#endif
2013
66e9b071
TG
2014 mod->noinstr_text_start = section_objs(info, ".noinstr.text", 1,
2015 &mod->noinstr_text_size);
2016
f91a13bb 2017#ifdef CONFIG_TRACEPOINTS
65498646
MD
2018 mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
2019 sizeof(*mod->tracepoints_ptrs),
2020 &mod->num_tracepoints);
f91a13bb 2021#endif
fe15b50c
PM
2022#ifdef CONFIG_TREE_SRCU
2023 mod->srcu_struct_ptrs = section_objs(info, "___srcu_struct_ptrs",
2024 sizeof(*mod->srcu_struct_ptrs),
2025 &mod->num_srcu_structs);
2026#endif
a38d1107
MM
2027#ifdef CONFIG_BPF_EVENTS
2028 mod->bpf_raw_events = section_objs(info, "__bpf_raw_tp_map",
2029 sizeof(*mod->bpf_raw_events),
2030 &mod->num_bpf_raw_events);
2031#endif
36e68442
AN
2032#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
2033 mod->btf_data = any_section_objs(info, ".BTF", 1, &mod->btf_data_size);
2034#endif
e9666d10 2035#ifdef CONFIG_JUMP_LABEL
bf5438fc
JB
2036 mod->jump_entries = section_objs(info, "__jump_table",
2037 sizeof(*mod->jump_entries),
2038 &mod->num_jump_entries);
2039#endif
f91a13bb 2040#ifdef CONFIG_EVENT_TRACING
49668688 2041 mod->trace_events = section_objs(info, "_ftrace_events",
f91a13bb
LT
2042 sizeof(*mod->trace_events),
2043 &mod->num_trace_events);
99be647c
JL
2044 mod->trace_evals = section_objs(info, "_ftrace_eval_map",
2045 sizeof(*mod->trace_evals),
2046 &mod->num_trace_evals);
f91a13bb 2047#endif
13b9b6e7
SR
2048#ifdef CONFIG_TRACING
2049 mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
2050 sizeof(*mod->trace_bprintk_fmt_start),
2051 &mod->num_trace_bprintk_fmt);
13b9b6e7 2052#endif
f91a13bb
LT
2053#ifdef CONFIG_FTRACE_MCOUNT_RECORD
2054 /* sechdrs[0].sh_size is always zero */
a1326b17 2055 mod->ftrace_callsites = section_objs(info, FTRACE_CALLSITE_SECTION,
f91a13bb
LT
2056 sizeof(*mod->ftrace_callsites),
2057 &mod->num_ftrace_callsites);
2058#endif
540adea3
MH
2059#ifdef CONFIG_FUNCTION_ERROR_INJECTION
2060 mod->ei_funcs = section_objs(info, "_error_injection_whitelist",
2061 sizeof(*mod->ei_funcs),
2062 &mod->num_ei_funcs);
1e6769b0
MH
2063#endif
2064#ifdef CONFIG_KPROBES
2065 mod->kprobes_text_start = section_objs(info, ".kprobes.text", 1,
2066 &mod->kprobes_text_size);
16db6264
MH
2067 mod->kprobe_blacklist = section_objs(info, "_kprobe_blacklist",
2068 sizeof(unsigned long),
2069 &mod->num_kprobe_blacklist);
9183c3f9 2070#endif
33701557
CD
2071#ifdef CONFIG_PRINTK_INDEX
2072 mod->printk_index_start = section_objs(info, ".printk_index",
2073 sizeof(*mod->printk_index_start),
2074 &mod->printk_index_size);
2075#endif
9183c3f9
JP
2076#ifdef CONFIG_HAVE_STATIC_CALL_INLINE
2077 mod->static_call_sites = section_objs(info, ".static_call_sites",
2078 sizeof(*mod->static_call_sites),
2079 &mod->num_static_call_sites);
92ace999 2080#endif
811d66a0
RR
2081 mod->extable = section_objs(info, "__ex_table",
2082 sizeof(*mod->extable), &mod->num_exentries);
2083
49668688 2084 if (section_addr(info, "__obsparm"))
bddb12b3 2085 pr_warn("%s: Ignoring obsolete parameters\n", mod->name);
811d66a0 2086
e5ebffe1 2087 info->debug = section_objs(info, "__dyndbg",
811d66a0 2088 sizeof(*info->debug), &info->num_debug);
eb3057df
FH
2089
2090 return 0;
f91a13bb
LT
2091}
2092
49668688 2093static int move_module(struct module *mod, struct load_info *info)
65b8a9b4
LT
2094{
2095 int i;
2096 void *ptr;
2097
2098 /* Do the allocs. */
7523e4dc 2099 ptr = module_alloc(mod->core_layout.size);
65b8a9b4
LT
2100 /*
2101 * The pointer to this block is stored in the module structure
2102 * which is inside the block. Just mark it as not being a
2103 * leak.
2104 */
2105 kmemleak_not_leak(ptr);
2106 if (!ptr)
d913188c 2107 return -ENOMEM;
65b8a9b4 2108
7523e4dc
RR
2109 memset(ptr, 0, mod->core_layout.size);
2110 mod->core_layout.base = ptr;
65b8a9b4 2111
7523e4dc
RR
2112 if (mod->init_layout.size) {
2113 ptr = module_alloc(mod->init_layout.size);
82fab442
RR
2114 /*
2115 * The pointer to this block is stored in the module structure
2116 * which is inside the block. This block doesn't need to be
2117 * scanned as it contains data and code that will be freed
2118 * after the module is initialized.
2119 */
2120 kmemleak_ignore(ptr);
2121 if (!ptr) {
7523e4dc 2122 module_memfree(mod->core_layout.base);
82fab442
RR
2123 return -ENOMEM;
2124 }
7523e4dc
RR
2125 memset(ptr, 0, mod->init_layout.size);
2126 mod->init_layout.base = ptr;
82fab442 2127 } else
7523e4dc 2128 mod->init_layout.base = NULL;
65b8a9b4
LT
2129
2130 /* Transfer each section which specifies SHF_ALLOC */
5e124169 2131 pr_debug("final section addresses:\n");
49668688 2132 for (i = 0; i < info->hdr->e_shnum; i++) {
65b8a9b4 2133 void *dest;
49668688 2134 Elf_Shdr *shdr = &info->sechdrs[i];
65b8a9b4 2135
49668688 2136 if (!(shdr->sh_flags & SHF_ALLOC))
65b8a9b4
LT
2137 continue;
2138
49668688 2139 if (shdr->sh_entsize & INIT_OFFSET_MASK)
7523e4dc 2140 dest = mod->init_layout.base
49668688 2141 + (shdr->sh_entsize & ~INIT_OFFSET_MASK);
65b8a9b4 2142 else
7523e4dc 2143 dest = mod->core_layout.base + shdr->sh_entsize;
65b8a9b4 2144
49668688
RR
2145 if (shdr->sh_type != SHT_NOBITS)
2146 memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
65b8a9b4 2147 /* Update sh_addr to point to copy in image. */
49668688 2148 shdr->sh_addr = (unsigned long)dest;
5e124169
JC
2149 pr_debug("\t0x%lx %s\n",
2150 (long)shdr->sh_addr, info->secstrings + shdr->sh_name);
65b8a9b4 2151 }
d913188c
RR
2152
2153 return 0;
65b8a9b4
LT
2154}
2155
49668688 2156static int check_module_license_and_versions(struct module *mod)
22e268eb 2157{
3205c36c
LP
2158 int prev_taint = test_taint(TAINT_PROPRIETARY_MODULE);
2159
22e268eb
RR
2160 /*
2161 * ndiswrapper is under GPL by itself, but loads proprietary modules.
2162 * Don't use add_taint_module(), as it would prevent ndiswrapper from
2163 * using GPL-only symbols it needs.
2164 */
2165 if (strcmp(mod->name, "ndiswrapper") == 0)
373d4d09 2166 add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
22e268eb
RR
2167
2168 /* driverloader was caught wrongly pretending to be under GPL */
2169 if (strcmp(mod->name, "driverloader") == 0)
373d4d09
RR
2170 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2171 LOCKDEP_NOW_UNRELIABLE);
22e268eb 2172
c99af375
MG
2173 /* lve claims to be GPL but upstream won't provide source */
2174 if (strcmp(mod->name, "lve") == 0)
373d4d09
RR
2175 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2176 LOCKDEP_NOW_UNRELIABLE);
c99af375 2177
3205c36c
LP
2178 if (!prev_taint && test_taint(TAINT_PROPRIETARY_MODULE))
2179 pr_warn("%s: module license taints kernel.\n", mod->name);
2180
22e268eb 2181#ifdef CONFIG_MODVERSIONS
36794822
CH
2182 if ((mod->num_syms && !mod->crcs) ||
2183 (mod->num_gpl_syms && !mod->gpl_crcs)) {
22e268eb
RR
2184 return try_to_force_load(mod,
2185 "no versions for exported symbols");
2186 }
2187#endif
2188 return 0;
2189}
2190
2191static void flush_module_icache(const struct module *mod)
2192{
22e268eb
RR
2193 /*
2194 * Flush the instruction cache, since we've played with text.
2195 * Do it before processing of module parameters, so the module
2196 * can provide parameter accessor functions of its own.
2197 */
7523e4dc
RR
2198 if (mod->init_layout.base)
2199 flush_icache_range((unsigned long)mod->init_layout.base,
2200 (unsigned long)mod->init_layout.base
2201 + mod->init_layout.size);
2202 flush_icache_range((unsigned long)mod->core_layout.base,
2203 (unsigned long)mod->core_layout.base + mod->core_layout.size);
22e268eb
RR
2204}
2205
74e08fcf
JB
2206int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
2207 Elf_Shdr *sechdrs,
2208 char *secstrings,
2209 struct module *mod)
2210{
2211 return 0;
2212}
2213
be7de5f9
PB
2214/* module_blacklist is a comma-separated list of module names */
2215static char *module_blacklist;
96b5b194 2216static bool blacklisted(const char *module_name)
be7de5f9
PB
2217{
2218 const char *p;
2219 size_t len;
2220
2221 if (!module_blacklist)
2222 return false;
2223
2224 for (p = module_blacklist; *p; p += len) {
2225 len = strcspn(p, ",");
2226 if (strlen(module_name) == len && !memcmp(module_name, p, len))
2227 return true;
2228 if (p[len] == ',')
2229 len++;
2230 }
2231 return false;
2232}
2233core_param(module_blacklist, module_blacklist, charp, 0400);
2234
2f3238ae 2235static struct module *layout_and_allocate(struct load_info *info, int flags)
1da177e4 2236{
1da177e4 2237 struct module *mod;
444d13ff 2238 unsigned int ndx;
d913188c 2239 int err;
3ae91c21 2240
81a0abd9 2241 err = check_modinfo(info->mod, info, flags);
40dd2560
RR
2242 if (err)
2243 return ERR_PTR(err);
1da177e4 2244
1da177e4 2245 /* Allow arches to frob section contents and sizes. */
49668688 2246 err = module_frob_arch_sections(info->hdr, info->sechdrs,
81a0abd9 2247 info->secstrings, info->mod);
1da177e4 2248 if (err < 0)
8d8022e8 2249 return ERR_PTR(err);
1da177e4 2250
5c3a7db0
PZ
2251 err = module_enforce_rwx_sections(info->hdr, info->sechdrs,
2252 info->secstrings, info->mod);
2253 if (err < 0)
2254 return ERR_PTR(err);
2255
8d8022e8
RR
2256 /* We will do a special allocation for per-cpu sections later. */
2257 info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
1da177e4 2258
444d13ff
JY
2259 /*
2260 * Mark ro_after_init section with SHF_RO_AFTER_INIT so that
2261 * layout_sections() can put it in the right place.
2262 * Note: ro_after_init sections also have SHF_{WRITE,ALLOC} set.
2263 */
2264 ndx = find_sec(info, ".data..ro_after_init");
e872267b
AB
2265 if (ndx)
2266 info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
2267 /*
2268 * Mark the __jump_table section as ro_after_init as well: these data
2269 * structures are never modified, with the exception of entries that
2270 * refer to code in the __init section, which are annotated as such
2271 * at module load time.
2272 */
2273 ndx = find_sec(info, "__jump_table");
444d13ff
JY
2274 if (ndx)
2275 info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
2276
24b9f0d2
SS
2277 /*
2278 * Determine total sizes, and put offsets in sh_entsize. For now
2279 * this is done generically; there doesn't appear to be any
2280 * special cases for the architectures.
2281 */
81a0abd9
JY
2282 layout_sections(info->mod, info);
2283 layout_symtab(info->mod, info);
1da177e4 2284
65b8a9b4 2285 /* Allocate and move to the final place */
81a0abd9 2286 err = move_module(info->mod, info);
d913188c 2287 if (err)
8d8022e8 2288 return ERR_PTR(err);
d913188c
RR
2289
2290 /* Module has been copied to its final place now: return it. */
2291 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
49668688 2292 kmemleak_load_module(mod, info);
d913188c 2293 return mod;
d913188c
RR
2294}
2295
2296/* mod is no longer valid after this! */
2297static void module_deallocate(struct module *mod, struct load_info *info)
2298{
d913188c 2299 percpu_modfree(mod);
d453cded 2300 module_arch_freeing_init(mod);
7523e4dc
RR
2301 module_memfree(mod->init_layout.base);
2302 module_memfree(mod->core_layout.base);
d913188c
RR
2303}
2304
74e08fcf
JB
2305int __weak module_finalize(const Elf_Ehdr *hdr,
2306 const Elf_Shdr *sechdrs,
2307 struct module *me)
2308{
2309 return 0;
2310}
2311
811d66a0
RR
2312static int post_relocation(struct module *mod, const struct load_info *info)
2313{
51f3d0f4 2314 /* Sort exception table now relocations are done. */
811d66a0
RR
2315 sort_extable(mod->extable, mod->extable + mod->num_exentries);
2316
2317 /* Copy relocated percpu area over. */
2318 percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
2319 info->sechdrs[info->index.pcpu].sh_size);
2320
51f3d0f4 2321 /* Setup kallsyms-specific fields. */
811d66a0
RR
2322 add_kallsyms(mod, info);
2323
2324 /* Arch-specific module finalizing. */
2325 return module_finalize(info->hdr, info->sechdrs, mod);
2326}
2327
9bb9c3be
RR
2328/* Is this module of this name done loading? No locks held. */
2329static bool finished_loading(const char *name)
2330{
2331 struct module *mod;
2332 bool ret;
2333
9cc019b8
PZ
2334 /*
2335 * The module_mutex should not be a heavily contended lock;
2336 * if we get the occasional sleep here, we'll go an extra iteration
2337 * in the wait_event_interruptible(), which is harmless.
2338 */
2339 sched_annotate_sleep();
9bb9c3be 2340 mutex_lock(&module_mutex);
4f6de4d5 2341 mod = find_module_all(name, strlen(name), true);
6e6de3de 2342 ret = !mod || mod->state == MODULE_STATE_LIVE;
9bb9c3be
RR
2343 mutex_unlock(&module_mutex);
2344
2345 return ret;
2346}
2347
34e1169d
KC
2348/* Call module constructors. */
2349static void do_mod_ctors(struct module *mod)
2350{
2351#ifdef CONFIG_CONSTRUCTORS
2352 unsigned long i;
2353
2354 for (i = 0; i < mod->num_ctors; i++)
2355 mod->ctors[i]();
2356#endif
2357}
2358
c7496379
RR
2359/* For freeing module_init on success, in case kallsyms traversing */
2360struct mod_initfree {
1a7b7d92 2361 struct llist_node node;
c7496379
RR
2362 void *module_init;
2363};
2364
1a7b7d92 2365static void do_free_init(struct work_struct *w)
c7496379 2366{
1a7b7d92
RE
2367 struct llist_node *pos, *n, *list;
2368 struct mod_initfree *initfree;
2369
2370 list = llist_del_all(&init_free_list);
2371
2372 synchronize_rcu();
2373
2374 llist_for_each_safe(pos, n, list) {
2375 initfree = container_of(pos, struct mod_initfree, node);
2376 module_memfree(initfree->module_init);
2377 kfree(initfree);
2378 }
c7496379
RR
2379}
2380
be02a186
JK
2381/*
2382 * This is where the real work happens.
2383 *
2384 * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb
2385 * helper command 'lx-symbols'.
2386 */
2387static noinline int do_init_module(struct module *mod)
34e1169d
KC
2388{
2389 int ret = 0;
c7496379
RR
2390 struct mod_initfree *freeinit;
2391
2392 freeinit = kmalloc(sizeof(*freeinit), GFP_KERNEL);
2393 if (!freeinit) {
2394 ret = -ENOMEM;
2395 goto fail;
2396 }
7523e4dc 2397 freeinit->module_init = mod->init_layout.base;
34e1169d 2398
34e1169d
KC
2399 do_mod_ctors(mod);
2400 /* Start the module */
2401 if (mod->init != NULL)
2402 ret = do_one_initcall(mod->init);
2403 if (ret < 0) {
c7496379 2404 goto fail_free_freeinit;
34e1169d
KC
2405 }
2406 if (ret > 0) {
bddb12b3
AM
2407 pr_warn("%s: '%s'->init suspiciously returned %d, it should "
2408 "follow 0/-E convention\n"
2409 "%s: loading module anyway...\n",
2410 __func__, mod->name, ret, __func__);
34e1169d
KC
2411 dump_stack();
2412 }
2413
2414 /* Now it's a first class citizen! */
2415 mod->state = MODULE_STATE_LIVE;
2416 blocking_notifier_call_chain(&module_notify_list,
2417 MODULE_STATE_LIVE, mod);
2418
38dc717e
JY
2419 /* Delay uevent until module has finished its init routine */
2420 kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
2421
774a1221
TH
2422 /*
2423 * We need to finish all async code before the module init sequence
67d6212a
IP
2424 * is done. This has potential to deadlock if synchronous module
2425 * loading is requested from async (which is not allowed!).
774a1221 2426 *
67d6212a
IP
2427 * See commit 0fdff3ec6d87 ("async, kmod: warn on synchronous
2428 * request_module() from async workers") for more details.
774a1221 2429 */
67d6212a 2430 if (!mod->async_probe_requested)
774a1221 2431 async_synchronize_full();
34e1169d 2432
aba4b5c2 2433 ftrace_free_mem(mod, mod->init_layout.base, mod->init_layout.base +
3e234289 2434 mod->init_layout.size);
34e1169d
KC
2435 mutex_lock(&module_mutex);
2436 /* Drop initial reference. */
2437 module_put(mod);
2438 trim_init_extable(mod);
2439#ifdef CONFIG_KALLSYMS
8244062e
RR
2440 /* Switch to core kallsyms now init is done: kallsyms may be walking! */
2441 rcu_assign_pointer(mod->kallsyms, &mod->core_kallsyms);
34e1169d 2442#endif
444d13ff 2443 module_enable_ro(mod, true);
93c2e105 2444 mod_tree_remove_init(mod);
d453cded 2445 module_arch_freeing_init(mod);
7523e4dc
RR
2446 mod->init_layout.base = NULL;
2447 mod->init_layout.size = 0;
2448 mod->init_layout.ro_size = 0;
444d13ff 2449 mod->init_layout.ro_after_init_size = 0;
7523e4dc 2450 mod->init_layout.text_size = 0;
607c543f
AN
2451#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
2452 /* .BTF is not SHF_ALLOC and will get removed, so sanitize pointer */
2453 mod->btf_data = NULL;
607c543f 2454#endif
c7496379
RR
2455 /*
2456 * We want to free module_init, but be aware that kallsyms may be
0be964be 2457 * walking this with preempt disabled. In all the failure paths, we
cb2f5536 2458 * call synchronize_rcu(), but we don't want to slow down the success
1a7b7d92
RE
2459 * path. module_memfree() cannot be called in an interrupt, so do the
2460 * work and call synchronize_rcu() in a work queue.
2461 *
ae646f0b
JH
2462 * Note that module_alloc() on most architectures creates W+X page
2463 * mappings which won't be cleaned up until do_free_init() runs. Any
2464 * code such as mark_rodata_ro() which depends on those mappings to
2465 * be cleaned up needs to sync with the queued work - ie
cb2f5536 2466 * rcu_barrier()
c7496379 2467 */
1a7b7d92
RE
2468 if (llist_add(&freeinit->node, &init_free_list))
2469 schedule_work(&init_free_wq);
2470
34e1169d
KC
2471 mutex_unlock(&module_mutex);
2472 wake_up_all(&module_wq);
2473
2474 return 0;
c7496379
RR
2475
2476fail_free_freeinit:
2477 kfree(freeinit);
2478fail:
2479 /* Try to protect us from buggy refcounters. */
2480 mod->state = MODULE_STATE_GOING;
cb2f5536 2481 synchronize_rcu();
c7496379
RR
2482 module_put(mod);
2483 blocking_notifier_call_chain(&module_notify_list,
2484 MODULE_STATE_GOING, mod);
7e545d6e 2485 klp_module_going(mod);
7dcd182b 2486 ftrace_release_mod(mod);
c7496379
RR
2487 free_module(mod);
2488 wake_up_all(&module_wq);
2489 return ret;
34e1169d
KC
2490}
2491
2492static int may_init_module(void)
2493{
2494 if (!capable(CAP_SYS_MODULE) || modules_disabled)
2495 return -EPERM;
2496
2497 return 0;
2498}
2499
a3535c7e
RR
2500/*
2501 * We try to place it in the list now to make sure it's unique before
2502 * we dedicate too many resources. In particular, temporary percpu
2503 * memory exhaustion.
2504 */
2505static int add_unformed_module(struct module *mod)
2506{
2507 int err;
2508 struct module *old;
2509
2510 mod->state = MODULE_STATE_UNFORMED;
2511
2512again:
2513 mutex_lock(&module_mutex);
4f6de4d5
MK
2514 old = find_module_all(mod->name, strlen(mod->name), true);
2515 if (old != NULL) {
6e6de3de 2516 if (old->state != MODULE_STATE_LIVE) {
a3535c7e
RR
2517 /* Wait in case it fails to load. */
2518 mutex_unlock(&module_mutex);
9cc019b8
PZ
2519 err = wait_event_interruptible(module_wq,
2520 finished_loading(mod->name));
a3535c7e
RR
2521 if (err)
2522 goto out_unlocked;
2523 goto again;
2524 }
2525 err = -EEXIST;
2526 goto out;
2527 }
4f666546 2528 mod_update_bounds(mod);
a3535c7e 2529 list_add_rcu(&mod->list, &modules);
93c2e105 2530 mod_tree_insert(mod);
a3535c7e
RR
2531 err = 0;
2532
2533out:
2534 mutex_unlock(&module_mutex);
2535out_unlocked:
2536 return err;
2537}
2538
2539static int complete_formation(struct module *mod, struct load_info *info)
2540{
2541 int err;
2542
2543 mutex_lock(&module_mutex);
2544
2545 /* Find duplicate symbols (must be called under lock). */
2d25bc55 2546 err = verify_exported_symbols(mod);
a3535c7e
RR
2547 if (err < 0)
2548 goto out;
2549
2550 /* This relies on module_mutex for list integrity. */
2551 module_bug_finalize(info->hdr, info->sechdrs, mod);
2552
444d13ff 2553 module_enable_ro(mod, false);
85c898db 2554 module_enable_nx(mod);
af742623 2555 module_enable_x(mod);
4982223e 2556
24b9f0d2
SS
2557 /*
2558 * Mark state as coming so strong_try_module_get() ignores us,
2559 * but kallsyms etc. can see us.
2560 */
a3535c7e 2561 mod->state = MODULE_STATE_COMING;
4982223e
RR
2562 mutex_unlock(&module_mutex);
2563
4982223e 2564 return 0;
a3535c7e
RR
2565
2566out:
2567 mutex_unlock(&module_mutex);
2568 return err;
2569}
2570
4c973d16
JY
2571static int prepare_coming_module(struct module *mod)
2572{
7e545d6e
JY
2573 int err;
2574
4c973d16 2575 ftrace_module_enable(mod);
7e545d6e
JY
2576 err = klp_module_coming(mod);
2577 if (err)
2578 return err;
2579
59cc8e0a
PZ
2580 err = blocking_notifier_call_chain_robust(&module_notify_list,
2581 MODULE_STATE_COMING, MODULE_STATE_GOING, mod);
2582 err = notifier_to_errno(err);
2583 if (err)
2584 klp_module_going(mod);
2585
2586 return err;
4c973d16
JY
2587}
2588
ecc86170
LR
2589static int unknown_module_param_cb(char *param, char *val, const char *modname,
2590 void *arg)
54041d8a 2591{
f2411da7
LR
2592 struct module *mod = arg;
2593 int ret;
2594
2595 if (strcmp(param, "async_probe") == 0) {
2596 mod->async_probe_requested = true;
2597 return 0;
2598 }
2599
6da0b565 2600 /* Check for magic 'dyndbg' arg */
f2411da7 2601 ret = ddebug_dyndbg_module_param_cb(param, val, modname);
bddb12b3
AM
2602 if (ret != 0)
2603 pr_warn("%s: unknown parameter '%s' ignored\n", modname, param);
54041d8a
RR
2604 return 0;
2605}
2606
cf68fffb
ST
2607static void cfi_init(struct module *mod);
2608
24b9f0d2
SS
2609/*
2610 * Allocate and load the module: note that size of section 0 is always
2611 * zero, and we rely on this for optional sections.
2612 */
2f3238ae
RR
2613static int load_module(struct load_info *info, const char __user *uargs,
2614 int flags)
d913188c 2615{
a3535c7e 2616 struct module *mod;
5fdc7db6 2617 long err = 0;
51e158c1 2618 char *after_dashes;
d913188c 2619
ec2a2959
FL
2620 /*
2621 * Do the signature check (if any) first. All that
2622 * the signature check needs is info->len, it does
2623 * not need any of the section info. That can be
2624 * set up later. This will minimize the chances
2625 * of a corrupt module causing problems before
2626 * we even get to the signature check.
2627 *
2628 * The check will also adjust info->len by stripping
2629 * off the sig length at the end of the module, making
2630 * checks against info->len more correct.
2631 */
2632 err = module_sig_check(info, flags);
2633 if (err)
2634 goto free_copy;
2635
2636 /*
2637 * Do basic sanity checks against the ELF header and
2638 * sections.
2639 */
2640 err = elf_validity_check(info);
7fd982f3 2641 if (err)
5fdc7db6
JY
2642 goto free_copy;
2643
ec2a2959
FL
2644 /*
2645 * Everything checks out, so set up the section info
2646 * in the info structure.
2647 */
5fdc7db6
JY
2648 err = setup_load_info(info, flags);
2649 if (err)
2650 goto free_copy;
2651
ec2a2959
FL
2652 /*
2653 * Now that we know we have the correct module name, check
2654 * if it's blacklisted.
2655 */
5fdc7db6
JY
2656 if (blacklisted(info->name)) {
2657 err = -EPERM;
14721add 2658 pr_err("Module %s is blacklisted\n", info->name);
5fdc7db6
JY
2659 goto free_copy;
2660 }
2661
5fdc7db6 2662 err = rewrite_section_headers(info, flags);
d913188c 2663 if (err)
34e1169d 2664 goto free_copy;
d913188c 2665
5fdc7db6
JY
2666 /* Check module struct version now, before we try to use module. */
2667 if (!check_modstruct_version(info, info->mod)) {
2668 err = -ENOEXEC;
2669 goto free_copy;
2670 }
2671
d913188c 2672 /* Figure out module layout, and allocate all the memory. */
2f3238ae 2673 mod = layout_and_allocate(info, flags);
65b8a9b4
LT
2674 if (IS_ERR(mod)) {
2675 err = PTR_ERR(mod);
d913188c 2676 goto free_copy;
1da177e4 2677 }
1da177e4 2678
ca86cad7
RGB
2679 audit_log_kern_module(mod->name);
2680
a3535c7e
RR
2681 /* Reserve our place in the list. */
2682 err = add_unformed_module(mod);
2683 if (err)
1fb9341a 2684 goto free_module;
1fb9341a 2685
106a4ee2 2686#ifdef CONFIG_MODULE_SIG
34e1169d 2687 mod->sig_ok = info->sig_ok;
64748a2c 2688 if (!mod->sig_ok) {
bddb12b3 2689 pr_notice_once("%s: module verification failed: signature "
ab92ebbb 2690 "and/or required key missing - tainting "
bddb12b3 2691 "kernel\n", mod->name);
66cc69e3 2692 add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
64748a2c 2693 }
106a4ee2
RR
2694#endif
2695
8d8022e8 2696 /* To avoid stressing percpu allocator, do this once we're unique. */
9eb76d77 2697 err = percpu_modalloc(mod, info);
8d8022e8
RR
2698 if (err)
2699 goto unlink_mod;
2700
49668688 2701 /* Now module is in final location, initialize linked lists, etc. */
9f85a4bb
RR
2702 err = module_unload_init(mod);
2703 if (err)
1fb9341a 2704 goto unlink_mod;
1da177e4 2705
cf2fde7b 2706 init_param_lock(mod);
b51d23e4 2707
24b9f0d2
SS
2708 /*
2709 * Now we've got everything in the final locations, we can
2710 * find optional sections.
2711 */
eb3057df
FH
2712 err = find_module_sections(mod, info);
2713 if (err)
2714 goto free_unload;
9b37ccfc 2715
49668688 2716 err = check_module_license_and_versions(mod);
22e268eb
RR
2717 if (err)
2718 goto free_unload;
9841d61d 2719
c988d2b2 2720 /* Set up MODINFO_ATTR fields */
34e1169d 2721 setup_modinfo(mod, info);
c988d2b2 2722
1da177e4 2723 /* Fix up syms, so that st_value is a pointer to location. */
34e1169d 2724 err = simplify_symbols(mod, info);
1da177e4 2725 if (err < 0)
d913188c 2726 goto free_modinfo;
1da177e4 2727
34e1169d 2728 err = apply_relocations(mod, info);
22e268eb 2729 if (err < 0)
d913188c 2730 goto free_modinfo;
1da177e4 2731
34e1169d 2732 err = post_relocation(mod, info);
1da177e4 2733 if (err < 0)
d913188c 2734 goto free_modinfo;
1da177e4 2735
22e268eb 2736 flush_module_icache(mod);
378bac82 2737
cf68fffb
ST
2738 /* Setup CFI for the module. */
2739 cfi_init(mod);
2740
6526c534
RR
2741 /* Now copy in args */
2742 mod->args = strndup_user(uargs, ~0UL >> 1);
2743 if (IS_ERR(mod->args)) {
2744 err = PTR_ERR(mod->args);
2745 goto free_arch_cleanup;
2746 }
8d3b33f6 2747
9294523e 2748 init_build_id(mod, info);
52796312 2749 dynamic_debug_setup(mod, info->debug, info->num_debug);
ff49d74a 2750
a949ae56
SRRH
2751 /* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
2752 ftrace_module_init(mod);
2753
a3535c7e
RR
2754 /* Finally it's fully formed, ready to start executing. */
2755 err = complete_formation(mod, info);
2756 if (err)
1fb9341a 2757 goto ddebug_cleanup;
be593f4c 2758
4c973d16
JY
2759 err = prepare_coming_module(mod);
2760 if (err)
2761 goto bug_cleanup;
2762
51f3d0f4 2763 /* Module is ready to execute: parsing args may do that. */
51e158c1 2764 after_dashes = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
4355efbd 2765 -32768, 32767, mod,
ecc86170 2766 unknown_module_param_cb);
51e158c1
RR
2767 if (IS_ERR(after_dashes)) {
2768 err = PTR_ERR(after_dashes);
4c973d16 2769 goto coming_cleanup;
51e158c1
RR
2770 } else if (after_dashes) {
2771 pr_warn("%s: parameters '%s' after `--' ignored\n",
2772 mod->name, after_dashes);
2773 }
1da177e4 2774
ca86cad7 2775 /* Link in to sysfs. */
34e1169d 2776 err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
1da177e4 2777 if (err < 0)
4c973d16 2778 goto coming_cleanup;
80a3d1bb 2779
1ce15ef4
JY
2780 if (is_livepatch_module(mod)) {
2781 err = copy_module_elf(mod, info);
2782 if (err < 0)
2783 goto sysfs_cleanup;
2784 }
2785
48fd1188 2786 /* Get rid of temporary copy. */
b1ae6dc4 2787 free_copy(info, flags);
1da177e4
LT
2788
2789 /* Done! */
51f3d0f4 2790 trace_module_load(mod);
34e1169d
KC
2791
2792 return do_init_module(mod);
1da177e4 2793
1ce15ef4
JY
2794 sysfs_cleanup:
2795 mod_sysfs_teardown(mod);
4c973d16 2796 coming_cleanup:
885a78d4 2797 mod->state = MODULE_STATE_GOING;
a5544880 2798 destroy_params(mod->kp, mod->num_kp);
4c973d16
JY
2799 blocking_notifier_call_chain(&module_notify_list,
2800 MODULE_STATE_GOING, mod);
7e545d6e 2801 klp_module_going(mod);
1fb9341a 2802 bug_cleanup:
5e8ed280 2803 mod->state = MODULE_STATE_GOING;
1fb9341a 2804 /* module_bug_cleanup needs module_mutex protection */
75676500 2805 mutex_lock(&module_mutex);
5336377d 2806 module_bug_cleanup(mod);
ee61abb3 2807 mutex_unlock(&module_mutex);
ff7e0055 2808
a3535c7e 2809 ddebug_cleanup:
1323eac7 2810 ftrace_release_mod(mod);
52796312 2811 dynamic_debug_remove(mod, info->debug);
cb2f5536 2812 synchronize_rcu();
6526c534
RR
2813 kfree(mod->args);
2814 free_arch_cleanup:
cf68fffb 2815 cfi_cleanup(mod);
1da177e4 2816 module_arch_cleanup(mod);
d913188c 2817 free_modinfo:
a263f776 2818 free_modinfo(mod);
22e268eb 2819 free_unload:
1da177e4 2820 module_unload_free(mod);
1fb9341a
RR
2821 unlink_mod:
2822 mutex_lock(&module_mutex);
2823 /* Unlink carefully: kallsyms could be walking list. */
2824 list_del_rcu(&mod->list);
758556bd 2825 mod_tree_remove(mod);
1fb9341a 2826 wake_up_all(&module_wq);
0be964be 2827 /* Wait for RCU-sched synchronizing before releasing mod->list. */
cb2f5536 2828 synchronize_rcu();
1fb9341a 2829 mutex_unlock(&module_mutex);
d913188c 2830 free_module:
35a9393c 2831 /* Free lock-classes; relies on the preceding sync_rcu() */
7523e4dc 2832 lockdep_free_key_range(mod->core_layout.base, mod->core_layout.size);
35a9393c 2833
34e1169d 2834 module_deallocate(mod, info);
d913188c 2835 free_copy:
b1ae6dc4 2836 free_copy(info, flags);
34e1169d 2837 return err;
b99b87f7
PO
2838}
2839
17da2bd9
HC
2840SYSCALL_DEFINE3(init_module, void __user *, umod,
2841 unsigned long, len, const char __user *, uargs)
1da177e4 2842{
34e1169d
KC
2843 int err;
2844 struct load_info info = { };
1da177e4 2845
34e1169d
KC
2846 err = may_init_module();
2847 if (err)
2848 return err;
1da177e4 2849
34e1169d
KC
2850 pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
2851 umod, len, uargs);
1da177e4 2852
34e1169d
KC
2853 err = copy_module_from_user(umod, len, &info);
2854 if (err)
2855 return err;
1da177e4 2856
2f3238ae 2857 return load_module(&info, uargs, 0);
34e1169d 2858}
94462ad3 2859
2f3238ae 2860SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
34e1169d 2861{
34e1169d 2862 struct load_info info = { };
b1ae6dc4
DT
2863 void *buf = NULL;
2864 int len;
a1db7420 2865 int err;
94462ad3 2866
34e1169d
KC
2867 err = may_init_module();
2868 if (err)
2869 return err;
1da177e4 2870
2f3238ae 2871 pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
6c5db22d 2872
2f3238ae 2873 if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
b1ae6dc4
DT
2874 |MODULE_INIT_IGNORE_VERMAGIC
2875 |MODULE_INIT_COMPRESSED_FILE))
2f3238ae 2876 return -EINVAL;
d6de2c80 2877
b1ae6dc4 2878 len = kernel_read_file_from_fd(fd, 0, &buf, INT_MAX, NULL,
a1db7420 2879 READING_MODULE);
b1ae6dc4
DT
2880 if (len < 0)
2881 return len;
2882
2883 if (flags & MODULE_INIT_COMPRESSED_FILE) {
2884 err = module_decompress(&info, buf, len);
2885 vfree(buf); /* compressed data is no longer needed */
2886 if (err)
2887 return err;
2888 } else {
2889 info.hdr = buf;
2890 info.len = len;
2891 }
1da177e4 2892
2f3238ae 2893 return load_module(&info, uargs, flags);
1da177e4
LT
2894}
2895
2896static inline int within(unsigned long addr, void *start, unsigned long size)
2897{
2898 return ((void *)addr >= start && (void *)addr < start + size);
2899}
2900
cf68fffb
ST
2901static void cfi_init(struct module *mod)
2902{
2903#ifdef CONFIG_CFI_CLANG
2904 initcall_t *init;
2905 exitcall_t *exit;
2906
2907 rcu_read_lock_sched();
2908 mod->cfi_check = (cfi_check_fn)
2909 find_kallsyms_symbol_value(mod, "__cfi_check");
2910 init = (initcall_t *)
2911 find_kallsyms_symbol_value(mod, "__cfi_jt_init_module");
2912 exit = (exitcall_t *)
2913 find_kallsyms_symbol_value(mod, "__cfi_jt_cleanup_module");
2914 rcu_read_unlock_sched();
2915
2916 /* Fix init/exit functions to point to the CFI jump table */
2917 if (init)
2918 mod->init = *init;
0d67e332 2919#ifdef CONFIG_MODULE_UNLOAD
cf68fffb
ST
2920 if (exit)
2921 mod->exit = *exit;
0d67e332 2922#endif
cf68fffb
ST
2923
2924 cfi_module_add(mod, module_addr_min);
2925#endif
2926}
2927
2928static void cfi_cleanup(struct module *mod)
2929{
2930#ifdef CONFIG_CFI_CLANG
2931 cfi_module_remove(mod, module_addr_min);
2932#endif
2933}
2934
7fd8329b 2935/* Keep in sync with MODULE_FLAGS_BUF_SIZE !!! */
0ffc40f6 2936char *module_flags(struct module *mod, char *buf)
fa3ba2e8
FM
2937{
2938 int bx = 0;
2939
0d21b0e3 2940 BUG_ON(mod->state == MODULE_STATE_UNFORMED);
21aa9280
AV
2941 if (mod->taints ||
2942 mod->state == MODULE_STATE_GOING ||
2943 mod->state == MODULE_STATE_COMING) {
fa3ba2e8 2944 buf[bx++] = '(';
cca3e707 2945 bx += module_flags_taint(mod, buf + bx);
21aa9280
AV
2946 /* Show a - for module-is-being-unloaded */
2947 if (mod->state == MODULE_STATE_GOING)
2948 buf[bx++] = '-';
2949 /* Show a + for module-is-being-loaded */
2950 if (mod->state == MODULE_STATE_COMING)
2951 buf[bx++] = '+';
fa3ba2e8
FM
2952 buf[bx++] = ')';
2953 }
2954 buf[bx] = '\0';
2955
2956 return buf;
2957}
2958
1da177e4
LT
2959/* Given an address, look for it in the module exception tables. */
2960const struct exception_table_entry *search_module_extables(unsigned long addr)
2961{
1da177e4
LT
2962 const struct exception_table_entry *e = NULL;
2963 struct module *mod;
2964
24da1cbf 2965 preempt_disable();
5ff22646
PZ
2966 mod = __module_address(addr);
2967 if (!mod)
2968 goto out;
22a8bdeb 2969
5ff22646
PZ
2970 if (!mod->num_exentries)
2971 goto out;
2972
2973 e = search_extable(mod->extable,
a94c33dd 2974 mod->num_exentries,
5ff22646
PZ
2975 addr);
2976out:
24da1cbf 2977 preempt_enable();
1da177e4 2978
5ff22646
PZ
2979 /*
2980 * Now, if we found one, we are running inside it now, hence
2981 * we cannot unload the module, hence no refcnt needed.
2982 */
1da177e4
LT
2983 return e;
2984}
2985
2541743e
SS
2986/**
2987 * is_module_address() - is this address inside a module?
e610499e
RR
2988 * @addr: the address to check.
2989 *
2990 * See is_module_text_address() if you simply want to see if the address
2991 * is code (not data).
4d435f9d 2992 */
e610499e 2993bool is_module_address(unsigned long addr)
4d435f9d 2994{
e610499e 2995 bool ret;
4d435f9d 2996
24da1cbf 2997 preempt_disable();
e610499e 2998 ret = __module_address(addr) != NULL;
24da1cbf 2999 preempt_enable();
4d435f9d 3000
e610499e 3001 return ret;
4d435f9d
IM
3002}
3003
2541743e
SS
3004/**
3005 * __module_address() - get the module which contains an address.
e610499e
RR
3006 * @addr: the address.
3007 *
3008 * Must be called with preempt disabled or module mutex held so that
3009 * module doesn't get freed during this.
3010 */
714f83d5 3011struct module *__module_address(unsigned long addr)
1da177e4
LT
3012{
3013 struct module *mod;
3014
3a642e99
RR
3015 if (addr < module_addr_min || addr > module_addr_max)
3016 return NULL;
3017
0be964be
PZ
3018 module_assert_mutex_or_preempt();
3019
6c9692e2 3020 mod = mod_find(addr);
93c2e105
PZ
3021 if (mod) {
3022 BUG_ON(!within_module(addr, mod));
0d21b0e3 3023 if (mod->state == MODULE_STATE_UNFORMED)
93c2e105 3024 mod = NULL;
0d21b0e3 3025 }
93c2e105 3026 return mod;
1da177e4
LT
3027}
3028
2541743e
SS
3029/**
3030 * is_module_text_address() - is this address inside module code?
e610499e
RR
3031 * @addr: the address to check.
3032 *
3033 * See is_module_address() if you simply want to see if the address is
3034 * anywhere in a module. See kernel_text_address() for testing if an
3035 * address corresponds to kernel or module code.
3036 */
3037bool is_module_text_address(unsigned long addr)
3038{
3039 bool ret;
3040
3041 preempt_disable();
3042 ret = __module_text_address(addr) != NULL;
3043 preempt_enable();
3044
3045 return ret;
3046}
3047
2541743e
SS
3048/**
3049 * __module_text_address() - get the module whose code contains an address.
e610499e
RR
3050 * @addr: the address.
3051 *
3052 * Must be called with preempt disabled or module mutex held so that
3053 * module doesn't get freed during this.
3054 */
3055struct module *__module_text_address(unsigned long addr)
3056{
3057 struct module *mod = __module_address(addr);
3058 if (mod) {
3059 /* Make sure it's within the text section. */
7523e4dc
RR
3060 if (!within(addr, mod->init_layout.base, mod->init_layout.text_size)
3061 && !within(addr, mod->core_layout.base, mod->core_layout.text_size))
e610499e
RR
3062 mod = NULL;
3063 }
3064 return mod;
3065}
3066
1da177e4
LT
3067/* Don't grab lock, we're oopsing. */
3068void print_modules(void)
3069{
3070 struct module *mod;
7fd8329b 3071 char buf[MODULE_FLAGS_BUF_SIZE];
1da177e4 3072
b231125a 3073 printk(KERN_DEFAULT "Modules linked in:");
d72b3751
AK
3074 /* Most callers should already have preempt disabled, but make sure */
3075 preempt_disable();
0d21b0e3
RR
3076 list_for_each_entry_rcu(mod, &modules, list) {
3077 if (mod->state == MODULE_STATE_UNFORMED)
3078 continue;
27bba4d6 3079 pr_cont(" %s%s", mod->name, module_flags(mod, buf));
0d21b0e3 3080 }
d72b3751 3081 preempt_enable();
e14af7ee 3082 if (last_unloaded_module[0])
27bba4d6
JS
3083 pr_cont(" [last unloaded: %s]", last_unloaded_module);
3084 pr_cont("\n");
1da177e4 3085}