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