1 // SPDX-License-Identifier: GPL-2.0-or-later 2 /* 3 * Copyright (C) 2002 Richard Henderson 4 * Copyright (C) 2001 Rusty Russell, 2002, 2010 Rusty Russell IBM. 5 * Copyright (C) 2023 Luis Chamberlain <mcgrof@kernel.org> 6 */ 7 8 #define INCLUDE_VERMAGIC 9 10 #include <linux/export.h> 11 #include <linux/extable.h> 12 #include <linux/moduleloader.h> 13 #include <linux/module_signature.h> 14 #include <linux/module_symbol.h> 15 #include <linux/trace_events.h> 16 #include <linux/init.h> 17 #include <linux/kallsyms.h> 18 #include <linux/buildid.h> 19 #include <linux/fs.h> 20 #include <linux/kernel.h> 21 #include <linux/kernel_read_file.h> 22 #include <linux/kstrtox.h> 23 #include <linux/slab.h> 24 #include <linux/vmalloc.h> 25 #include <linux/elf.h> 26 #include <linux/seq_file.h> 27 #include <linux/syscalls.h> 28 #include <linux/fcntl.h> 29 #include <linux/rcupdate.h> 30 #include <linux/capability.h> 31 #include <linux/cpu.h> 32 #include <linux/moduleparam.h> 33 #include <linux/errno.h> 34 #include <linux/err.h> 35 #include <linux/vermagic.h> 36 #include <linux/notifier.h> 37 #include <linux/sched.h> 38 #include <linux/device.h> 39 #include <linux/string.h> 40 #include <linux/mutex.h> 41 #include <linux/rculist.h> 42 #include <linux/uaccess.h> 43 #include <asm/cacheflush.h> 44 #include <linux/set_memory.h> 45 #include <asm/mmu_context.h> 46 #include <linux/license.h> 47 #include <asm/sections.h> 48 #include <linux/tracepoint.h> 49 #include <linux/ftrace.h> 50 #include <linux/livepatch.h> 51 #include <linux/async.h> 52 #include <linux/percpu.h> 53 #include <linux/kmemleak.h> 54 #include <linux/jump_label.h> 55 #include <linux/pfn.h> 56 #include <linux/bsearch.h> 57 #include <linux/dynamic_debug.h> 58 #include <linux/audit.h> 59 #include <linux/cfi.h> 60 #include <linux/codetag.h> 61 #include <linux/debugfs.h> 62 #include <linux/execmem.h> 63 #include <uapi/linux/module.h> 64 #include "internal.h" 65 66 #define CREATE_TRACE_POINTS 67 #include <trace/events/module.h> 68 69 /* 70 * Mutex protects: 71 * 1) List of modules (also safely readable within RCU read section), 72 * 2) module_use links, 73 * 3) mod_tree.addr_min/mod_tree.addr_max. 74 * (delete and add uses RCU list operations). 75 */ 76 DEFINE_MUTEX(module_mutex); 77 LIST_HEAD(modules); 78 79 /* Work queue for freeing init sections in success case */ 80 static void do_free_init(struct work_struct *w); 81 static DECLARE_WORK(init_free_wq, do_free_init); 82 static LLIST_HEAD(init_free_list); 83 84 struct mod_tree_root mod_tree __cacheline_aligned = { 85 .addr_min = -1UL, 86 }; 87 88 struct symsearch { 89 const struct kernel_symbol *start, *stop; 90 const u32 *crcs; 91 const u8 *flagstab; 92 }; 93 94 /* 95 * Bounds of module memory, for speeding up __module_address. 96 * Protected by module_mutex. 97 */ 98 static void __mod_update_bounds(enum mod_mem_type type __maybe_unused, void *base, 99 unsigned int size, struct mod_tree_root *tree) 100 { 101 unsigned long min = (unsigned long)base; 102 unsigned long max = min + size; 103 104 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC 105 if (mod_mem_type_is_core_data(type)) { 106 if (min < tree->data_addr_min) 107 tree->data_addr_min = min; 108 if (max > tree->data_addr_max) 109 tree->data_addr_max = max; 110 return; 111 } 112 #endif 113 if (min < tree->addr_min) 114 tree->addr_min = min; 115 if (max > tree->addr_max) 116 tree->addr_max = max; 117 } 118 119 static void mod_update_bounds(struct module *mod) 120 { 121 for_each_mod_mem_type(type) { 122 struct module_memory *mod_mem = &mod->mem[type]; 123 124 if (mod_mem->size) 125 __mod_update_bounds(type, mod_mem->base, mod_mem->size, &mod_tree); 126 } 127 } 128 129 /* Block module loading/unloading? */ 130 static int modules_disabled; 131 core_param(nomodule, modules_disabled, bint, 0); 132 133 static const struct ctl_table module_sysctl_table[] = { 134 { 135 .procname = "modprobe", 136 .data = &modprobe_path, 137 .maxlen = KMOD_PATH_LEN, 138 .mode = 0644, 139 .proc_handler = proc_dostring, 140 }, 141 { 142 .procname = "modules_disabled", 143 .data = &modules_disabled, 144 .maxlen = sizeof(int), 145 .mode = 0644, 146 /* only handle a transition from default "0" to "1" */ 147 .proc_handler = proc_dointvec_minmax, 148 .extra1 = SYSCTL_ONE, 149 .extra2 = SYSCTL_ONE, 150 }, 151 }; 152 153 static int __init init_module_sysctl(void) 154 { 155 register_sysctl_init("kernel", module_sysctl_table); 156 return 0; 157 } 158 159 subsys_initcall(init_module_sysctl); 160 161 /* Waiting for a module to finish initializing? */ 162 static DECLARE_WAIT_QUEUE_HEAD(module_wq); 163 164 static BLOCKING_NOTIFIER_HEAD(module_notify_list); 165 166 int register_module_notifier(struct notifier_block *nb) 167 { 168 return blocking_notifier_chain_register(&module_notify_list, nb); 169 } 170 EXPORT_SYMBOL(register_module_notifier); 171 172 int unregister_module_notifier(struct notifier_block *nb) 173 { 174 return blocking_notifier_chain_unregister(&module_notify_list, nb); 175 } 176 EXPORT_SYMBOL(unregister_module_notifier); 177 178 /* 179 * We require a truly strong try_module_get(): 0 means success. 180 * Otherwise an error is returned due to ongoing or failed 181 * initialization etc. 182 */ 183 static inline int strong_try_module_get(struct module *mod) 184 { 185 BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED); 186 if (mod && mod->state == MODULE_STATE_COMING) 187 return -EBUSY; 188 if (try_module_get(mod)) 189 return 0; 190 else 191 return -ENOENT; 192 } 193 194 /** 195 * add_taint_module: add a taint flag if not already set for a specific module 196 * @mod: pointer to the module that caused the problem 197 * @flag: one of the TAINT_* constants. 198 * @lockdep_ok: whether lock debugging is still OK. 199 * 200 * If something bad has gone wrong, you'll want 201 * @lockdep_ok = LOCKDEP_NOW_UNRELIABLE, but for some 202 * noteworthy-but-not-corrupting cases, it can be set to LOCKDEP_STILL_OK. 203 */ 204 void add_taint_module(struct module *mod, unsigned flag, 205 enum lockdep_ok lockdep_ok) 206 { 207 add_taint(flag, lockdep_ok); 208 if (mod) 209 set_bit(flag, &mod->taints); 210 } 211 212 /* 213 * Like strncmp(), except s/-/_/g as per scripts/Makefile.lib:name-fix-token rule. 214 */ 215 static int mod_strncmp(const char *str_a, const char *str_b, size_t n) 216 { 217 for (int i = 0; i < n; i++) { 218 char a = str_a[i]; 219 char b = str_b[i]; 220 int d; 221 222 if (a == '-') a = '_'; 223 if (b == '-') b = '_'; 224 225 d = a - b; 226 if (d) 227 return d; 228 229 if (!a) 230 break; 231 } 232 233 return 0; 234 } 235 236 /* 237 * A thread that wants to hold a reference to a module only while it 238 * is running can call this to safely exit. 239 */ 240 void __noreturn __module_put_and_kthread_exit(struct module *mod, long code) 241 { 242 module_put(mod); 243 kthread_exit(code); 244 } 245 EXPORT_SYMBOL(__module_put_and_kthread_exit); 246 247 /* Find a module section: 0 means not found. */ 248 static unsigned int find_sec(const struct load_info *info, const char *name) 249 { 250 unsigned int i; 251 252 for (i = 1; i < info->hdr->e_shnum; i++) { 253 Elf_Shdr *shdr = &info->sechdrs[i]; 254 /* Alloc bit cleared means "ignore it." */ 255 if ((shdr->sh_flags & SHF_ALLOC) 256 && strcmp(info->secstrings + shdr->sh_name, name) == 0) 257 return i; 258 } 259 return 0; 260 } 261 262 /** 263 * find_any_unique_sec() - Find a unique section index by name 264 * @info: Load info for the module to scan 265 * @name: Name of the section we're looking for 266 * 267 * Locates a unique section by name. Ignores SHF_ALLOC. 268 * 269 * Return: Section index if found uniquely, zero if absent, negative count 270 * of total instances if multiple were found. 271 */ 272 static int find_any_unique_sec(const struct load_info *info, const char *name) 273 { 274 unsigned int idx; 275 unsigned int count = 0; 276 int i; 277 278 for (i = 1; i < info->hdr->e_shnum; i++) { 279 if (strcmp(info->secstrings + info->sechdrs[i].sh_name, 280 name) == 0) { 281 count++; 282 idx = i; 283 } 284 } 285 if (count == 1) { 286 return idx; 287 } else if (count == 0) { 288 return 0; 289 } else { 290 return -count; 291 } 292 } 293 294 /* Find a module section, or NULL. */ 295 static void *section_addr(const struct load_info *info, const char *name) 296 { 297 /* Section 0 has sh_addr 0. */ 298 return (void *)info->sechdrs[find_sec(info, name)].sh_addr; 299 } 300 301 /* Find a module section, or NULL. Fill in number of "objects" in section. */ 302 static void *section_objs(const struct load_info *info, 303 const char *name, 304 size_t object_size, 305 unsigned int *num) 306 { 307 unsigned int sec = find_sec(info, name); 308 309 /* Section 0 has sh_addr 0 and sh_size 0. */ 310 *num = info->sechdrs[sec].sh_size / object_size; 311 return (void *)info->sechdrs[sec].sh_addr; 312 } 313 314 /* Find a module section: 0 means not found. Ignores SHF_ALLOC flag. */ 315 static unsigned int find_any_sec(const struct load_info *info, const char *name) 316 { 317 unsigned int i; 318 319 for (i = 1; i < info->hdr->e_shnum; i++) { 320 Elf_Shdr *shdr = &info->sechdrs[i]; 321 if (strcmp(info->secstrings + shdr->sh_name, name) == 0) 322 return i; 323 } 324 return 0; 325 } 326 327 /* 328 * Find a module section, or NULL. Fill in number of "objects" in section. 329 * Ignores SHF_ALLOC flag. 330 */ 331 static __maybe_unused void *any_section_objs(const struct load_info *info, 332 const char *name, 333 size_t object_size, 334 unsigned int *num) 335 { 336 unsigned int sec = find_any_sec(info, name); 337 338 /* Section 0 has sh_addr 0 and sh_size 0. */ 339 *num = info->sechdrs[sec].sh_size / object_size; 340 return (void *)info->sechdrs[sec].sh_addr; 341 } 342 343 #ifndef CONFIG_MODVERSIONS 344 #define symversion(base, idx) NULL 345 #else 346 #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL) 347 #endif 348 349 static const char *kernel_symbol_name(const struct kernel_symbol *sym) 350 { 351 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS 352 return offset_to_ptr(&sym->name_offset); 353 #else 354 return sym->name; 355 #endif 356 } 357 358 static const char *kernel_symbol_namespace(const struct kernel_symbol *sym) 359 { 360 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS 361 if (!sym->namespace_offset) 362 return NULL; 363 return offset_to_ptr(&sym->namespace_offset); 364 #else 365 return sym->namespace; 366 #endif 367 } 368 369 int cmp_name(const void *name, const void *sym) 370 { 371 return strcmp(name, kernel_symbol_name(sym)); 372 } 373 374 static bool find_exported_symbol_in_section(const struct symsearch *syms, 375 struct module *owner, 376 struct find_symbol_arg *fsa) 377 { 378 struct kernel_symbol *sym; 379 u8 sym_flags; 380 381 sym = bsearch(fsa->name, syms->start, syms->stop - syms->start, 382 sizeof(struct kernel_symbol), cmp_name); 383 if (!sym) 384 return false; 385 386 sym_flags = *(syms->flagstab + (sym - syms->start)); 387 if (!fsa->gplok && (sym_flags & KSYM_FLAG_GPL_ONLY)) 388 return false; 389 390 fsa->owner = owner; 391 fsa->crc = symversion(syms->crcs, sym - syms->start); 392 fsa->sym = sym; 393 fsa->license = (sym_flags & KSYM_FLAG_GPL_ONLY) ? GPL_ONLY : NOT_GPL_ONLY; 394 395 return true; 396 } 397 398 /* 399 * Find an exported symbol and return it, along with, (optional) crc and 400 * (optional) module which owns it. Needs RCU or module_mutex. 401 */ 402 bool find_symbol(struct find_symbol_arg *fsa) 403 { 404 const struct symsearch syms = { 405 .start = __start___ksymtab, 406 .stop = __stop___ksymtab, 407 .crcs = __start___kcrctab, 408 .flagstab = __start___kflagstab, 409 }; 410 struct module *mod; 411 412 if (find_exported_symbol_in_section(&syms, NULL, fsa)) 413 return true; 414 415 list_for_each_entry_rcu(mod, &modules, list, 416 lockdep_is_held(&module_mutex)) { 417 const struct symsearch syms = { 418 .start = mod->syms, 419 .stop = mod->syms + mod->num_syms, 420 .crcs = mod->crcs, 421 .flagstab = mod->flagstab, 422 }; 423 424 if (mod->state == MODULE_STATE_UNFORMED) 425 continue; 426 427 if (find_exported_symbol_in_section(&syms, mod, fsa)) 428 return true; 429 } 430 431 pr_debug("Failed to find symbol %s\n", fsa->name); 432 return false; 433 } 434 435 /* 436 * Search for module by name: must hold module_mutex (or RCU for read-only 437 * access). 438 */ 439 struct module *find_module_all(const char *name, size_t len, 440 bool even_unformed) 441 { 442 struct module *mod; 443 444 list_for_each_entry_rcu(mod, &modules, list, 445 lockdep_is_held(&module_mutex)) { 446 if (!even_unformed && mod->state == MODULE_STATE_UNFORMED) 447 continue; 448 if (strlen(mod->name) == len && !memcmp(mod->name, name, len)) 449 return mod; 450 } 451 return NULL; 452 } 453 454 struct module *find_module(const char *name) 455 { 456 return find_module_all(name, strlen(name), false); 457 } 458 459 #ifdef CONFIG_SMP 460 461 static inline void __percpu *mod_percpu(struct module *mod) 462 { 463 return mod->percpu; 464 } 465 466 static int percpu_modalloc(struct module *mod, struct load_info *info) 467 { 468 Elf_Shdr *pcpusec = &info->sechdrs[info->index.pcpu]; 469 unsigned long align = pcpusec->sh_addralign; 470 471 if (!pcpusec->sh_size) 472 return 0; 473 474 if (align > PAGE_SIZE) { 475 pr_warn("%s: per-cpu alignment %li > %li\n", 476 mod->name, align, PAGE_SIZE); 477 align = PAGE_SIZE; 478 } 479 480 mod->percpu = __alloc_reserved_percpu(pcpusec->sh_size, align); 481 if (!mod->percpu) { 482 pr_warn("%s: Could not allocate %lu bytes percpu data\n", 483 mod->name, (unsigned long)pcpusec->sh_size); 484 return -ENOMEM; 485 } 486 mod->percpu_size = pcpusec->sh_size; 487 return 0; 488 } 489 490 static void percpu_modfree(struct module *mod) 491 { 492 free_percpu(mod->percpu); 493 } 494 495 static unsigned int find_pcpusec(struct load_info *info) 496 { 497 return find_sec(info, ".data..percpu"); 498 } 499 500 static void percpu_modcopy(struct module *mod, 501 const void *from, unsigned long size) 502 { 503 int cpu; 504 505 for_each_possible_cpu(cpu) 506 memcpy(per_cpu_ptr(mod->percpu, cpu), from, size); 507 } 508 509 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr) 510 { 511 struct module *mod; 512 unsigned int cpu; 513 514 guard(rcu)(); 515 list_for_each_entry_rcu(mod, &modules, list) { 516 if (mod->state == MODULE_STATE_UNFORMED) 517 continue; 518 if (!mod->percpu_size) 519 continue; 520 for_each_possible_cpu(cpu) { 521 void *start = per_cpu_ptr(mod->percpu, cpu); 522 void *va = (void *)addr; 523 524 if (va >= start && va < start + mod->percpu_size) { 525 if (can_addr) { 526 *can_addr = (unsigned long) (va - start); 527 *can_addr += (unsigned long) 528 per_cpu_ptr(mod->percpu, 529 get_boot_cpu_id()); 530 } 531 return true; 532 } 533 } 534 } 535 return false; 536 } 537 538 /** 539 * is_module_percpu_address() - test whether address is from module static percpu 540 * @addr: address to test 541 * 542 * Test whether @addr belongs to module static percpu area. 543 * 544 * Return: %true if @addr is from module static percpu area 545 */ 546 bool is_module_percpu_address(unsigned long addr) 547 { 548 return __is_module_percpu_address(addr, NULL); 549 } 550 551 #else /* ... !CONFIG_SMP */ 552 553 static inline void __percpu *mod_percpu(struct module *mod) 554 { 555 return NULL; 556 } 557 static int percpu_modalloc(struct module *mod, struct load_info *info) 558 { 559 /* UP modules shouldn't have this section: ENOMEM isn't quite right */ 560 if (info->sechdrs[info->index.pcpu].sh_size != 0) 561 return -ENOMEM; 562 return 0; 563 } 564 static inline void percpu_modfree(struct module *mod) 565 { 566 } 567 static unsigned int find_pcpusec(struct load_info *info) 568 { 569 return 0; 570 } 571 static inline void percpu_modcopy(struct module *mod, 572 const void *from, unsigned long size) 573 { 574 /* pcpusec should be 0, and size of that section should be 0. */ 575 BUG_ON(size != 0); 576 } 577 bool is_module_percpu_address(unsigned long addr) 578 { 579 return false; 580 } 581 582 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr) 583 { 584 return false; 585 } 586 587 #endif /* CONFIG_SMP */ 588 589 #define MODINFO_ATTR(field) \ 590 static void setup_modinfo_##field(struct module *mod, const char *s) \ 591 { \ 592 mod->field = kstrdup(s, GFP_KERNEL); \ 593 } \ 594 static ssize_t show_modinfo_##field(const struct module_attribute *mattr, \ 595 struct module_kobject *mk, char *buffer) \ 596 { \ 597 return scnprintf(buffer, PAGE_SIZE, "%s\n", mk->mod->field); \ 598 } \ 599 static int modinfo_##field##_exists(struct module *mod) \ 600 { \ 601 return mod->field != NULL; \ 602 } \ 603 static void free_modinfo_##field(struct module *mod) \ 604 { \ 605 kfree(mod->field); \ 606 mod->field = NULL; \ 607 } \ 608 static const struct module_attribute modinfo_##field = { \ 609 .attr = { .name = __stringify(field), .mode = 0444 }, \ 610 .show = show_modinfo_##field, \ 611 .setup = setup_modinfo_##field, \ 612 .test = modinfo_##field##_exists, \ 613 .free = free_modinfo_##field, \ 614 }; 615 616 MODINFO_ATTR(version); 617 MODINFO_ATTR(srcversion); 618 619 static void setup_modinfo_import_ns(struct module *mod, const char *s) 620 { 621 mod->imported_namespaces = NULL; 622 } 623 624 static ssize_t show_modinfo_import_ns(const struct module_attribute *mattr, 625 struct module_kobject *mk, char *buffer) 626 { 627 return sysfs_emit(buffer, "%s\n", mk->mod->imported_namespaces); 628 } 629 630 static int modinfo_import_ns_exists(struct module *mod) 631 { 632 return mod->imported_namespaces != NULL; 633 } 634 635 static void free_modinfo_import_ns(struct module *mod) 636 { 637 kfree(mod->imported_namespaces); 638 mod->imported_namespaces = NULL; 639 } 640 641 static const struct module_attribute modinfo_import_ns = { 642 .attr = { .name = "import_ns", .mode = 0444 }, 643 .show = show_modinfo_import_ns, 644 .setup = setup_modinfo_import_ns, 645 .test = modinfo_import_ns_exists, 646 .free = free_modinfo_import_ns, 647 }; 648 649 static struct { 650 char name[MODULE_NAME_LEN]; 651 char taints[MODULE_FLAGS_BUF_SIZE]; 652 } last_unloaded_module; 653 654 #ifdef CONFIG_MODULE_UNLOAD 655 656 EXPORT_TRACEPOINT_SYMBOL(module_get); 657 658 /* MODULE_REF_BASE is the base reference count by kmodule loader. */ 659 #define MODULE_REF_BASE 1 660 661 /* Init the unload section of the module. */ 662 static int module_unload_init(struct module *mod) 663 { 664 /* 665 * Initialize reference counter to MODULE_REF_BASE. 666 * refcnt == 0 means module is going. 667 */ 668 atomic_set(&mod->refcnt, MODULE_REF_BASE); 669 670 INIT_LIST_HEAD(&mod->source_list); 671 INIT_LIST_HEAD(&mod->target_list); 672 673 /* Hold reference count during initialization. */ 674 atomic_inc(&mod->refcnt); 675 676 return 0; 677 } 678 679 /* Does a already use b? */ 680 static int already_uses(struct module *a, struct module *b) 681 { 682 struct module_use *use; 683 684 list_for_each_entry(use, &b->source_list, source_list) { 685 if (use->source == a) 686 return 1; 687 } 688 pr_debug("%s does not use %s!\n", a->name, b->name); 689 return 0; 690 } 691 692 /* 693 * Module a uses b 694 * - we add 'a' as a "source", 'b' as a "target" of module use 695 * - the module_use is added to the list of 'b' sources (so 696 * 'b' can walk the list to see who sourced them), and of 'a' 697 * targets (so 'a' can see what modules it targets). 698 */ 699 static int add_module_usage(struct module *a, struct module *b) 700 { 701 struct module_use *use; 702 703 pr_debug("Allocating new usage for %s.\n", a->name); 704 use = kmalloc_obj(*use, GFP_ATOMIC); 705 if (!use) 706 return -ENOMEM; 707 708 use->source = a; 709 use->target = b; 710 list_add(&use->source_list, &b->source_list); 711 list_add(&use->target_list, &a->target_list); 712 return 0; 713 } 714 715 /* Module a uses b: caller needs module_mutex() */ 716 static int ref_module(struct module *a, struct module *b) 717 { 718 int err; 719 720 if (b == NULL || already_uses(a, b)) 721 return 0; 722 723 /* If module isn't available, we fail. */ 724 err = strong_try_module_get(b); 725 if (err) 726 return err; 727 728 err = add_module_usage(a, b); 729 if (err) { 730 module_put(b); 731 return err; 732 } 733 return 0; 734 } 735 736 /* Clear the unload stuff of the module. */ 737 static void module_unload_free(struct module *mod) 738 { 739 struct module_use *use, *tmp; 740 741 mutex_lock(&module_mutex); 742 list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) { 743 struct module *i = use->target; 744 pr_debug("%s unusing %s\n", mod->name, i->name); 745 module_put(i); 746 list_del(&use->source_list); 747 list_del(&use->target_list); 748 kfree(use); 749 } 750 mutex_unlock(&module_mutex); 751 } 752 753 #ifdef CONFIG_MODULE_FORCE_UNLOAD 754 static inline int try_force_unload(unsigned int flags) 755 { 756 int ret = (flags & O_TRUNC); 757 if (ret) 758 add_taint(TAINT_FORCED_RMMOD, LOCKDEP_NOW_UNRELIABLE); 759 return ret; 760 } 761 #else 762 static inline int try_force_unload(unsigned int flags) 763 { 764 return 0; 765 } 766 #endif /* CONFIG_MODULE_FORCE_UNLOAD */ 767 768 /* Try to release refcount of module, 0 means success. */ 769 static int try_release_module_ref(struct module *mod) 770 { 771 int ret; 772 773 /* Try to decrement refcnt which we set at loading */ 774 ret = atomic_sub_return(MODULE_REF_BASE, &mod->refcnt); 775 BUG_ON(ret < 0); 776 if (ret) 777 /* Someone can put this right now, recover with checking */ 778 ret = atomic_add_unless(&mod->refcnt, MODULE_REF_BASE, 0); 779 780 return ret; 781 } 782 783 static int try_stop_module(struct module *mod, int flags, int *forced) 784 { 785 /* If it's not unused, quit unless we're forcing. */ 786 if (try_release_module_ref(mod) != 0) { 787 *forced = try_force_unload(flags); 788 if (!(*forced)) 789 return -EWOULDBLOCK; 790 } 791 792 /* Mark it as dying. */ 793 mod->state = MODULE_STATE_GOING; 794 795 return 0; 796 } 797 798 /** 799 * module_refcount() - return the refcount or -1 if unloading 800 * @mod: the module we're checking 801 * 802 * Return: 803 * -1 if the module is in the process of unloading 804 * otherwise the number of references in the kernel to the module 805 */ 806 int module_refcount(struct module *mod) 807 { 808 return atomic_read(&mod->refcnt) - MODULE_REF_BASE; 809 } 810 EXPORT_SYMBOL(module_refcount); 811 812 /* This exists whether we can unload or not */ 813 static void free_module(struct module *mod); 814 815 SYSCALL_DEFINE2(delete_module, const char __user *, name_user, 816 unsigned int, flags) 817 { 818 struct module *mod; 819 char name[MODULE_NAME_LEN]; 820 char buf[MODULE_FLAGS_BUF_SIZE]; 821 int ret, len, forced = 0; 822 823 if (!capable(CAP_SYS_MODULE) || modules_disabled) 824 return -EPERM; 825 826 len = strncpy_from_user(name, name_user, MODULE_NAME_LEN); 827 if (len == 0 || len == MODULE_NAME_LEN) 828 return -ENOENT; 829 if (len < 0) 830 return len; 831 832 audit_log_kern_module(name); 833 834 if (mutex_lock_interruptible(&module_mutex) != 0) 835 return -EINTR; 836 837 mod = find_module(name); 838 if (!mod) { 839 ret = -ENOENT; 840 goto out; 841 } 842 843 if (!list_empty(&mod->source_list)) { 844 /* Other modules depend on us: get rid of them first. */ 845 ret = -EWOULDBLOCK; 846 goto out; 847 } 848 849 /* Doing init or already dying? */ 850 if (mod->state != MODULE_STATE_LIVE) { 851 /* FIXME: if (force), slam module count damn the torpedoes */ 852 pr_debug("%s already dying\n", mod->name); 853 ret = -EBUSY; 854 goto out; 855 } 856 857 /* If it has an init func, it must have an exit func to unload */ 858 if (mod->init && !mod->exit) { 859 forced = try_force_unload(flags); 860 if (!forced) { 861 /* This module can't be removed */ 862 ret = -EBUSY; 863 goto out; 864 } 865 } 866 867 ret = try_stop_module(mod, flags, &forced); 868 if (ret != 0) 869 goto out; 870 871 mutex_unlock(&module_mutex); 872 /* Final destruction now no one is using it. */ 873 if (mod->exit != NULL) 874 mod->exit(); 875 blocking_notifier_call_chain(&module_notify_list, 876 MODULE_STATE_GOING, mod); 877 klp_module_going(mod); 878 ftrace_release_mod(mod); 879 880 async_synchronize_full(); 881 882 /* Store the name and taints of the last unloaded module for diagnostic purposes */ 883 strscpy(last_unloaded_module.name, mod->name); 884 strscpy(last_unloaded_module.taints, module_flags(mod, buf, false)); 885 886 free_module(mod); 887 /* someone could wait for the module in add_unformed_module() */ 888 wake_up_all(&module_wq); 889 return 0; 890 out: 891 mutex_unlock(&module_mutex); 892 return ret; 893 } 894 895 void __symbol_put(const char *symbol) 896 { 897 struct find_symbol_arg fsa = { 898 .name = symbol, 899 .gplok = true, 900 }; 901 902 guard(rcu)(); 903 BUG_ON(!find_symbol(&fsa)); 904 module_put(fsa.owner); 905 } 906 EXPORT_SYMBOL(__symbol_put); 907 908 /* Note this assumes addr is a function, which it currently always is. */ 909 void symbol_put_addr(void *addr) 910 { 911 struct module *modaddr; 912 unsigned long a = (unsigned long)dereference_function_descriptor(addr); 913 914 if (core_kernel_text(a)) 915 return; 916 917 /* 918 * Even though we hold a reference on the module; we still need to 919 * RCU read section in order to safely traverse the data structure. 920 */ 921 guard(rcu)(); 922 modaddr = __module_text_address(a); 923 BUG_ON(!modaddr); 924 module_put(modaddr); 925 } 926 EXPORT_SYMBOL_GPL(symbol_put_addr); 927 928 static ssize_t show_refcnt(const struct module_attribute *mattr, 929 struct module_kobject *mk, char *buffer) 930 { 931 return sprintf(buffer, "%i\n", module_refcount(mk->mod)); 932 } 933 934 static const struct module_attribute modinfo_refcnt = 935 __ATTR(refcnt, 0444, show_refcnt, NULL); 936 937 void __module_get(struct module *module) 938 { 939 if (module) { 940 atomic_inc(&module->refcnt); 941 trace_module_get(module, _RET_IP_); 942 } 943 } 944 EXPORT_SYMBOL(__module_get); 945 946 bool try_module_get(struct module *module) 947 { 948 bool ret = true; 949 950 if (module) { 951 /* Note: here, we can fail to get a reference */ 952 if (likely(module_is_live(module) && 953 atomic_inc_not_zero(&module->refcnt) != 0)) 954 trace_module_get(module, _RET_IP_); 955 else 956 ret = false; 957 } 958 return ret; 959 } 960 EXPORT_SYMBOL(try_module_get); 961 962 void module_put(struct module *module) 963 { 964 int ret; 965 966 if (module) { 967 ret = atomic_dec_if_positive(&module->refcnt); 968 WARN_ON(ret < 0); /* Failed to put refcount */ 969 trace_module_put(module, _RET_IP_); 970 } 971 } 972 EXPORT_SYMBOL(module_put); 973 974 #else /* !CONFIG_MODULE_UNLOAD */ 975 static inline void module_unload_free(struct module *mod) 976 { 977 } 978 979 static int ref_module(struct module *a, struct module *b) 980 { 981 return strong_try_module_get(b); 982 } 983 984 static inline int module_unload_init(struct module *mod) 985 { 986 return 0; 987 } 988 #endif /* CONFIG_MODULE_UNLOAD */ 989 990 size_t module_flags_taint(unsigned long taints, char *buf) 991 { 992 size_t l = 0; 993 int i; 994 995 for (i = 0; i < TAINT_FLAGS_COUNT; i++) { 996 if (test_bit(i, &taints)) 997 buf[l++] = taint_flags[i].c_true; 998 } 999 1000 return l; 1001 } 1002 1003 static ssize_t show_initstate(const struct module_attribute *mattr, 1004 struct module_kobject *mk, char *buffer) 1005 { 1006 const char *state = "unknown"; 1007 1008 switch (mk->mod->state) { 1009 case MODULE_STATE_LIVE: 1010 state = "live"; 1011 break; 1012 case MODULE_STATE_COMING: 1013 state = "coming"; 1014 break; 1015 case MODULE_STATE_GOING: 1016 state = "going"; 1017 break; 1018 default: 1019 BUG(); 1020 } 1021 return sprintf(buffer, "%s\n", state); 1022 } 1023 1024 static const struct module_attribute modinfo_initstate = 1025 __ATTR(initstate, 0444, show_initstate, NULL); 1026 1027 static ssize_t store_uevent(const struct module_attribute *mattr, 1028 struct module_kobject *mk, 1029 const char *buffer, size_t count) 1030 { 1031 int rc; 1032 1033 rc = kobject_synth_uevent(&mk->kobj, buffer, count); 1034 return rc ? rc : count; 1035 } 1036 1037 const struct module_attribute module_uevent = 1038 __ATTR(uevent, 0200, NULL, store_uevent); 1039 1040 static ssize_t show_coresize(const struct module_attribute *mattr, 1041 struct module_kobject *mk, char *buffer) 1042 { 1043 unsigned int size = mk->mod->mem[MOD_TEXT].size; 1044 1045 if (!IS_ENABLED(CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC)) { 1046 for_class_mod_mem_type(type, core_data) 1047 size += mk->mod->mem[type].size; 1048 } 1049 return sprintf(buffer, "%u\n", size); 1050 } 1051 1052 static const struct module_attribute modinfo_coresize = 1053 __ATTR(coresize, 0444, show_coresize, NULL); 1054 1055 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC 1056 static ssize_t show_datasize(const struct module_attribute *mattr, 1057 struct module_kobject *mk, char *buffer) 1058 { 1059 unsigned int size = 0; 1060 1061 for_class_mod_mem_type(type, core_data) 1062 size += mk->mod->mem[type].size; 1063 return sprintf(buffer, "%u\n", size); 1064 } 1065 1066 static const struct module_attribute modinfo_datasize = 1067 __ATTR(datasize, 0444, show_datasize, NULL); 1068 #endif 1069 1070 static ssize_t show_initsize(const struct module_attribute *mattr, 1071 struct module_kobject *mk, char *buffer) 1072 { 1073 unsigned int size = 0; 1074 1075 for_class_mod_mem_type(type, init) 1076 size += mk->mod->mem[type].size; 1077 return sprintf(buffer, "%u\n", size); 1078 } 1079 1080 static const struct module_attribute modinfo_initsize = 1081 __ATTR(initsize, 0444, show_initsize, NULL); 1082 1083 static ssize_t show_taint(const struct module_attribute *mattr, 1084 struct module_kobject *mk, char *buffer) 1085 { 1086 size_t l; 1087 1088 l = module_flags_taint(mk->mod->taints, buffer); 1089 buffer[l++] = '\n'; 1090 return l; 1091 } 1092 1093 static const struct module_attribute modinfo_taint = 1094 __ATTR(taint, 0444, show_taint, NULL); 1095 1096 const struct module_attribute *const modinfo_attrs[] = { 1097 &module_uevent, 1098 &modinfo_version, 1099 &modinfo_srcversion, 1100 &modinfo_import_ns, 1101 &modinfo_initstate, 1102 &modinfo_coresize, 1103 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC 1104 &modinfo_datasize, 1105 #endif 1106 &modinfo_initsize, 1107 &modinfo_taint, 1108 #ifdef CONFIG_MODULE_UNLOAD 1109 &modinfo_refcnt, 1110 #endif 1111 NULL, 1112 }; 1113 1114 const size_t modinfo_attrs_count = ARRAY_SIZE(modinfo_attrs); 1115 1116 static const char vermagic[] = VERMAGIC_STRING; 1117 1118 int try_to_force_load(struct module *mod, const char *reason) 1119 { 1120 #ifdef CONFIG_MODULE_FORCE_LOAD 1121 if (!test_taint(TAINT_FORCED_MODULE)) 1122 pr_warn("%s: %s: kernel tainted.\n", mod->name, reason); 1123 add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE); 1124 return 0; 1125 #else 1126 return -ENOEXEC; 1127 #endif 1128 } 1129 1130 /* Parse tag=value strings from .modinfo section */ 1131 char *module_next_tag_pair(char *string, unsigned long *secsize) 1132 { 1133 /* Skip non-zero chars */ 1134 while (string[0]) { 1135 string++; 1136 if ((*secsize)-- <= 1) 1137 return NULL; 1138 } 1139 1140 /* Skip any zero padding. */ 1141 while (!string[0]) { 1142 string++; 1143 if ((*secsize)-- <= 1) 1144 return NULL; 1145 } 1146 return string; 1147 } 1148 1149 static char *get_next_modinfo(const struct load_info *info, const char *tag, 1150 char *prev) 1151 { 1152 char *p; 1153 unsigned int taglen = strlen(tag); 1154 Elf_Shdr *infosec = &info->sechdrs[info->index.info]; 1155 unsigned long size = infosec->sh_size; 1156 1157 /* 1158 * get_modinfo() calls made before rewrite_section_headers() 1159 * must use sh_offset, as sh_addr isn't set! 1160 */ 1161 char *modinfo = (char *)info->hdr + infosec->sh_offset; 1162 1163 if (prev) { 1164 size -= prev - modinfo; 1165 modinfo = module_next_tag_pair(prev, &size); 1166 } 1167 1168 for (p = modinfo; p; p = module_next_tag_pair(p, &size)) { 1169 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=') 1170 return p + taglen + 1; 1171 } 1172 return NULL; 1173 } 1174 1175 static char *get_modinfo(const struct load_info *info, const char *tag) 1176 { 1177 return get_next_modinfo(info, tag, NULL); 1178 } 1179 1180 /** 1181 * verify_module_namespace() - does @modname have access to this symbol's @namespace 1182 * @namespace: export symbol namespace 1183 * @modname: module name 1184 * 1185 * If @namespace is prefixed with "module:" to indicate it is a module namespace 1186 * then test if @modname matches any of the comma separated patterns. 1187 * 1188 * The patterns only support tail-glob. 1189 */ 1190 static bool verify_module_namespace(const char *namespace, const char *modname) 1191 { 1192 size_t len, modlen = strlen(modname); 1193 const char *prefix = "module:"; 1194 const char *sep; 1195 bool glob; 1196 1197 if (!strstarts(namespace, prefix)) 1198 return false; 1199 1200 for (namespace += strlen(prefix); *namespace; namespace = sep) { 1201 sep = strchrnul(namespace, ','); 1202 len = sep - namespace; 1203 1204 glob = false; 1205 if (sep[-1] == '*') { 1206 len--; 1207 glob = true; 1208 } 1209 1210 if (*sep) 1211 sep++; 1212 1213 if (mod_strncmp(namespace, modname, len) == 0 && (glob || len == modlen)) 1214 return true; 1215 } 1216 1217 return false; 1218 } 1219 1220 static int verify_namespace_is_imported(const struct load_info *info, 1221 const struct kernel_symbol *sym, 1222 struct module *mod) 1223 { 1224 const char *namespace; 1225 char *imported_namespace; 1226 1227 namespace = kernel_symbol_namespace(sym); 1228 if (namespace && namespace[0]) { 1229 1230 if (verify_module_namespace(namespace, mod->name)) 1231 return 0; 1232 1233 for_each_modinfo_entry(imported_namespace, info, "import_ns") { 1234 if (strcmp(namespace, imported_namespace) == 0) 1235 return 0; 1236 } 1237 #ifdef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS 1238 pr_warn( 1239 #else 1240 pr_err( 1241 #endif 1242 "%s: module uses symbol (%s) from namespace %s, but does not import it.\n", 1243 mod->name, kernel_symbol_name(sym), namespace); 1244 #ifndef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS 1245 return -EINVAL; 1246 #endif 1247 } 1248 return 0; 1249 } 1250 1251 static bool inherit_taint(struct module *mod, struct module *owner, const char *name) 1252 { 1253 if (!owner || !test_bit(TAINT_PROPRIETARY_MODULE, &owner->taints)) 1254 return true; 1255 1256 if (mod->using_gplonly_symbols) { 1257 pr_err("%s: module using GPL-only symbols uses symbols %s from proprietary module %s.\n", 1258 mod->name, name, owner->name); 1259 return false; 1260 } 1261 1262 if (!test_bit(TAINT_PROPRIETARY_MODULE, &mod->taints)) { 1263 pr_warn("%s: module uses symbols %s from proprietary module %s, inheriting taint.\n", 1264 mod->name, name, owner->name); 1265 set_bit(TAINT_PROPRIETARY_MODULE, &mod->taints); 1266 } 1267 return true; 1268 } 1269 1270 /* Resolve a symbol for this module. I.e. if we find one, record usage. */ 1271 static const struct kernel_symbol *resolve_symbol(struct module *mod, 1272 const struct load_info *info, 1273 const char *name, 1274 char ownername[]) 1275 { 1276 struct find_symbol_arg fsa = { 1277 .name = name, 1278 .gplok = !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)), 1279 .warn = true, 1280 }; 1281 int err; 1282 1283 /* 1284 * The module_mutex should not be a heavily contended lock; 1285 * if we get the occasional sleep here, we'll go an extra iteration 1286 * in the wait_event_interruptible(), which is harmless. 1287 */ 1288 sched_annotate_sleep(); 1289 mutex_lock(&module_mutex); 1290 if (!find_symbol(&fsa)) 1291 goto unlock; 1292 1293 if (fsa.license == GPL_ONLY) 1294 mod->using_gplonly_symbols = true; 1295 1296 if (!inherit_taint(mod, fsa.owner, name)) { 1297 fsa.sym = NULL; 1298 goto getname; 1299 } 1300 1301 if (!check_version(info, name, mod, fsa.crc)) { 1302 fsa.sym = ERR_PTR(-EINVAL); 1303 goto getname; 1304 } 1305 1306 err = verify_namespace_is_imported(info, fsa.sym, mod); 1307 if (err) { 1308 fsa.sym = ERR_PTR(err); 1309 goto getname; 1310 } 1311 1312 err = ref_module(mod, fsa.owner); 1313 if (err) { 1314 fsa.sym = ERR_PTR(err); 1315 goto getname; 1316 } 1317 1318 getname: 1319 /* We must make copy under the lock if we failed to get ref. */ 1320 strscpy(ownername, module_name(fsa.owner), MODULE_NAME_LEN); 1321 unlock: 1322 mutex_unlock(&module_mutex); 1323 return fsa.sym; 1324 } 1325 1326 static const struct kernel_symbol * 1327 resolve_symbol_wait(struct module *mod, 1328 const struct load_info *info, 1329 const char *name) 1330 { 1331 const struct kernel_symbol *ksym; 1332 char owner[MODULE_NAME_LEN]; 1333 1334 if (wait_event_interruptible_timeout(module_wq, 1335 !IS_ERR(ksym = resolve_symbol(mod, info, name, owner)) 1336 || PTR_ERR(ksym) != -EBUSY, 1337 30 * HZ) <= 0) { 1338 pr_warn("%s: gave up waiting for init of module %s.\n", 1339 mod->name, owner); 1340 } 1341 return ksym; 1342 } 1343 1344 void __weak module_arch_cleanup(struct module *mod) 1345 { 1346 } 1347 1348 void __weak module_arch_freeing_init(struct module *mod) 1349 { 1350 } 1351 1352 static int module_memory_alloc(struct module *mod, enum mod_mem_type type) 1353 { 1354 unsigned int size = PAGE_ALIGN(mod->mem[type].size); 1355 enum execmem_type execmem_type; 1356 void *ptr; 1357 1358 mod->mem[type].size = size; 1359 1360 if (mod_mem_type_is_data(type)) 1361 execmem_type = EXECMEM_MODULE_DATA; 1362 else 1363 execmem_type = EXECMEM_MODULE_TEXT; 1364 1365 ptr = execmem_alloc_rw(execmem_type, size); 1366 if (!ptr) 1367 return -ENOMEM; 1368 1369 mod->mem[type].is_rox = execmem_is_rox(execmem_type); 1370 1371 /* 1372 * The pointer to these blocks of memory are stored on the module 1373 * structure and we keep that around so long as the module is 1374 * around. We only free that memory when we unload the module. 1375 * Just mark them as not being a leak then. The .init* ELF 1376 * sections *do* get freed after boot so we *could* treat them 1377 * slightly differently with kmemleak_ignore() and only grey 1378 * them out as they work as typical memory allocations which 1379 * *do* eventually get freed, but let's just keep things simple 1380 * and avoid *any* false positives. 1381 */ 1382 if (!mod->mem[type].is_rox) 1383 kmemleak_not_leak(ptr); 1384 1385 memset(ptr, 0, size); 1386 mod->mem[type].base = ptr; 1387 1388 return 0; 1389 } 1390 1391 static void module_memory_restore_rox(struct module *mod) 1392 { 1393 for_class_mod_mem_type(type, text) { 1394 struct module_memory *mem = &mod->mem[type]; 1395 1396 if (mem->is_rox) 1397 execmem_restore_rox(mem->base, mem->size); 1398 } 1399 } 1400 1401 static void module_memory_free(struct module *mod, enum mod_mem_type type) 1402 { 1403 struct module_memory *mem = &mod->mem[type]; 1404 1405 execmem_free(mem->base); 1406 } 1407 1408 static void free_mod_mem(struct module *mod) 1409 { 1410 for_each_mod_mem_type(type) { 1411 struct module_memory *mod_mem = &mod->mem[type]; 1412 1413 if (type == MOD_DATA) 1414 continue; 1415 1416 /* Free lock-classes; relies on the preceding sync_rcu(). */ 1417 lockdep_free_key_range(mod_mem->base, mod_mem->size); 1418 if (mod_mem->size) 1419 module_memory_free(mod, type); 1420 } 1421 1422 /* MOD_DATA hosts mod, so free it at last */ 1423 lockdep_free_key_range(mod->mem[MOD_DATA].base, mod->mem[MOD_DATA].size); 1424 module_memory_free(mod, MOD_DATA); 1425 } 1426 1427 /* Free a module, remove from lists, etc. */ 1428 static void free_module(struct module *mod) 1429 { 1430 trace_module_free(mod); 1431 1432 codetag_unload_module(mod); 1433 1434 mod_sysfs_teardown(mod); 1435 1436 /* 1437 * We leave it in list to prevent duplicate loads, but make sure 1438 * that noone uses it while it's being deconstructed. 1439 */ 1440 mutex_lock(&module_mutex); 1441 mod->state = MODULE_STATE_UNFORMED; 1442 mutex_unlock(&module_mutex); 1443 1444 /* Arch-specific cleanup. */ 1445 module_arch_cleanup(mod); 1446 1447 /* Module unload stuff */ 1448 module_unload_free(mod); 1449 1450 /* Free any allocated parameters. */ 1451 module_destroy_params(mod->kp, mod->num_kp); 1452 1453 if (is_livepatch_module(mod)) 1454 free_module_elf(mod); 1455 1456 /* Now we can delete it from the lists */ 1457 mutex_lock(&module_mutex); 1458 /* Unlink carefully: kallsyms could be walking list. */ 1459 list_del_rcu(&mod->list); 1460 mod_tree_remove(mod); 1461 /* Remove this module from bug list, this uses list_del_rcu */ 1462 module_bug_cleanup(mod); 1463 /* Wait for RCU synchronizing before releasing mod->list and buglist. */ 1464 synchronize_rcu(); 1465 if (try_add_tainted_module(mod)) 1466 pr_err("%s: adding tainted module to the unloaded tainted modules list failed.\n", 1467 mod->name); 1468 mutex_unlock(&module_mutex); 1469 1470 /* This may be empty, but that's OK */ 1471 module_arch_freeing_init(mod); 1472 percpu_modfree(mod); 1473 1474 free_mod_mem(mod); 1475 } 1476 1477 void *__symbol_get(const char *symbol) 1478 { 1479 struct find_symbol_arg fsa = { 1480 .name = symbol, 1481 .gplok = true, 1482 .warn = true, 1483 }; 1484 1485 scoped_guard(rcu) { 1486 if (!find_symbol(&fsa)) 1487 return NULL; 1488 if (fsa.license != GPL_ONLY) { 1489 pr_warn("failing symbol_get of non-GPLONLY symbol %s.\n", 1490 symbol); 1491 return NULL; 1492 } 1493 if (strong_try_module_get(fsa.owner)) 1494 return NULL; 1495 } 1496 return (void *)kernel_symbol_value(fsa.sym); 1497 } 1498 EXPORT_SYMBOL_GPL(__symbol_get); 1499 1500 /* 1501 * Ensure that an exported symbol [global namespace] does not already exist 1502 * in the kernel or in some other module's exported symbol table. 1503 * 1504 * You must hold the module_mutex. 1505 */ 1506 static int verify_exported_symbols(struct module *mod) 1507 { 1508 const struct kernel_symbol *s; 1509 for (s = mod->syms; s < mod->syms + mod->num_syms; s++) { 1510 struct find_symbol_arg fsa = { 1511 .name = kernel_symbol_name(s), 1512 .gplok = true, 1513 }; 1514 if (find_symbol(&fsa)) { 1515 pr_err("%s: exports duplicate symbol %s (owned by %s)\n", 1516 mod->name, kernel_symbol_name(s), 1517 module_name(fsa.owner)); 1518 return -ENOEXEC; 1519 } 1520 } 1521 return 0; 1522 } 1523 1524 static bool ignore_undef_symbol(Elf_Half emachine, const char *name) 1525 { 1526 /* 1527 * On x86, PIC code and Clang non-PIC code may have call foo@PLT. GNU as 1528 * before 2.37 produces an unreferenced _GLOBAL_OFFSET_TABLE_ on x86-64. 1529 * i386 has a similar problem but may not deserve a fix. 1530 * 1531 * If we ever have to ignore many symbols, consider refactoring the code to 1532 * only warn if referenced by a relocation. 1533 */ 1534 if (emachine == EM_386 || emachine == EM_X86_64) 1535 return !strcmp(name, "_GLOBAL_OFFSET_TABLE_"); 1536 return false; 1537 } 1538 1539 /* Change all symbols so that st_value encodes the pointer directly. */ 1540 static int simplify_symbols(struct module *mod, const struct load_info *info) 1541 { 1542 Elf_Shdr *symsec = &info->sechdrs[info->index.sym]; 1543 Elf_Sym *sym = (void *)symsec->sh_addr; 1544 unsigned long secbase; 1545 unsigned int i; 1546 int ret = 0; 1547 const struct kernel_symbol *ksym; 1548 1549 for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) { 1550 const char *name = info->strtab + sym[i].st_name; 1551 1552 switch (sym[i].st_shndx) { 1553 case SHN_COMMON: 1554 /* Ignore common symbols */ 1555 if (!strncmp(name, "__gnu_lto", 9)) 1556 break; 1557 1558 /* 1559 * We compiled with -fno-common. These are not 1560 * supposed to happen. 1561 */ 1562 pr_debug("Common symbol: %s\n", name); 1563 pr_warn("%s: please compile with -fno-common\n", 1564 mod->name); 1565 ret = -ENOEXEC; 1566 break; 1567 1568 case SHN_ABS: 1569 /* Don't need to do anything */ 1570 pr_debug("Absolute symbol: 0x%08lx %s\n", 1571 (long)sym[i].st_value, name); 1572 break; 1573 1574 case SHN_LIVEPATCH: 1575 /* Livepatch symbols are resolved by livepatch */ 1576 break; 1577 1578 case SHN_UNDEF: 1579 ksym = resolve_symbol_wait(mod, info, name); 1580 /* Ok if resolved. */ 1581 if (ksym && !IS_ERR(ksym)) { 1582 sym[i].st_value = kernel_symbol_value(ksym); 1583 break; 1584 } 1585 1586 /* Ok if weak or ignored. */ 1587 if (!ksym && 1588 (ELF_ST_BIND(sym[i].st_info) == STB_WEAK || 1589 ignore_undef_symbol(info->hdr->e_machine, name))) 1590 break; 1591 1592 ret = PTR_ERR(ksym) ?: -ENOENT; 1593 pr_warn("%s: Unknown symbol %s (err %d)\n", 1594 mod->name, name, ret); 1595 break; 1596 1597 default: 1598 if (sym[i].st_shndx >= info->hdr->e_shnum) { 1599 pr_err("%s: Symbol %s has an invalid section index %u (max %u)\n", 1600 mod->name, name, sym[i].st_shndx, info->hdr->e_shnum - 1); 1601 ret = -ENOEXEC; 1602 break; 1603 } 1604 1605 /* Divert to percpu allocation if a percpu var. */ 1606 if (sym[i].st_shndx == info->index.pcpu) 1607 secbase = (unsigned long)mod_percpu(mod); 1608 else 1609 secbase = info->sechdrs[sym[i].st_shndx].sh_addr; 1610 sym[i].st_value += secbase; 1611 break; 1612 } 1613 } 1614 1615 return ret; 1616 } 1617 1618 static int apply_relocations(struct module *mod, const struct load_info *info) 1619 { 1620 unsigned int i; 1621 int err = 0; 1622 1623 /* Now do relocations. */ 1624 for (i = 1; i < info->hdr->e_shnum; i++) { 1625 unsigned int infosec = info->sechdrs[i].sh_info; 1626 1627 /* Not a valid relocation section? */ 1628 if (infosec >= info->hdr->e_shnum) 1629 continue; 1630 1631 /* 1632 * Don't bother with non-allocated sections. 1633 * An exception is the percpu section, which has separate allocations 1634 * for individual CPUs. We relocate the percpu section in the initial 1635 * ELF template and subsequently copy it to the per-CPU destinations. 1636 */ 1637 if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC) && 1638 (!infosec || infosec != info->index.pcpu)) 1639 continue; 1640 1641 if (info->sechdrs[i].sh_flags & SHF_RELA_LIVEPATCH) 1642 err = klp_apply_section_relocs(mod, info->sechdrs, 1643 info->secstrings, 1644 info->strtab, 1645 info->index.sym, i, 1646 NULL); 1647 else if (info->sechdrs[i].sh_type == SHT_REL) 1648 err = apply_relocate(info->sechdrs, info->strtab, 1649 info->index.sym, i, mod); 1650 else if (info->sechdrs[i].sh_type == SHT_RELA) 1651 err = apply_relocate_add(info->sechdrs, info->strtab, 1652 info->index.sym, i, mod); 1653 if (err < 0) 1654 break; 1655 } 1656 return err; 1657 } 1658 1659 /* Additional bytes needed by arch in front of individual sections */ 1660 unsigned int __weak arch_mod_section_prepend(struct module *mod, 1661 unsigned int section) 1662 { 1663 /* default implementation just returns zero */ 1664 return 0; 1665 } 1666 1667 long module_get_offset_and_type(struct module *mod, enum mod_mem_type type, 1668 Elf_Shdr *sechdr, unsigned int section) 1669 { 1670 long offset; 1671 long mask = ((unsigned long)(type) & SH_ENTSIZE_TYPE_MASK) << SH_ENTSIZE_TYPE_SHIFT; 1672 1673 mod->mem[type].size += arch_mod_section_prepend(mod, section); 1674 offset = ALIGN(mod->mem[type].size, sechdr->sh_addralign ?: 1); 1675 mod->mem[type].size = offset + sechdr->sh_size; 1676 1677 WARN_ON_ONCE(offset & mask); 1678 return offset | mask; 1679 } 1680 1681 bool module_init_layout_section(const char *sname) 1682 { 1683 #ifndef CONFIG_MODULE_UNLOAD 1684 if (module_exit_section(sname)) 1685 return true; 1686 #endif 1687 return module_init_section(sname); 1688 } 1689 1690 static void __layout_sections(struct module *mod, struct load_info *info, bool is_init) 1691 { 1692 unsigned int m, i; 1693 1694 /* 1695 * { Mask of required section header flags, 1696 * Mask of excluded section header flags } 1697 */ 1698 static const unsigned long masks[][2] = { 1699 { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL }, 1700 { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL }, 1701 { SHF_RO_AFTER_INIT | SHF_ALLOC, ARCH_SHF_SMALL }, 1702 { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL }, 1703 { ARCH_SHF_SMALL | SHF_ALLOC, 0 } 1704 }; 1705 static const int core_m_to_mem_type[] = { 1706 MOD_TEXT, 1707 MOD_RODATA, 1708 MOD_RO_AFTER_INIT, 1709 MOD_DATA, 1710 MOD_DATA, 1711 }; 1712 static const int init_m_to_mem_type[] = { 1713 MOD_INIT_TEXT, 1714 MOD_INIT_RODATA, 1715 MOD_INVALID, 1716 MOD_INIT_DATA, 1717 MOD_INIT_DATA, 1718 }; 1719 1720 for (m = 0; m < ARRAY_SIZE(masks); ++m) { 1721 enum mod_mem_type type = is_init ? init_m_to_mem_type[m] : core_m_to_mem_type[m]; 1722 1723 for (i = 0; i < info->hdr->e_shnum; ++i) { 1724 Elf_Shdr *s = &info->sechdrs[i]; 1725 const char *sname = info->secstrings + s->sh_name; 1726 1727 if ((s->sh_flags & masks[m][0]) != masks[m][0] 1728 || (s->sh_flags & masks[m][1]) 1729 || s->sh_entsize != ~0UL 1730 || is_init != module_init_layout_section(sname)) 1731 continue; 1732 1733 if (WARN_ON_ONCE(type == MOD_INVALID)) 1734 continue; 1735 1736 /* 1737 * Do not allocate codetag memory as we load it into 1738 * preallocated contiguous memory. 1739 */ 1740 if (codetag_needs_module_section(mod, sname, s->sh_size)) { 1741 /* 1742 * s->sh_entsize won't be used but populate the 1743 * type field to avoid confusion. 1744 */ 1745 s->sh_entsize = ((unsigned long)(type) & SH_ENTSIZE_TYPE_MASK) 1746 << SH_ENTSIZE_TYPE_SHIFT; 1747 continue; 1748 } 1749 1750 s->sh_entsize = module_get_offset_and_type(mod, type, s, i); 1751 pr_debug("\t%s\n", sname); 1752 } 1753 } 1754 } 1755 1756 /* 1757 * Lay out the SHF_ALLOC sections in a way not dissimilar to how ld 1758 * might -- code, read-only data, read-write data, small data. Tally 1759 * sizes, and place the offsets into sh_entsize fields: high bit means it 1760 * belongs in init. 1761 */ 1762 static void layout_sections(struct module *mod, struct load_info *info) 1763 { 1764 unsigned int i; 1765 1766 for (i = 0; i < info->hdr->e_shnum; i++) 1767 info->sechdrs[i].sh_entsize = ~0UL; 1768 1769 pr_debug("Core section allocation order for %s:\n", mod->name); 1770 __layout_sections(mod, info, false); 1771 1772 pr_debug("Init section allocation order for %s:\n", mod->name); 1773 __layout_sections(mod, info, true); 1774 } 1775 1776 static void module_license_taint_check(struct module *mod, const char *license) 1777 { 1778 if (!license) 1779 license = "unspecified"; 1780 1781 if (!license_is_gpl_compatible(license)) { 1782 if (!test_taint(TAINT_PROPRIETARY_MODULE)) 1783 pr_warn("%s: module license '%s' taints kernel.\n", 1784 mod->name, license); 1785 add_taint_module(mod, TAINT_PROPRIETARY_MODULE, 1786 LOCKDEP_NOW_UNRELIABLE); 1787 } 1788 } 1789 1790 static int copy_modinfo_import_ns(struct module *mod, struct load_info *info) 1791 { 1792 char *ns; 1793 size_t len, total_len = 0; 1794 char *buf, *p; 1795 1796 for_each_modinfo_entry(ns, info, "import_ns") 1797 total_len += strlen(ns) + 1; 1798 1799 if (!total_len) { 1800 mod->imported_namespaces = NULL; 1801 return 0; 1802 } 1803 1804 buf = kmalloc(total_len, GFP_KERNEL); 1805 if (!buf) 1806 return -ENOMEM; 1807 1808 p = buf; 1809 for_each_modinfo_entry(ns, info, "import_ns") { 1810 len = strlen(ns); 1811 memcpy(p, ns, len); 1812 p += len; 1813 *p++ = '\n'; 1814 } 1815 /* Replace trailing newline with null terminator. */ 1816 *(p - 1) = '\0'; 1817 1818 mod->imported_namespaces = buf; 1819 return 0; 1820 } 1821 1822 static int setup_modinfo(struct module *mod, struct load_info *info) 1823 { 1824 const struct module_attribute *attr; 1825 char *imported_namespace; 1826 int i, err; 1827 1828 for (i = 0; (attr = modinfo_attrs[i]); i++) { 1829 if (attr->setup) 1830 attr->setup(mod, get_modinfo(info, attr->attr.name)); 1831 } 1832 1833 for_each_modinfo_entry(imported_namespace, info, "import_ns") { 1834 /* 1835 * 'module:' prefixed namespaces are implicit, disallow 1836 * explicit imports. 1837 */ 1838 if (strstarts(imported_namespace, "module:")) { 1839 pr_err("%s: module tries to import module namespace: %s\n", 1840 mod->name, imported_namespace); 1841 return -EPERM; 1842 } 1843 } 1844 1845 err = copy_modinfo_import_ns(mod, info); 1846 if (err) 1847 return err; 1848 1849 return 0; 1850 } 1851 1852 static void free_modinfo(struct module *mod) 1853 { 1854 const struct module_attribute *attr; 1855 int i; 1856 1857 for (i = 0; (attr = modinfo_attrs[i]); i++) { 1858 if (attr->free) 1859 attr->free(mod); 1860 } 1861 } 1862 1863 bool __weak module_init_section(const char *name) 1864 { 1865 return strstarts(name, ".init"); 1866 } 1867 1868 bool __weak module_exit_section(const char *name) 1869 { 1870 return strstarts(name, ".exit"); 1871 } 1872 1873 static int validate_section_offset(const struct load_info *info, Elf_Shdr *shdr) 1874 { 1875 #if defined(CONFIG_64BIT) 1876 unsigned long long secend; 1877 #else 1878 unsigned long secend; 1879 #endif 1880 1881 /* 1882 * Check for both overflow and offset/size being 1883 * too large. 1884 */ 1885 secend = shdr->sh_offset + shdr->sh_size; 1886 if (secend < shdr->sh_offset || secend > info->len) 1887 return -ENOEXEC; 1888 1889 return 0; 1890 } 1891 1892 /** 1893 * elf_validity_ehdr() - Checks an ELF header for module validity 1894 * @info: Load info containing the ELF header to check 1895 * 1896 * Checks whether an ELF header could belong to a valid module. Checks: 1897 * 1898 * * ELF header is within the data the user provided 1899 * * ELF magic is present 1900 * * It is relocatable (not final linked, not core file, etc.) 1901 * * The header's machine type matches what the architecture expects. 1902 * * Optional arch-specific hook for other properties 1903 * - module_elf_check_arch() is currently only used by PPC to check 1904 * ELF ABI version, but may be used by others in the future. 1905 * 1906 * Return: %0 if valid, %-ENOEXEC on failure. 1907 */ 1908 static int elf_validity_ehdr(const struct load_info *info) 1909 { 1910 if (info->len < sizeof(*(info->hdr))) { 1911 pr_err("Invalid ELF header len %lu\n", info->len); 1912 return -ENOEXEC; 1913 } 1914 if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0) { 1915 pr_err("Invalid ELF header magic: != %s\n", ELFMAG); 1916 return -ENOEXEC; 1917 } 1918 if (info->hdr->e_type != ET_REL) { 1919 pr_err("Invalid ELF header type: %u != %u\n", 1920 info->hdr->e_type, ET_REL); 1921 return -ENOEXEC; 1922 } 1923 if (!elf_check_arch(info->hdr)) { 1924 pr_err("Invalid architecture in ELF header: %u\n", 1925 info->hdr->e_machine); 1926 return -ENOEXEC; 1927 } 1928 if (!module_elf_check_arch(info->hdr)) { 1929 pr_err("Invalid module architecture in ELF header: %u\n", 1930 info->hdr->e_machine); 1931 return -ENOEXEC; 1932 } 1933 return 0; 1934 } 1935 1936 /** 1937 * elf_validity_cache_sechdrs() - Cache section headers if valid 1938 * @info: Load info to compute section headers from 1939 * 1940 * Checks: 1941 * 1942 * * ELF header is valid (see elf_validity_ehdr()) 1943 * * Section headers are the size we expect 1944 * * Section array fits in the user provided data 1945 * * Section index 0 is NULL 1946 * * Section contents are inbounds 1947 * 1948 * Then updates @info with a &load_info->sechdrs pointer if valid. 1949 * 1950 * Return: %0 if valid, negative error code if validation failed. 1951 */ 1952 static int elf_validity_cache_sechdrs(struct load_info *info) 1953 { 1954 Elf_Shdr *sechdrs; 1955 Elf_Shdr *shdr; 1956 int i; 1957 int err; 1958 1959 err = elf_validity_ehdr(info); 1960 if (err < 0) 1961 return err; 1962 1963 if (info->hdr->e_shentsize != sizeof(Elf_Shdr)) { 1964 pr_err("Invalid ELF section header size\n"); 1965 return -ENOEXEC; 1966 } 1967 1968 /* 1969 * e_shnum is 16 bits, and sizeof(Elf_Shdr) is 1970 * known and small. So e_shnum * sizeof(Elf_Shdr) 1971 * will not overflow unsigned long on any platform. 1972 */ 1973 if (info->hdr->e_shoff >= info->len 1974 || (info->hdr->e_shnum * sizeof(Elf_Shdr) > 1975 info->len - info->hdr->e_shoff)) { 1976 pr_err("Invalid ELF section header overflow\n"); 1977 return -ENOEXEC; 1978 } 1979 1980 sechdrs = (void *)info->hdr + info->hdr->e_shoff; 1981 1982 /* 1983 * The code assumes that section 0 has a length of zero and 1984 * an addr of zero, so check for it. 1985 */ 1986 if (sechdrs[0].sh_type != SHT_NULL 1987 || sechdrs[0].sh_size != 0 1988 || sechdrs[0].sh_addr != 0) { 1989 pr_err("ELF Spec violation: section 0 type(%d)!=SH_NULL or non-zero len or addr\n", 1990 sechdrs[0].sh_type); 1991 return -ENOEXEC; 1992 } 1993 1994 /* Validate contents are inbounds */ 1995 for (i = 1; i < info->hdr->e_shnum; i++) { 1996 shdr = &sechdrs[i]; 1997 switch (shdr->sh_type) { 1998 case SHT_NULL: 1999 case SHT_NOBITS: 2000 /* No contents, offset/size don't mean anything */ 2001 continue; 2002 default: 2003 err = validate_section_offset(info, shdr); 2004 if (err < 0) { 2005 pr_err("Invalid ELF section in module (section %u type %u)\n", 2006 i, shdr->sh_type); 2007 return err; 2008 } 2009 } 2010 } 2011 2012 info->sechdrs = sechdrs; 2013 2014 return 0; 2015 } 2016 2017 /** 2018 * elf_validity_cache_secstrings() - Caches section names if valid 2019 * @info: Load info to cache section names from. Must have valid sechdrs. 2020 * 2021 * Specifically checks: 2022 * 2023 * * Section name table index is inbounds of section headers 2024 * * Section name table type is SHT_STRTAB 2025 * * Section name table is not empty 2026 * * Section name table is NUL terminated 2027 * * All section name offsets are inbounds of the section 2028 * 2029 * Then updates @info with a &load_info->secstrings pointer if valid. 2030 * 2031 * Return: %0 if valid, negative error code if validation failed. 2032 */ 2033 static int elf_validity_cache_secstrings(struct load_info *info) 2034 { 2035 Elf_Shdr *strhdr, *shdr; 2036 char *secstrings; 2037 int i; 2038 2039 /* 2040 * Verify if the section name table index is valid. 2041 */ 2042 if (info->hdr->e_shstrndx == SHN_UNDEF 2043 || info->hdr->e_shstrndx >= info->hdr->e_shnum) { 2044 pr_err("Invalid ELF section name index: %d || e_shstrndx (%d) >= e_shnum (%d)\n", 2045 info->hdr->e_shstrndx, info->hdr->e_shstrndx, 2046 info->hdr->e_shnum); 2047 return -ENOEXEC; 2048 } 2049 2050 strhdr = &info->sechdrs[info->hdr->e_shstrndx]; 2051 2052 if (strhdr->sh_type != SHT_STRTAB) { 2053 pr_err("Invalid ELF section name table type: %u\n", strhdr->sh_type); 2054 return -ENOEXEC; 2055 } 2056 2057 /* 2058 * The section name table must be NUL-terminated, as required 2059 * by the spec. This makes strcmp and pr_* calls that access 2060 * strings in the section safe. 2061 */ 2062 secstrings = (void *)info->hdr + strhdr->sh_offset; 2063 if (strhdr->sh_size == 0) { 2064 pr_err("empty section name table\n"); 2065 return -ENOEXEC; 2066 } 2067 if (secstrings[strhdr->sh_size - 1] != '\0') { 2068 pr_err("ELF Spec violation: section name table isn't null terminated\n"); 2069 return -ENOEXEC; 2070 } 2071 2072 for (i = 0; i < info->hdr->e_shnum; i++) { 2073 shdr = &info->sechdrs[i]; 2074 /* SHT_NULL means sh_name has an undefined value */ 2075 if (shdr->sh_type == SHT_NULL) 2076 continue; 2077 if (shdr->sh_name >= strhdr->sh_size) { 2078 pr_err("Invalid ELF section name in module (section %u type %u)\n", 2079 i, shdr->sh_type); 2080 return -ENOEXEC; 2081 } 2082 } 2083 2084 info->secstrings = secstrings; 2085 return 0; 2086 } 2087 2088 /** 2089 * elf_validity_cache_index_info() - Validate and cache modinfo section 2090 * @info: Load info to populate the modinfo index on. 2091 * Must have &load_info->sechdrs and &load_info->secstrings populated 2092 * 2093 * Checks that if there is a .modinfo section, it is unique. 2094 * Then, it caches its index in &load_info->index.info. 2095 * Finally, it tries to populate the name to improve error messages. 2096 * 2097 * Return: %0 if valid, %-ENOEXEC if multiple modinfo sections were found. 2098 */ 2099 static int elf_validity_cache_index_info(struct load_info *info) 2100 { 2101 int info_idx; 2102 2103 info_idx = find_any_unique_sec(info, ".modinfo"); 2104 2105 if (info_idx == 0) 2106 /* Early return, no .modinfo */ 2107 return 0; 2108 2109 if (info_idx < 0) { 2110 pr_err("Only one .modinfo section must exist.\n"); 2111 return -ENOEXEC; 2112 } 2113 2114 info->index.info = info_idx; 2115 /* Try to find a name early so we can log errors with a module name */ 2116 info->name = get_modinfo(info, "name"); 2117 2118 return 0; 2119 } 2120 2121 /** 2122 * elf_validity_cache_index_mod() - Validates and caches this_module section 2123 * @info: Load info to cache this_module on. 2124 * Must have &load_info->sechdrs and &load_info->secstrings populated 2125 * 2126 * The ".gnu.linkonce.this_module" ELF section is special. It is what modpost 2127 * uses to refer to __this_module and let's use rely on THIS_MODULE to point 2128 * to &__this_module properly. The kernel's modpost declares it on each 2129 * modules's *.mod.c file. If the struct module of the kernel changes a full 2130 * kernel rebuild is required. 2131 * 2132 * We have a few expectations for this special section, this function 2133 * validates all this for us: 2134 * 2135 * * The section has contents 2136 * * The section is unique 2137 * * We expect the kernel to always have to allocate it: SHF_ALLOC 2138 * * The section size must match the kernel's run time's struct module 2139 * size 2140 * 2141 * If all checks pass, the index will be cached in &load_info->index.mod 2142 * 2143 * Return: %0 on validation success, %-ENOEXEC on failure 2144 */ 2145 static int elf_validity_cache_index_mod(struct load_info *info) 2146 { 2147 Elf_Shdr *shdr; 2148 int mod_idx; 2149 2150 mod_idx = find_any_unique_sec(info, ".gnu.linkonce.this_module"); 2151 if (mod_idx <= 0) { 2152 pr_err("module %s: Exactly one .gnu.linkonce.this_module section must exist.\n", 2153 info->name ?: "(missing .modinfo section or name field)"); 2154 return -ENOEXEC; 2155 } 2156 2157 shdr = &info->sechdrs[mod_idx]; 2158 2159 if (shdr->sh_type == SHT_NOBITS) { 2160 pr_err("module %s: .gnu.linkonce.this_module section must have a size set\n", 2161 info->name ?: "(missing .modinfo section or name field)"); 2162 return -ENOEXEC; 2163 } 2164 2165 if (!(shdr->sh_flags & SHF_ALLOC)) { 2166 pr_err("module %s: .gnu.linkonce.this_module must occupy memory during process execution\n", 2167 info->name ?: "(missing .modinfo section or name field)"); 2168 return -ENOEXEC; 2169 } 2170 2171 if (shdr->sh_size != sizeof(struct module)) { 2172 pr_err("module %s: .gnu.linkonce.this_module section size must match the kernel's built struct module size at run time\n", 2173 info->name ?: "(missing .modinfo section or name field)"); 2174 return -ENOEXEC; 2175 } 2176 2177 info->index.mod = mod_idx; 2178 2179 return 0; 2180 } 2181 2182 /** 2183 * elf_validity_cache_index_sym() - Validate and cache symtab index 2184 * @info: Load info to cache symtab index in. 2185 * Must have &load_info->sechdrs and &load_info->secstrings populated. 2186 * 2187 * Checks that there is exactly one symbol table, then caches its index in 2188 * &load_info->index.sym. 2189 * 2190 * Return: %0 if valid, %-ENOEXEC on failure. 2191 */ 2192 static int elf_validity_cache_index_sym(struct load_info *info) 2193 { 2194 unsigned int sym_idx; 2195 unsigned int num_sym_secs = 0; 2196 int i; 2197 2198 for (i = 1; i < info->hdr->e_shnum; i++) { 2199 if (info->sechdrs[i].sh_type == SHT_SYMTAB) { 2200 num_sym_secs++; 2201 sym_idx = i; 2202 } 2203 } 2204 2205 if (num_sym_secs != 1) { 2206 pr_warn("%s: module has no symbols (stripped?)\n", 2207 info->name ?: "(missing .modinfo section or name field)"); 2208 return -ENOEXEC; 2209 } 2210 2211 info->index.sym = sym_idx; 2212 2213 return 0; 2214 } 2215 2216 /** 2217 * elf_validity_cache_index_str() - Validate and cache strtab index 2218 * @info: Load info to cache strtab index in. 2219 * Must have &load_info->sechdrs and &load_info->secstrings populated. 2220 * Must have &load_info->index.sym populated. 2221 * 2222 * Looks at the symbol table's associated string table, makes sure it is 2223 * in-bounds and of type SHT_STRTAB, and caches it. 2224 * 2225 * Return: %0 if valid, %-ENOEXEC on failure. 2226 */ 2227 static int elf_validity_cache_index_str(struct load_info *info) 2228 { 2229 unsigned int str_idx = info->sechdrs[info->index.sym].sh_link; 2230 2231 if (str_idx == SHN_UNDEF || str_idx >= info->hdr->e_shnum) { 2232 pr_err("Invalid ELF sh_link!=SHN_UNDEF(%d) or (sh_link(%d) >= hdr->e_shnum(%d)\n", 2233 str_idx, str_idx, info->hdr->e_shnum); 2234 return -ENOEXEC; 2235 } 2236 2237 if (info->sechdrs[str_idx].sh_type != SHT_STRTAB) { 2238 pr_err("Invalid ELF symbol string table type: %u\n", 2239 info->sechdrs[str_idx].sh_type); 2240 return -ENOEXEC; 2241 } 2242 2243 info->index.str = str_idx; 2244 return 0; 2245 } 2246 2247 /** 2248 * elf_validity_cache_index_versions() - Validate and cache version indices 2249 * @info: Load info to cache version indices in. 2250 * Must have &load_info->sechdrs and &load_info->secstrings populated. 2251 * @flags: Load flags, relevant to suppress version loading, see 2252 * uapi/linux/module.h 2253 * 2254 * If we're ignoring modversions based on @flags, zero all version indices 2255 * and return validity. Othewrise check: 2256 * 2257 * * If "__version_ext_crcs" is present, "__version_ext_names" is present 2258 * * There is a name present for every crc 2259 * 2260 * Then populate: 2261 * 2262 * * &load_info->index.vers 2263 * * &load_info->index.vers_ext_crc 2264 * * &load_info->index.vers_ext_names 2265 * 2266 * if present. 2267 * 2268 * Return: %0 if valid, %-ENOEXEC on failure. 2269 */ 2270 static int elf_validity_cache_index_versions(struct load_info *info, int flags) 2271 { 2272 unsigned int vers_ext_crc; 2273 unsigned int vers_ext_name; 2274 size_t crc_count; 2275 size_t remaining_len; 2276 size_t name_size; 2277 char *name; 2278 2279 /* If modversions were suppressed, pretend we didn't find any */ 2280 if (flags & MODULE_INIT_IGNORE_MODVERSIONS) { 2281 info->index.vers = 0; 2282 info->index.vers_ext_crc = 0; 2283 info->index.vers_ext_name = 0; 2284 return 0; 2285 } 2286 2287 vers_ext_crc = find_sec(info, "__version_ext_crcs"); 2288 vers_ext_name = find_sec(info, "__version_ext_names"); 2289 2290 /* If we have one field, we must have the other */ 2291 if (!!vers_ext_crc != !!vers_ext_name) { 2292 pr_err("extended version crc+name presence does not match"); 2293 return -ENOEXEC; 2294 } 2295 2296 /* 2297 * If we have extended version information, we should have the same 2298 * number of entries in every section. 2299 */ 2300 if (vers_ext_crc) { 2301 crc_count = info->sechdrs[vers_ext_crc].sh_size / sizeof(u32); 2302 name = (void *)info->hdr + 2303 info->sechdrs[vers_ext_name].sh_offset; 2304 remaining_len = info->sechdrs[vers_ext_name].sh_size; 2305 2306 while (crc_count--) { 2307 name_size = strnlen(name, remaining_len) + 1; 2308 if (name_size > remaining_len) { 2309 pr_err("more extended version crcs than names"); 2310 return -ENOEXEC; 2311 } 2312 remaining_len -= name_size; 2313 name += name_size; 2314 } 2315 } 2316 2317 info->index.vers = find_sec(info, "__versions"); 2318 info->index.vers_ext_crc = vers_ext_crc; 2319 info->index.vers_ext_name = vers_ext_name; 2320 return 0; 2321 } 2322 2323 /** 2324 * elf_validity_cache_index() - Resolve, validate, cache section indices 2325 * @info: Load info to read from and update. 2326 * &load_info->sechdrs and &load_info->secstrings must be populated. 2327 * @flags: Load flags, relevant to suppress version loading, see 2328 * uapi/linux/module.h 2329 * 2330 * Populates &load_info->index, validating as it goes. 2331 * See child functions for per-field validation: 2332 * 2333 * * elf_validity_cache_index_info() 2334 * * elf_validity_cache_index_mod() 2335 * * elf_validity_cache_index_sym() 2336 * * elf_validity_cache_index_str() 2337 * * elf_validity_cache_index_versions() 2338 * 2339 * If CONFIG_SMP is enabled, load the percpu section by name with no 2340 * validation. 2341 * 2342 * Return: 0 on success, negative error code if an index failed validation. 2343 */ 2344 static int elf_validity_cache_index(struct load_info *info, int flags) 2345 { 2346 int err; 2347 2348 err = elf_validity_cache_index_info(info); 2349 if (err < 0) 2350 return err; 2351 err = elf_validity_cache_index_mod(info); 2352 if (err < 0) 2353 return err; 2354 err = elf_validity_cache_index_sym(info); 2355 if (err < 0) 2356 return err; 2357 err = elf_validity_cache_index_str(info); 2358 if (err < 0) 2359 return err; 2360 err = elf_validity_cache_index_versions(info, flags); 2361 if (err < 0) 2362 return err; 2363 2364 info->index.pcpu = find_pcpusec(info); 2365 2366 return 0; 2367 } 2368 2369 /** 2370 * elf_validity_cache_strtab() - Validate and cache symbol string table 2371 * @info: Load info to read from and update. 2372 * Must have &load_info->sechdrs and &load_info->secstrings populated. 2373 * Must have &load_info->index populated. 2374 * 2375 * Checks: 2376 * 2377 * * The string table is not empty. 2378 * * The string table starts and ends with NUL (required by ELF spec). 2379 * * Every &Elf_Sym->st_name offset in the symbol table is inbounds of the 2380 * string table. 2381 * 2382 * And caches the pointer as &load_info->strtab in @info. 2383 * 2384 * Return: 0 on success, negative error code if a check failed. 2385 */ 2386 static int elf_validity_cache_strtab(struct load_info *info) 2387 { 2388 Elf_Shdr *str_shdr = &info->sechdrs[info->index.str]; 2389 Elf_Shdr *sym_shdr = &info->sechdrs[info->index.sym]; 2390 char *strtab = (char *)info->hdr + str_shdr->sh_offset; 2391 Elf_Sym *syms = (void *)info->hdr + sym_shdr->sh_offset; 2392 int i; 2393 2394 if (str_shdr->sh_size == 0) { 2395 pr_err("empty symbol string table\n"); 2396 return -ENOEXEC; 2397 } 2398 if (strtab[0] != '\0') { 2399 pr_err("symbol string table missing leading NUL\n"); 2400 return -ENOEXEC; 2401 } 2402 if (strtab[str_shdr->sh_size - 1] != '\0') { 2403 pr_err("symbol string table isn't NUL terminated\n"); 2404 return -ENOEXEC; 2405 } 2406 2407 /* 2408 * Now that we know strtab is correctly structured, check symbol 2409 * starts are inbounds before they're used later. 2410 */ 2411 for (i = 0; i < sym_shdr->sh_size / sizeof(*syms); i++) { 2412 if (syms[i].st_name >= str_shdr->sh_size) { 2413 pr_err("symbol name out of bounds in string table"); 2414 return -ENOEXEC; 2415 } 2416 } 2417 2418 info->strtab = strtab; 2419 return 0; 2420 } 2421 2422 /* 2423 * Check userspace passed ELF module against our expectations, and cache 2424 * useful variables for further processing as we go. 2425 * 2426 * This does basic validity checks against section offsets and sizes, the 2427 * section name string table, and the indices used for it (sh_name). 2428 * 2429 * As a last step, since we're already checking the ELF sections we cache 2430 * useful variables which will be used later for our convenience: 2431 * 2432 * o pointers to section headers 2433 * o cache the modinfo symbol section 2434 * o cache the string symbol section 2435 * o cache the module section 2436 * 2437 * As a last step we set info->mod to the temporary copy of the module in 2438 * info->hdr. The final one will be allocated in move_module(). Any 2439 * modifications we make to our copy of the module will be carried over 2440 * to the final minted module. 2441 */ 2442 static int elf_validity_cache_copy(struct load_info *info, int flags) 2443 { 2444 int err; 2445 2446 err = elf_validity_cache_sechdrs(info); 2447 if (err < 0) 2448 return err; 2449 err = elf_validity_cache_secstrings(info); 2450 if (err < 0) 2451 return err; 2452 err = elf_validity_cache_index(info, flags); 2453 if (err < 0) 2454 return err; 2455 err = elf_validity_cache_strtab(info); 2456 if (err < 0) 2457 return err; 2458 2459 /* This is temporary: point mod into copy of data. */ 2460 info->mod = (void *)info->hdr + info->sechdrs[info->index.mod].sh_offset; 2461 2462 /* 2463 * If we didn't load the .modinfo 'name' field earlier, fall back to 2464 * on-disk struct mod 'name' field. 2465 */ 2466 if (!info->name) 2467 info->name = info->mod->name; 2468 2469 return 0; 2470 } 2471 2472 #define COPY_CHUNK_SIZE (16*PAGE_SIZE) 2473 2474 static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len) 2475 { 2476 do { 2477 unsigned long n = min(len, COPY_CHUNK_SIZE); 2478 2479 if (copy_from_user(dst, usrc, n) != 0) 2480 return -EFAULT; 2481 cond_resched(); 2482 dst += n; 2483 usrc += n; 2484 len -= n; 2485 } while (len); 2486 return 0; 2487 } 2488 2489 static int check_modinfo_livepatch(struct module *mod, struct load_info *info) 2490 { 2491 if (!get_modinfo(info, "livepatch")) 2492 /* Nothing more to do */ 2493 return 0; 2494 2495 if (set_livepatch_module(mod)) 2496 return 0; 2497 2498 pr_err("%s: module is marked as livepatch module, but livepatch support is disabled", 2499 mod->name); 2500 return -ENOEXEC; 2501 } 2502 2503 static void check_modinfo_retpoline(struct module *mod, struct load_info *info) 2504 { 2505 if (retpoline_module_ok(get_modinfo(info, "retpoline"))) 2506 return; 2507 2508 pr_warn("%s: loading module not compiled with retpoline compiler.\n", 2509 mod->name); 2510 } 2511 2512 /* Sets info->hdr and info->len. */ 2513 static int copy_module_from_user(const void __user *umod, unsigned long len, 2514 struct load_info *info) 2515 { 2516 int err; 2517 2518 info->len = len; 2519 if (info->len < sizeof(*(info->hdr))) 2520 return -ENOEXEC; 2521 2522 err = security_kernel_load_data(LOADING_MODULE, true); 2523 if (err) 2524 return err; 2525 2526 /* Suck in entire file: we'll want most of it. */ 2527 info->hdr = __vmalloc(info->len, GFP_KERNEL | __GFP_NOWARN); 2528 if (!info->hdr) 2529 return -ENOMEM; 2530 2531 if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) { 2532 err = -EFAULT; 2533 goto out; 2534 } 2535 2536 err = security_kernel_post_load_data((char *)info->hdr, info->len, 2537 LOADING_MODULE, "init_module"); 2538 out: 2539 if (err) 2540 vfree(info->hdr); 2541 2542 return err; 2543 } 2544 2545 static void free_copy(struct load_info *info, int flags) 2546 { 2547 if (flags & MODULE_INIT_COMPRESSED_FILE) 2548 module_decompress_cleanup(info); 2549 else 2550 vfree(info->hdr); 2551 } 2552 2553 static int rewrite_section_headers(struct load_info *info, int flags) 2554 { 2555 unsigned int i; 2556 2557 /* This should always be true, but let's be sure. */ 2558 info->sechdrs[0].sh_addr = 0; 2559 2560 for (i = 1; i < info->hdr->e_shnum; i++) { 2561 Elf_Shdr *shdr = &info->sechdrs[i]; 2562 2563 /* 2564 * Mark all sections sh_addr with their address in the 2565 * temporary image. 2566 */ 2567 shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset; 2568 2569 } 2570 2571 /* Track but don't keep modinfo and version sections. */ 2572 info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC; 2573 info->sechdrs[info->index.vers_ext_crc].sh_flags &= 2574 ~(unsigned long)SHF_ALLOC; 2575 info->sechdrs[info->index.vers_ext_name].sh_flags &= 2576 ~(unsigned long)SHF_ALLOC; 2577 info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC; 2578 2579 return 0; 2580 } 2581 2582 static const char *const module_license_offenders[] = { 2583 /* driverloader was caught wrongly pretending to be under GPL */ 2584 "driverloader", 2585 2586 /* lve claims to be GPL but upstream won't provide source */ 2587 "lve", 2588 }; 2589 2590 /* 2591 * These calls taint the kernel depending certain module circumstances */ 2592 static void module_augment_kernel_taints(struct module *mod, struct load_info *info) 2593 { 2594 int prev_taint = test_taint(TAINT_PROPRIETARY_MODULE); 2595 size_t i; 2596 2597 if (!get_modinfo(info, "intree")) { 2598 if (!test_taint(TAINT_OOT_MODULE)) 2599 pr_warn("%s: loading out-of-tree module taints kernel.\n", 2600 mod->name); 2601 add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK); 2602 } 2603 2604 check_modinfo_retpoline(mod, info); 2605 2606 if (get_modinfo(info, "staging")) { 2607 add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK); 2608 pr_warn("%s: module is from the staging directory, the quality " 2609 "is unknown, you have been warned.\n", mod->name); 2610 } 2611 2612 if (is_livepatch_module(mod)) { 2613 add_taint_module(mod, TAINT_LIVEPATCH, LOCKDEP_STILL_OK); 2614 pr_notice_once("%s: tainting kernel with TAINT_LIVEPATCH\n", 2615 mod->name); 2616 } 2617 2618 module_license_taint_check(mod, get_modinfo(info, "license")); 2619 2620 if (get_modinfo(info, "test")) { 2621 if (!test_taint(TAINT_TEST)) 2622 pr_warn("%s: loading test module taints kernel.\n", 2623 mod->name); 2624 add_taint_module(mod, TAINT_TEST, LOCKDEP_STILL_OK); 2625 } 2626 #ifdef CONFIG_MODULE_SIG 2627 mod->sig_ok = info->sig_ok; 2628 if (!mod->sig_ok) { 2629 pr_notice_once("%s: module verification failed: signature " 2630 "and/or required key missing - tainting " 2631 "kernel\n", mod->name); 2632 add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK); 2633 } 2634 #endif 2635 2636 /* 2637 * ndiswrapper is under GPL by itself, but loads proprietary modules. 2638 * Don't use add_taint_module(), as it would prevent ndiswrapper from 2639 * using GPL-only symbols it needs. 2640 */ 2641 if (strcmp(mod->name, "ndiswrapper") == 0) 2642 add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE); 2643 2644 for (i = 0; i < ARRAY_SIZE(module_license_offenders); ++i) { 2645 if (strcmp(mod->name, module_license_offenders[i]) == 0) 2646 add_taint_module(mod, TAINT_PROPRIETARY_MODULE, 2647 LOCKDEP_NOW_UNRELIABLE); 2648 } 2649 2650 if (!prev_taint && test_taint(TAINT_PROPRIETARY_MODULE)) 2651 pr_warn("%s: module license taints kernel.\n", mod->name); 2652 2653 } 2654 2655 static int check_modinfo(struct module *mod, struct load_info *info, int flags) 2656 { 2657 const char *modmagic = get_modinfo(info, "vermagic"); 2658 int err; 2659 2660 if (flags & MODULE_INIT_IGNORE_VERMAGIC) 2661 modmagic = NULL; 2662 2663 /* This is allowed: modprobe --force will invalidate it. */ 2664 if (!modmagic) { 2665 err = try_to_force_load(mod, "bad vermagic"); 2666 if (err) 2667 return err; 2668 } else if (!same_magic(modmagic, vermagic, info->index.vers)) { 2669 pr_err("%s: version magic '%s' should be '%s'\n", 2670 info->name, modmagic, vermagic); 2671 return -ENOEXEC; 2672 } 2673 2674 err = check_modinfo_livepatch(mod, info); 2675 if (err) 2676 return err; 2677 2678 return 0; 2679 } 2680 2681 static int find_module_sections(struct module *mod, struct load_info *info) 2682 { 2683 mod->kp = section_objs(info, "__param", 2684 sizeof(*mod->kp), &mod->num_kp); 2685 mod->syms = section_objs(info, "__ksymtab", 2686 sizeof(*mod->syms), &mod->num_syms); 2687 mod->crcs = section_addr(info, "__kcrctab"); 2688 mod->flagstab = section_addr(info, "__kflagstab"); 2689 2690 if (section_addr(info, "__ksymtab_gpl")) 2691 pr_warn("%s: ignoring obsolete section __ksymtab_gpl\n", 2692 mod->name); 2693 if (section_addr(info, "__kcrctab_gpl")) 2694 pr_warn("%s: ignoring obsolete section __kcrctab_gpl\n", 2695 mod->name); 2696 2697 #ifdef CONFIG_CONSTRUCTORS 2698 mod->ctors = section_objs(info, ".ctors", 2699 sizeof(*mod->ctors), &mod->num_ctors); 2700 if (!mod->ctors) 2701 mod->ctors = section_objs(info, ".init_array", 2702 sizeof(*mod->ctors), &mod->num_ctors); 2703 else if (find_sec(info, ".init_array")) { 2704 /* 2705 * This shouldn't happen with same compiler and binutils 2706 * building all parts of the module. 2707 */ 2708 pr_warn("%s: has both .ctors and .init_array.\n", 2709 mod->name); 2710 return -EINVAL; 2711 } 2712 #endif 2713 2714 mod->noinstr_text_start = section_objs(info, ".noinstr.text", 1, 2715 &mod->noinstr_text_size); 2716 2717 #ifdef CONFIG_TRACEPOINTS 2718 mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs", 2719 sizeof(*mod->tracepoints_ptrs), 2720 &mod->num_tracepoints); 2721 #endif 2722 #ifdef CONFIG_TREE_SRCU 2723 mod->srcu_struct_ptrs = section_objs(info, "___srcu_struct_ptrs", 2724 sizeof(*mod->srcu_struct_ptrs), 2725 &mod->num_srcu_structs); 2726 #endif 2727 #ifdef CONFIG_BPF_EVENTS 2728 mod->bpf_raw_events = section_objs(info, "__bpf_raw_tp_map", 2729 sizeof(*mod->bpf_raw_events), 2730 &mod->num_bpf_raw_events); 2731 #endif 2732 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES 2733 mod->btf_data = any_section_objs(info, ".BTF", 1, &mod->btf_data_size); 2734 mod->btf_base_data = any_section_objs(info, ".BTF.base", 1, 2735 &mod->btf_base_data_size); 2736 #endif 2737 #ifdef CONFIG_JUMP_LABEL 2738 mod->jump_entries = section_objs(info, "__jump_table", 2739 sizeof(*mod->jump_entries), 2740 &mod->num_jump_entries); 2741 #endif 2742 #ifdef CONFIG_EVENT_TRACING 2743 mod->trace_events = section_objs(info, "_ftrace_events", 2744 sizeof(*mod->trace_events), 2745 &mod->num_trace_events); 2746 mod->trace_evals = section_objs(info, "_ftrace_eval_map", 2747 sizeof(*mod->trace_evals), 2748 &mod->num_trace_evals); 2749 #endif 2750 #ifdef CONFIG_TRACING 2751 mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt", 2752 sizeof(*mod->trace_bprintk_fmt_start), 2753 &mod->num_trace_bprintk_fmt); 2754 #endif 2755 #ifdef CONFIG_DYNAMIC_FTRACE 2756 /* sechdrs[0].sh_size is always zero */ 2757 mod->ftrace_callsites = section_objs(info, FTRACE_CALLSITE_SECTION, 2758 sizeof(*mod->ftrace_callsites), 2759 &mod->num_ftrace_callsites); 2760 #endif 2761 #ifdef CONFIG_FUNCTION_ERROR_INJECTION 2762 mod->ei_funcs = section_objs(info, "_error_injection_whitelist", 2763 sizeof(*mod->ei_funcs), 2764 &mod->num_ei_funcs); 2765 #endif 2766 #ifdef CONFIG_KPROBES 2767 mod->kprobes_text_start = section_objs(info, ".kprobes.text", 1, 2768 &mod->kprobes_text_size); 2769 mod->kprobe_blacklist = section_objs(info, "_kprobe_blacklist", 2770 sizeof(unsigned long), 2771 &mod->num_kprobe_blacklist); 2772 #endif 2773 #ifdef CONFIG_PRINTK_INDEX 2774 mod->printk_index_start = section_objs(info, ".printk_index", 2775 sizeof(*mod->printk_index_start), 2776 &mod->printk_index_size); 2777 #endif 2778 #ifdef CONFIG_HAVE_STATIC_CALL_INLINE 2779 mod->static_call_sites = section_objs(info, ".static_call_sites", 2780 sizeof(*mod->static_call_sites), 2781 &mod->num_static_call_sites); 2782 #endif 2783 #if IS_ENABLED(CONFIG_KUNIT) 2784 mod->kunit_suites = section_objs(info, ".kunit_test_suites", 2785 sizeof(*mod->kunit_suites), 2786 &mod->num_kunit_suites); 2787 mod->kunit_init_suites = section_objs(info, ".kunit_init_test_suites", 2788 sizeof(*mod->kunit_init_suites), 2789 &mod->num_kunit_init_suites); 2790 #endif 2791 2792 mod->extable = section_objs(info, "__ex_table", 2793 sizeof(*mod->extable), &mod->num_exentries); 2794 2795 if (section_addr(info, "__obsparm")) 2796 pr_warn("%s: Ignoring obsolete parameters\n", mod->name); 2797 2798 #ifdef CONFIG_DYNAMIC_DEBUG_CORE 2799 mod->dyndbg_info.descs = section_objs(info, "__dyndbg", 2800 sizeof(*mod->dyndbg_info.descs), 2801 &mod->dyndbg_info.num_descs); 2802 mod->dyndbg_info.classes = section_objs(info, "__dyndbg_classes", 2803 sizeof(*mod->dyndbg_info.classes), 2804 &mod->dyndbg_info.num_classes); 2805 #endif 2806 2807 return 0; 2808 } 2809 2810 static int move_module(struct module *mod, struct load_info *info) 2811 { 2812 int i, ret; 2813 enum mod_mem_type t = MOD_MEM_NUM_TYPES; 2814 bool codetag_section_found = false; 2815 2816 for_each_mod_mem_type(type) { 2817 if (!mod->mem[type].size) { 2818 mod->mem[type].base = NULL; 2819 continue; 2820 } 2821 2822 ret = module_memory_alloc(mod, type); 2823 if (ret) { 2824 t = type; 2825 goto out_err; 2826 } 2827 } 2828 2829 /* Transfer each section which specifies SHF_ALLOC */ 2830 pr_debug("Final section addresses for %s:\n", mod->name); 2831 for (i = 0; i < info->hdr->e_shnum; i++) { 2832 void *dest; 2833 Elf_Shdr *shdr = &info->sechdrs[i]; 2834 const char *sname; 2835 2836 if (!(shdr->sh_flags & SHF_ALLOC)) 2837 continue; 2838 2839 sname = info->secstrings + shdr->sh_name; 2840 /* 2841 * Load codetag sections separately as they might still be used 2842 * after module unload. 2843 */ 2844 if (codetag_needs_module_section(mod, sname, shdr->sh_size)) { 2845 dest = codetag_alloc_module_section(mod, sname, shdr->sh_size, 2846 arch_mod_section_prepend(mod, i), shdr->sh_addralign); 2847 if (WARN_ON(!dest)) { 2848 ret = -EINVAL; 2849 goto out_err; 2850 } 2851 if (IS_ERR(dest)) { 2852 ret = PTR_ERR(dest); 2853 goto out_err; 2854 } 2855 codetag_section_found = true; 2856 } else { 2857 enum mod_mem_type type = shdr->sh_entsize >> SH_ENTSIZE_TYPE_SHIFT; 2858 unsigned long offset = shdr->sh_entsize & SH_ENTSIZE_OFFSET_MASK; 2859 2860 dest = mod->mem[type].base + offset; 2861 } 2862 2863 if (shdr->sh_type != SHT_NOBITS) { 2864 /* 2865 * Our ELF checker already validated this, but let's 2866 * be pedantic and make the goal clearer. We actually 2867 * end up copying over all modifications made to the 2868 * userspace copy of the entire struct module. 2869 */ 2870 if (i == info->index.mod && 2871 (WARN_ON_ONCE(shdr->sh_size != sizeof(struct module)))) { 2872 ret = -ENOEXEC; 2873 goto out_err; 2874 } 2875 memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size); 2876 } 2877 /* 2878 * Update the userspace copy's ELF section address to point to 2879 * our newly allocated memory as a pure convenience so that 2880 * users of info can keep taking advantage and using the newly 2881 * minted official memory area. 2882 */ 2883 shdr->sh_addr = (unsigned long)dest; 2884 pr_debug("\t0x%lx 0x%.8lx %s\n", (long)shdr->sh_addr, 2885 (long)shdr->sh_size, info->secstrings + shdr->sh_name); 2886 } 2887 2888 return 0; 2889 out_err: 2890 module_memory_restore_rox(mod); 2891 while (t--) 2892 module_memory_free(mod, t); 2893 if (codetag_section_found) 2894 codetag_free_module_sections(mod); 2895 2896 return ret; 2897 } 2898 2899 static int check_export_symbol_sections(struct module *mod) 2900 { 2901 if (mod->num_syms && !mod->flagstab) { 2902 pr_err("%s: no flags for exported symbols\n", mod->name); 2903 return -ENOEXEC; 2904 } 2905 #ifdef CONFIG_MODVERSIONS 2906 if (mod->num_syms && !mod->crcs) { 2907 return try_to_force_load(mod, 2908 "no versions for exported symbols"); 2909 } 2910 #endif 2911 return 0; 2912 } 2913 2914 static void flush_module_icache(const struct module *mod) 2915 { 2916 /* 2917 * Flush the instruction cache, since we've played with text. 2918 * Do it before processing of module parameters, so the module 2919 * can provide parameter accessor functions of its own. 2920 */ 2921 for_each_mod_mem_type(type) { 2922 const struct module_memory *mod_mem = &mod->mem[type]; 2923 2924 if (mod_mem->size) { 2925 flush_icache_range((unsigned long)mod_mem->base, 2926 (unsigned long)mod_mem->base + mod_mem->size); 2927 } 2928 } 2929 } 2930 2931 bool __weak module_elf_check_arch(Elf_Ehdr *hdr) 2932 { 2933 return true; 2934 } 2935 2936 int __weak module_frob_arch_sections(Elf_Ehdr *hdr, 2937 Elf_Shdr *sechdrs, 2938 char *secstrings, 2939 struct module *mod) 2940 { 2941 return 0; 2942 } 2943 2944 /* module_blacklist is a comma-separated list of module names */ 2945 static char *module_blacklist; 2946 static bool blacklisted(const char *module_name) 2947 { 2948 const char *p; 2949 size_t len; 2950 2951 if (!module_blacklist) 2952 return false; 2953 2954 for (p = module_blacklist; *p; p += len) { 2955 len = strcspn(p, ","); 2956 if (strlen(module_name) == len && !memcmp(module_name, p, len)) 2957 return true; 2958 if (p[len] == ',') 2959 len++; 2960 } 2961 return false; 2962 } 2963 core_param(module_blacklist, module_blacklist, charp, 0400); 2964 2965 static struct module *layout_and_allocate(struct load_info *info, int flags) 2966 { 2967 struct module *mod; 2968 int err; 2969 2970 /* Allow arches to frob section contents and sizes. */ 2971 err = module_frob_arch_sections(info->hdr, info->sechdrs, 2972 info->secstrings, info->mod); 2973 if (err < 0) 2974 return ERR_PTR(err); 2975 2976 err = module_enforce_rwx_sections(info->hdr, info->sechdrs, 2977 info->secstrings, info->mod); 2978 if (err < 0) 2979 return ERR_PTR(err); 2980 2981 /* We will do a special allocation for per-cpu sections later. */ 2982 info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC; 2983 2984 /* 2985 * Mark relevant sections as SHF_RO_AFTER_INIT so layout_sections() can 2986 * put them in the right place. 2987 * Note: ro_after_init sections also have SHF_{WRITE,ALLOC} set. 2988 */ 2989 module_mark_ro_after_init(info->hdr, info->sechdrs, info->secstrings); 2990 2991 /* 2992 * Determine total sizes, and put offsets in sh_entsize. For now 2993 * this is done generically; there doesn't appear to be any 2994 * special cases for the architectures. 2995 */ 2996 layout_sections(info->mod, info); 2997 layout_symtab(info->mod, info); 2998 2999 /* Allocate and move to the final place */ 3000 err = move_module(info->mod, info); 3001 if (err) 3002 return ERR_PTR(err); 3003 3004 /* Module has been copied to its final place now: return it. */ 3005 mod = (void *)info->sechdrs[info->index.mod].sh_addr; 3006 kmemleak_load_module(mod, info); 3007 codetag_module_replaced(info->mod, mod); 3008 3009 return mod; 3010 } 3011 3012 /* mod is no longer valid after this! */ 3013 static void module_deallocate(struct module *mod, struct load_info *info) 3014 { 3015 percpu_modfree(mod); 3016 module_arch_freeing_init(mod); 3017 codetag_free_module_sections(mod); 3018 3019 free_mod_mem(mod); 3020 } 3021 3022 int __weak module_finalize(const Elf_Ehdr *hdr, 3023 const Elf_Shdr *sechdrs, 3024 struct module *me) 3025 { 3026 return 0; 3027 } 3028 3029 static int post_relocation(struct module *mod, const struct load_info *info) 3030 { 3031 /* Sort exception table now relocations are done. */ 3032 sort_extable(mod->extable, mod->extable + mod->num_exentries); 3033 3034 /* Copy relocated percpu area over. */ 3035 percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr, 3036 info->sechdrs[info->index.pcpu].sh_size); 3037 3038 /* Setup kallsyms-specific fields. */ 3039 add_kallsyms(mod, info); 3040 3041 /* Arch-specific module finalizing. */ 3042 return module_finalize(info->hdr, info->sechdrs, mod); 3043 } 3044 3045 /* Call module constructors. */ 3046 static void do_mod_ctors(struct module *mod) 3047 { 3048 #ifdef CONFIG_CONSTRUCTORS 3049 unsigned long i; 3050 3051 for (i = 0; i < mod->num_ctors; i++) 3052 mod->ctors[i](); 3053 #endif 3054 } 3055 3056 /* For freeing module_init on success, in case kallsyms traversing */ 3057 struct mod_initfree { 3058 struct llist_node node; 3059 void *init_text; 3060 void *init_data; 3061 void *init_rodata; 3062 }; 3063 3064 static void do_free_init(struct work_struct *w) 3065 { 3066 struct llist_node *pos, *n, *list; 3067 struct mod_initfree *initfree; 3068 3069 list = llist_del_all(&init_free_list); 3070 3071 synchronize_rcu(); 3072 3073 llist_for_each_safe(pos, n, list) { 3074 initfree = container_of(pos, struct mod_initfree, node); 3075 execmem_free(initfree->init_text); 3076 execmem_free(initfree->init_data); 3077 execmem_free(initfree->init_rodata); 3078 kfree(initfree); 3079 } 3080 } 3081 3082 void flush_module_init_free_work(void) 3083 { 3084 flush_work(&init_free_wq); 3085 } 3086 3087 #undef MODULE_PARAM_PREFIX 3088 #define MODULE_PARAM_PREFIX "module." 3089 /* Default value for module->async_probe_requested */ 3090 static bool async_probe; 3091 module_param(async_probe, bool, 0644); 3092 3093 /* 3094 * This is where the real work happens. 3095 * 3096 * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb 3097 * helper command 'lx-symbols'. 3098 */ 3099 static noinline int do_init_module(struct module *mod) 3100 { 3101 int ret = 0; 3102 struct mod_initfree *freeinit; 3103 #if defined(CONFIG_MODULE_STATS) 3104 unsigned int text_size = 0, total_size = 0; 3105 3106 for_each_mod_mem_type(type) { 3107 const struct module_memory *mod_mem = &mod->mem[type]; 3108 if (mod_mem->size) { 3109 total_size += mod_mem->size; 3110 if (type == MOD_TEXT || type == MOD_INIT_TEXT) 3111 text_size += mod_mem->size; 3112 } 3113 } 3114 #endif 3115 3116 freeinit = kmalloc_obj(*freeinit); 3117 if (!freeinit) { 3118 ret = -ENOMEM; 3119 goto fail; 3120 } 3121 freeinit->init_text = mod->mem[MOD_INIT_TEXT].base; 3122 freeinit->init_data = mod->mem[MOD_INIT_DATA].base; 3123 freeinit->init_rodata = mod->mem[MOD_INIT_RODATA].base; 3124 3125 do_mod_ctors(mod); 3126 /* Start the module */ 3127 if (mod->init != NULL) 3128 ret = do_one_initcall(mod->init); 3129 if (ret < 0) { 3130 /* 3131 * -EEXIST is reserved by [f]init_module() to signal to userspace that 3132 * a module with this name is already loaded. Use something else if the 3133 * module itself is returning that. 3134 */ 3135 if (ret == -EEXIST) 3136 ret = -EBUSY; 3137 3138 goto fail_free_freeinit; 3139 } 3140 if (ret > 0) 3141 pr_warn("%s: init suspiciously returned %d, it should follow 0/-E convention\n", 3142 mod->name, ret); 3143 3144 /* Now it's a first class citizen! */ 3145 mod->state = MODULE_STATE_LIVE; 3146 blocking_notifier_call_chain(&module_notify_list, 3147 MODULE_STATE_LIVE, mod); 3148 3149 /* Delay uevent until module has finished its init routine */ 3150 kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD); 3151 3152 /* 3153 * We need to finish all async code before the module init sequence 3154 * is done. This has potential to deadlock if synchronous module 3155 * loading is requested from async (which is not allowed!). 3156 * 3157 * See commit 0fdff3ec6d87 ("async, kmod: warn on synchronous 3158 * request_module() from async workers") for more details. 3159 */ 3160 if (!mod->async_probe_requested) 3161 async_synchronize_full(); 3162 3163 ftrace_free_mem(mod, mod->mem[MOD_INIT_TEXT].base, 3164 mod->mem[MOD_INIT_TEXT].base + mod->mem[MOD_INIT_TEXT].size); 3165 mutex_lock(&module_mutex); 3166 /* Drop initial reference. */ 3167 module_put(mod); 3168 trim_init_extable(mod); 3169 #ifdef CONFIG_KALLSYMS 3170 /* Switch to core kallsyms now init is done: kallsyms may be walking! */ 3171 rcu_assign_pointer(mod->kallsyms, &mod->core_kallsyms); 3172 #endif 3173 ret = module_enable_rodata_ro_after_init(mod); 3174 if (ret) 3175 pr_warn("%s: module_enable_rodata_ro_after_init() returned %d, " 3176 "ro_after_init data might still be writable\n", 3177 mod->name, ret); 3178 3179 mod_tree_remove_init(mod); 3180 module_arch_freeing_init(mod); 3181 for_class_mod_mem_type(type, init) { 3182 mod->mem[type].base = NULL; 3183 mod->mem[type].size = 0; 3184 } 3185 3186 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES 3187 /* .BTF is not SHF_ALLOC and will get removed, so sanitize pointers */ 3188 mod->btf_data = NULL; 3189 mod->btf_base_data = NULL; 3190 #endif 3191 /* 3192 * We want to free module_init, but be aware that kallsyms may be 3193 * walking this within an RCU read section. In all the failure paths, we 3194 * call synchronize_rcu(), but we don't want to slow down the success 3195 * path. execmem_free() cannot be called in an interrupt, so do the 3196 * work and call synchronize_rcu() in a work queue. 3197 * 3198 * Note that execmem_alloc() on most architectures creates W+X page 3199 * mappings which won't be cleaned up until do_free_init() runs. Any 3200 * code such as mark_rodata_ro() which depends on those mappings to 3201 * be cleaned up needs to sync with the queued work by invoking 3202 * flush_module_init_free_work(). 3203 */ 3204 if (llist_add(&freeinit->node, &init_free_list)) 3205 schedule_work(&init_free_wq); 3206 3207 mutex_unlock(&module_mutex); 3208 wake_up_all(&module_wq); 3209 3210 mod_stat_add_long(text_size, &total_text_size); 3211 mod_stat_add_long(total_size, &total_mod_size); 3212 3213 mod_stat_inc(&modcount); 3214 3215 return 0; 3216 3217 fail_free_freeinit: 3218 kfree(freeinit); 3219 fail: 3220 /* Try to protect us from buggy refcounters. */ 3221 mod->state = MODULE_STATE_GOING; 3222 synchronize_rcu(); 3223 module_put(mod); 3224 blocking_notifier_call_chain(&module_notify_list, 3225 MODULE_STATE_GOING, mod); 3226 klp_module_going(mod); 3227 ftrace_release_mod(mod); 3228 free_module(mod); 3229 wake_up_all(&module_wq); 3230 3231 return ret; 3232 } 3233 3234 static int may_init_module(void) 3235 { 3236 if (!capable(CAP_SYS_MODULE) || modules_disabled) 3237 return -EPERM; 3238 3239 return 0; 3240 } 3241 3242 /* Is this module of this name done loading? No locks held. */ 3243 static bool finished_loading(const char *name) 3244 { 3245 struct module *mod; 3246 bool ret; 3247 3248 /* 3249 * The module_mutex should not be a heavily contended lock; 3250 * if we get the occasional sleep here, we'll go an extra iteration 3251 * in the wait_event_interruptible(), which is harmless. 3252 */ 3253 sched_annotate_sleep(); 3254 mutex_lock(&module_mutex); 3255 mod = find_module_all(name, strlen(name), true); 3256 ret = !mod || mod->state == MODULE_STATE_LIVE 3257 || mod->state == MODULE_STATE_GOING; 3258 mutex_unlock(&module_mutex); 3259 3260 return ret; 3261 } 3262 3263 /* Must be called with module_mutex held */ 3264 static int module_patient_check_exists(const char *name, 3265 enum fail_dup_mod_reason reason) 3266 { 3267 struct module *old; 3268 int err = 0; 3269 3270 old = find_module_all(name, strlen(name), true); 3271 if (old == NULL) 3272 return 0; 3273 3274 if (old->state == MODULE_STATE_COMING || 3275 old->state == MODULE_STATE_UNFORMED) { 3276 /* Wait in case it fails to load. */ 3277 mutex_unlock(&module_mutex); 3278 err = wait_event_interruptible(module_wq, 3279 finished_loading(name)); 3280 mutex_lock(&module_mutex); 3281 if (err) 3282 return err; 3283 3284 /* The module might have gone in the meantime. */ 3285 old = find_module_all(name, strlen(name), true); 3286 } 3287 3288 if (try_add_failed_module(name, reason)) 3289 pr_warn("Could not add fail-tracking for module: %s\n", name); 3290 3291 /* 3292 * We are here only when the same module was being loaded. Do 3293 * not try to load it again right now. It prevents long delays 3294 * caused by serialized module load failures. It might happen 3295 * when more devices of the same type trigger load of 3296 * a particular module. 3297 */ 3298 if (old && old->state == MODULE_STATE_LIVE) 3299 return -EEXIST; 3300 return -EBUSY; 3301 } 3302 3303 /* 3304 * We try to place it in the list now to make sure it's unique before 3305 * we dedicate too many resources. In particular, temporary percpu 3306 * memory exhaustion. 3307 */ 3308 static int add_unformed_module(struct module *mod) 3309 { 3310 int err; 3311 3312 mod->state = MODULE_STATE_UNFORMED; 3313 3314 mutex_lock(&module_mutex); 3315 err = module_patient_check_exists(mod->name, FAIL_DUP_MOD_LOAD); 3316 if (err) 3317 goto out; 3318 3319 mod_update_bounds(mod); 3320 list_add_rcu(&mod->list, &modules); 3321 mod_tree_insert(mod); 3322 err = 0; 3323 3324 out: 3325 mutex_unlock(&module_mutex); 3326 return err; 3327 } 3328 3329 static int complete_formation(struct module *mod, struct load_info *info) 3330 { 3331 int err; 3332 3333 mutex_lock(&module_mutex); 3334 3335 /* Find duplicate symbols (must be called under lock). */ 3336 err = verify_exported_symbols(mod); 3337 if (err < 0) 3338 goto out; 3339 3340 /* These rely on module_mutex for list integrity. */ 3341 module_bug_finalize(info->hdr, info->sechdrs, mod); 3342 module_cfi_finalize(info->hdr, info->sechdrs, mod); 3343 3344 err = module_enable_rodata_ro(mod); 3345 if (err) 3346 goto out_strict_rwx; 3347 err = module_enable_data_nx(mod); 3348 if (err) 3349 goto out_strict_rwx; 3350 err = module_enable_text_rox(mod); 3351 if (err) 3352 goto out_strict_rwx; 3353 3354 /* 3355 * Mark state as coming so strong_try_module_get() ignores us, 3356 * but kallsyms etc. can see us. 3357 */ 3358 mod->state = MODULE_STATE_COMING; 3359 mutex_unlock(&module_mutex); 3360 3361 return 0; 3362 3363 out_strict_rwx: 3364 module_bug_cleanup(mod); 3365 out: 3366 mutex_unlock(&module_mutex); 3367 return err; 3368 } 3369 3370 static int prepare_coming_module(struct module *mod) 3371 { 3372 int err; 3373 3374 ftrace_module_enable(mod); 3375 err = klp_module_coming(mod); 3376 if (err) 3377 return err; 3378 3379 err = blocking_notifier_call_chain_robust(&module_notify_list, 3380 MODULE_STATE_COMING, MODULE_STATE_GOING, mod); 3381 err = notifier_to_errno(err); 3382 if (err) 3383 klp_module_going(mod); 3384 3385 return err; 3386 } 3387 3388 static int unknown_module_param_cb(char *param, char *val, const char *modname, 3389 void *arg) 3390 { 3391 struct module *mod = arg; 3392 int ret; 3393 3394 if (strcmp(param, "async_probe") == 0) { 3395 if (kstrtobool(val, &mod->async_probe_requested)) 3396 mod->async_probe_requested = true; 3397 return 0; 3398 } 3399 3400 /* Check for magic 'dyndbg' arg */ 3401 ret = ddebug_dyndbg_module_param_cb(param, val, modname); 3402 if (ret != 0) 3403 pr_warn("%s: unknown parameter '%s' ignored\n", modname, param); 3404 return 0; 3405 } 3406 3407 /* Module within temporary copy, this doesn't do any allocation */ 3408 static int early_mod_check(struct load_info *info, int flags) 3409 { 3410 int err; 3411 3412 /* 3413 * Now that we know we have the correct module name, check 3414 * if it's blacklisted. 3415 */ 3416 if (blacklisted(info->name)) { 3417 pr_err("Module %s is blacklisted\n", info->name); 3418 return -EPERM; 3419 } 3420 3421 err = rewrite_section_headers(info, flags); 3422 if (err) 3423 return err; 3424 3425 /* Check module struct version now, before we try to use module. */ 3426 if (!check_modstruct_version(info, info->mod)) 3427 return -ENOEXEC; 3428 3429 err = check_modinfo(info->mod, info, flags); 3430 if (err) 3431 return err; 3432 3433 mutex_lock(&module_mutex); 3434 err = module_patient_check_exists(info->mod->name, FAIL_DUP_MOD_BECOMING); 3435 mutex_unlock(&module_mutex); 3436 3437 return err; 3438 } 3439 3440 /* 3441 * Allocate and load the module: note that size of section 0 is always 3442 * zero, and we rely on this for optional sections. 3443 */ 3444 static int load_module(struct load_info *info, const char __user *uargs, 3445 int flags) 3446 { 3447 struct module *mod; 3448 bool module_allocated = false; 3449 long err = 0; 3450 char *args = NULL, *after_dashes; 3451 3452 /* 3453 * Do the signature check (if any) first. All that 3454 * the signature check needs is info->len, it does 3455 * not need any of the section info. That can be 3456 * set up later. This will minimize the chances 3457 * of a corrupt module causing problems before 3458 * we even get to the signature check. 3459 * 3460 * The check will also adjust info->len by stripping 3461 * off the sig length at the end of the module, making 3462 * checks against info->len more correct. 3463 */ 3464 err = module_sig_check(info, flags); 3465 if (err) 3466 goto free_copy; 3467 3468 /* 3469 * Do basic sanity checks against the ELF header and 3470 * sections. Cache useful sections and set the 3471 * info->mod to the userspace passed struct module. 3472 */ 3473 err = elf_validity_cache_copy(info, flags); 3474 if (err) 3475 goto free_copy; 3476 3477 err = early_mod_check(info, flags); 3478 if (err) 3479 goto free_copy; 3480 3481 /* Figure out module layout, and allocate all the memory. */ 3482 mod = layout_and_allocate(info, flags); 3483 if (IS_ERR(mod)) { 3484 err = PTR_ERR(mod); 3485 goto free_copy; 3486 } 3487 3488 module_allocated = true; 3489 3490 audit_log_kern_module(info->name); 3491 3492 /* Reserve our place in the list. */ 3493 err = add_unformed_module(mod); 3494 if (err) 3495 goto free_module; 3496 3497 /* 3498 * We are tainting your kernel if your module gets into 3499 * the modules linked list somehow. 3500 */ 3501 module_augment_kernel_taints(mod, info); 3502 3503 /* To avoid stressing percpu allocator, do this once we're unique. */ 3504 err = percpu_modalloc(mod, info); 3505 if (err) 3506 goto unlink_mod; 3507 3508 /* Now module is in final location, initialize linked lists, etc. */ 3509 err = module_unload_init(mod); 3510 if (err) 3511 goto unlink_mod; 3512 3513 init_param_lock(mod); 3514 3515 /* 3516 * Now we've got everything in the final locations, we can 3517 * find optional sections. 3518 */ 3519 err = find_module_sections(mod, info); 3520 if (err) 3521 goto free_unload; 3522 3523 err = check_export_symbol_sections(mod); 3524 if (err) 3525 goto free_unload; 3526 3527 /* Set up MODINFO_ATTR fields */ 3528 err = setup_modinfo(mod, info); 3529 if (err) 3530 goto free_modinfo; 3531 3532 /* Fix up syms, so that st_value is a pointer to location. */ 3533 err = simplify_symbols(mod, info); 3534 if (err < 0) 3535 goto free_modinfo; 3536 3537 err = apply_relocations(mod, info); 3538 if (err < 0) 3539 goto free_modinfo; 3540 3541 err = post_relocation(mod, info); 3542 if (err < 0) 3543 goto free_modinfo; 3544 3545 flush_module_icache(mod); 3546 3547 /* Now copy in args */ 3548 args = strndup_user(uargs, ~0UL >> 1); 3549 if (IS_ERR(args)) { 3550 err = PTR_ERR(args); 3551 goto free_arch_cleanup; 3552 } 3553 3554 init_build_id(mod, info); 3555 3556 /* Ftrace init must be called in the MODULE_STATE_UNFORMED state */ 3557 ftrace_module_init(mod); 3558 3559 /* Finally it's fully formed, ready to start executing. */ 3560 err = complete_formation(mod, info); 3561 if (err) 3562 goto ddebug_cleanup; 3563 3564 err = prepare_coming_module(mod); 3565 if (err) 3566 goto bug_cleanup; 3567 3568 mod->async_probe_requested = async_probe; 3569 3570 /* Module is ready to execute: parsing args may do that. */ 3571 after_dashes = parse_args(mod->name, args, mod->kp, mod->num_kp, 3572 -32768, 32767, mod, 3573 unknown_module_param_cb); 3574 if (IS_ERR(after_dashes)) { 3575 err = PTR_ERR(after_dashes); 3576 goto coming_cleanup; 3577 } else if (after_dashes) { 3578 pr_warn("%s: parameters '%s' after `--' ignored\n", 3579 mod->name, after_dashes); 3580 } 3581 kfree(args); 3582 args = NULL; 3583 3584 /* Link in to sysfs. */ 3585 err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp); 3586 if (err < 0) 3587 goto coming_cleanup; 3588 3589 if (is_livepatch_module(mod)) { 3590 err = copy_module_elf(mod, info); 3591 if (err < 0) 3592 goto sysfs_cleanup; 3593 } 3594 3595 err = codetag_load_module(mod); 3596 if (err) 3597 goto livepatch_cleanup; 3598 3599 /* Get rid of temporary copy. */ 3600 free_copy(info, flags); 3601 3602 /* Done! */ 3603 trace_module_load(mod); 3604 3605 return do_init_module(mod); 3606 3607 livepatch_cleanup: 3608 if (is_livepatch_module(mod)) 3609 free_module_elf(mod); 3610 sysfs_cleanup: 3611 mod_sysfs_teardown(mod); 3612 coming_cleanup: 3613 mod->state = MODULE_STATE_GOING; 3614 module_destroy_params(mod->kp, mod->num_kp); 3615 blocking_notifier_call_chain(&module_notify_list, 3616 MODULE_STATE_GOING, mod); 3617 klp_module_going(mod); 3618 bug_cleanup: 3619 mod->state = MODULE_STATE_GOING; 3620 /* module_bug_cleanup needs module_mutex protection */ 3621 mutex_lock(&module_mutex); 3622 module_bug_cleanup(mod); 3623 mutex_unlock(&module_mutex); 3624 3625 ddebug_cleanup: 3626 ftrace_release_mod(mod); 3627 synchronize_rcu(); 3628 kfree(args); 3629 free_arch_cleanup: 3630 module_arch_cleanup(mod); 3631 free_modinfo: 3632 free_modinfo(mod); 3633 free_unload: 3634 module_unload_free(mod); 3635 unlink_mod: 3636 mutex_lock(&module_mutex); 3637 /* Unlink carefully: kallsyms could be walking list. */ 3638 list_del_rcu(&mod->list); 3639 mod_tree_remove(mod); 3640 wake_up_all(&module_wq); 3641 /* Wait for RCU-sched synchronizing before releasing mod->list. */ 3642 synchronize_rcu(); 3643 mutex_unlock(&module_mutex); 3644 free_module: 3645 mod_stat_bump_invalid(info, flags); 3646 module_memory_restore_rox(mod); 3647 module_deallocate(mod, info); 3648 free_copy: 3649 /* 3650 * The info->len is always set. We distinguish between 3651 * failures once the proper module was allocated and 3652 * before that. 3653 */ 3654 if (!module_allocated) { 3655 audit_log_kern_module(info->name ? info->name : "?"); 3656 mod_stat_bump_becoming(info, flags); 3657 } 3658 free_copy(info, flags); 3659 return err; 3660 } 3661 3662 SYSCALL_DEFINE3(init_module, void __user *, umod, 3663 unsigned long, len, const char __user *, uargs) 3664 { 3665 int err; 3666 struct load_info info = { }; 3667 3668 err = may_init_module(); 3669 if (err) 3670 return err; 3671 3672 pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n", 3673 umod, len, uargs); 3674 3675 err = copy_module_from_user(umod, len, &info); 3676 if (err) { 3677 mod_stat_inc(&failed_kreads); 3678 mod_stat_add_long(len, &invalid_kread_bytes); 3679 return err; 3680 } 3681 3682 return load_module(&info, uargs, 0); 3683 } 3684 3685 struct idempotent { 3686 const void *cookie; 3687 struct hlist_node entry; 3688 struct completion complete; 3689 int ret; 3690 }; 3691 3692 #define IDEM_HASH_BITS 8 3693 static struct hlist_head idem_hash[1 << IDEM_HASH_BITS]; 3694 static DEFINE_SPINLOCK(idem_lock); 3695 3696 static bool idempotent(struct idempotent *u, const void *cookie) 3697 { 3698 int hash = hash_ptr(cookie, IDEM_HASH_BITS); 3699 struct hlist_head *head = idem_hash + hash; 3700 struct idempotent *existing; 3701 bool first; 3702 3703 u->ret = -EINTR; 3704 u->cookie = cookie; 3705 init_completion(&u->complete); 3706 3707 spin_lock(&idem_lock); 3708 first = true; 3709 hlist_for_each_entry(existing, head, entry) { 3710 if (existing->cookie != cookie) 3711 continue; 3712 first = false; 3713 break; 3714 } 3715 hlist_add_head(&u->entry, idem_hash + hash); 3716 spin_unlock(&idem_lock); 3717 3718 return !first; 3719 } 3720 3721 /* 3722 * We were the first one with 'cookie' on the list, and we ended 3723 * up completing the operation. We now need to walk the list, 3724 * remove everybody - which includes ourselves - fill in the return 3725 * value, and then complete the operation. 3726 */ 3727 static int idempotent_complete(struct idempotent *u, int ret) 3728 { 3729 const void *cookie = u->cookie; 3730 int hash = hash_ptr(cookie, IDEM_HASH_BITS); 3731 struct hlist_head *head = idem_hash + hash; 3732 struct hlist_node *next; 3733 struct idempotent *pos; 3734 3735 spin_lock(&idem_lock); 3736 hlist_for_each_entry_safe(pos, next, head, entry) { 3737 if (pos->cookie != cookie) 3738 continue; 3739 hlist_del_init(&pos->entry); 3740 pos->ret = ret; 3741 complete(&pos->complete); 3742 } 3743 spin_unlock(&idem_lock); 3744 return ret; 3745 } 3746 3747 /* 3748 * Wait for the idempotent worker. 3749 * 3750 * If we get interrupted, we need to remove ourselves from the 3751 * the idempotent list, and the completion may still come in. 3752 * 3753 * The 'idem_lock' protects against the race, and 'idem.ret' was 3754 * initialized to -EINTR and is thus always the right return 3755 * value even if the idempotent work then completes between 3756 * the wait_for_completion and the cleanup. 3757 */ 3758 static int idempotent_wait_for_completion(struct idempotent *u) 3759 { 3760 if (wait_for_completion_interruptible(&u->complete)) { 3761 spin_lock(&idem_lock); 3762 if (!hlist_unhashed(&u->entry)) 3763 hlist_del(&u->entry); 3764 spin_unlock(&idem_lock); 3765 } 3766 return u->ret; 3767 } 3768 3769 static int init_module_from_file(struct file *f, const char __user * uargs, int flags) 3770 { 3771 bool compressed = !!(flags & MODULE_INIT_COMPRESSED_FILE); 3772 struct load_info info = { }; 3773 void *buf = NULL; 3774 int len; 3775 int err; 3776 3777 len = kernel_read_file(f, 0, &buf, INT_MAX, NULL, 3778 compressed ? READING_MODULE_COMPRESSED : 3779 READING_MODULE); 3780 if (len < 0) { 3781 mod_stat_inc(&failed_kreads); 3782 return len; 3783 } 3784 3785 if (compressed) { 3786 err = module_decompress(&info, buf, len); 3787 vfree(buf); /* compressed data is no longer needed */ 3788 if (err) { 3789 mod_stat_inc(&failed_decompress); 3790 mod_stat_add_long(len, &invalid_decompress_bytes); 3791 return err; 3792 } 3793 err = security_kernel_post_read_file(f, (char *)info.hdr, info.len, 3794 READING_MODULE); 3795 if (err) { 3796 mod_stat_inc(&failed_kreads); 3797 free_copy(&info, flags); 3798 return err; 3799 } 3800 } else { 3801 info.hdr = buf; 3802 info.len = len; 3803 } 3804 3805 return load_module(&info, uargs, flags); 3806 } 3807 3808 static int idempotent_init_module(struct file *f, const char __user * uargs, int flags) 3809 { 3810 struct idempotent idem; 3811 3812 if (!(f->f_mode & FMODE_READ)) 3813 return -EBADF; 3814 3815 /* Are we the winners of the race and get to do this? */ 3816 if (!idempotent(&idem, file_inode(f))) { 3817 int ret = init_module_from_file(f, uargs, flags); 3818 return idempotent_complete(&idem, ret); 3819 } 3820 3821 /* 3822 * Somebody else won the race and is loading the module. 3823 */ 3824 return idempotent_wait_for_completion(&idem); 3825 } 3826 3827 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags) 3828 { 3829 int err = may_init_module(); 3830 if (err) 3831 return err; 3832 3833 pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags); 3834 3835 if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS 3836 |MODULE_INIT_IGNORE_VERMAGIC 3837 |MODULE_INIT_COMPRESSED_FILE)) 3838 return -EINVAL; 3839 3840 CLASS(fd, f)(fd); 3841 if (fd_empty(f)) 3842 return -EBADF; 3843 return idempotent_init_module(fd_file(f), uargs, flags); 3844 } 3845 3846 /* Keep in sync with MODULE_FLAGS_BUF_SIZE !!! */ 3847 char *module_flags(struct module *mod, char *buf, bool show_state) 3848 { 3849 int bx = 0; 3850 3851 BUG_ON(mod->state == MODULE_STATE_UNFORMED); 3852 if (!mod->taints && !show_state) 3853 goto out; 3854 if (mod->taints || 3855 mod->state == MODULE_STATE_GOING || 3856 mod->state == MODULE_STATE_COMING) { 3857 buf[bx++] = '('; 3858 bx += module_flags_taint(mod->taints, buf + bx); 3859 /* Show a - for module-is-being-unloaded */ 3860 if (mod->state == MODULE_STATE_GOING && show_state) 3861 buf[bx++] = '-'; 3862 /* Show a + for module-is-being-loaded */ 3863 if (mod->state == MODULE_STATE_COMING && show_state) 3864 buf[bx++] = '+'; 3865 buf[bx++] = ')'; 3866 } 3867 out: 3868 buf[bx] = '\0'; 3869 3870 return buf; 3871 } 3872 3873 /* Given an address, look for it in the module exception tables. */ 3874 const struct exception_table_entry *search_module_extables(unsigned long addr) 3875 { 3876 struct module *mod; 3877 3878 guard(rcu)(); 3879 mod = __module_address(addr); 3880 if (!mod) 3881 return NULL; 3882 3883 if (!mod->num_exentries) 3884 return NULL; 3885 /* 3886 * The address passed here belongs to a module that is currently 3887 * invoked (we are running inside it). Therefore its module::refcnt 3888 * needs already be >0 to ensure that it is not removed at this stage. 3889 * All other user need to invoke this function within a RCU read 3890 * section. 3891 */ 3892 return search_extable(mod->extable, mod->num_exentries, addr); 3893 } 3894 3895 /** 3896 * is_module_address() - is this address inside a module? 3897 * @addr: the address to check. 3898 * 3899 * See is_module_text_address() if you simply want to see if the address 3900 * is code (not data). 3901 */ 3902 bool is_module_address(unsigned long addr) 3903 { 3904 guard(rcu)(); 3905 return __module_address(addr) != NULL; 3906 } 3907 3908 /** 3909 * __module_address() - get the module which contains an address. 3910 * @addr: the address. 3911 * 3912 * Must be called within RCU read section or module mutex held so that 3913 * module doesn't get freed during this. 3914 */ 3915 struct module *__module_address(unsigned long addr) 3916 { 3917 struct module *mod; 3918 3919 if (addr >= mod_tree.addr_min && addr <= mod_tree.addr_max) 3920 goto lookup; 3921 3922 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC 3923 if (addr >= mod_tree.data_addr_min && addr <= mod_tree.data_addr_max) 3924 goto lookup; 3925 #endif 3926 3927 return NULL; 3928 3929 lookup: 3930 mod = mod_find(addr, &mod_tree); 3931 if (mod) { 3932 BUG_ON(!within_module(addr, mod)); 3933 if (mod->state == MODULE_STATE_UNFORMED) 3934 mod = NULL; 3935 } 3936 return mod; 3937 } 3938 3939 /** 3940 * is_module_text_address() - is this address inside module code? 3941 * @addr: the address to check. 3942 * 3943 * See is_module_address() if you simply want to see if the address is 3944 * anywhere in a module. See kernel_text_address() for testing if an 3945 * address corresponds to kernel or module code. 3946 */ 3947 bool is_module_text_address(unsigned long addr) 3948 { 3949 guard(rcu)(); 3950 return __module_text_address(addr) != NULL; 3951 } 3952 3953 void module_for_each_mod(int(*func)(struct module *mod, void *data), void *data) 3954 { 3955 struct module *mod; 3956 3957 guard(rcu)(); 3958 list_for_each_entry_rcu(mod, &modules, list) { 3959 if (mod->state == MODULE_STATE_UNFORMED) 3960 continue; 3961 if (func(mod, data)) 3962 break; 3963 } 3964 } 3965 3966 /** 3967 * __module_text_address() - get the module whose code contains an address. 3968 * @addr: the address. 3969 * 3970 * Must be called within RCU read section or module mutex held so that 3971 * module doesn't get freed during this. 3972 */ 3973 struct module *__module_text_address(unsigned long addr) 3974 { 3975 struct module *mod = __module_address(addr); 3976 if (mod) { 3977 /* Make sure it's within the text section. */ 3978 if (!within_module_mem_type(addr, mod, MOD_TEXT) && 3979 !within_module_mem_type(addr, mod, MOD_INIT_TEXT)) 3980 mod = NULL; 3981 } 3982 return mod; 3983 } 3984 3985 /* Don't grab lock, we're oopsing. */ 3986 void print_modules(void) 3987 { 3988 struct module *mod; 3989 char buf[MODULE_FLAGS_BUF_SIZE]; 3990 3991 printk(KERN_DEFAULT "Modules linked in:"); 3992 /* Most callers should already have preempt disabled, but make sure */ 3993 guard(rcu)(); 3994 list_for_each_entry_rcu(mod, &modules, list) { 3995 if (mod->state == MODULE_STATE_UNFORMED) 3996 continue; 3997 pr_cont(" %s%s", mod->name, module_flags(mod, buf, true)); 3998 } 3999 4000 print_unloaded_tainted_modules(); 4001 if (last_unloaded_module.name[0]) 4002 pr_cont(" [last unloaded: %s%s]", last_unloaded_module.name, 4003 last_unloaded_module.taints); 4004 pr_cont("\n"); 4005 } 4006 4007 #ifdef CONFIG_MODULE_DEBUGFS 4008 struct dentry *mod_debugfs_root; 4009 4010 static int module_debugfs_init(void) 4011 { 4012 mod_debugfs_root = debugfs_create_dir("modules", NULL); 4013 return 0; 4014 } 4015 module_init(module_debugfs_init); 4016 #endif 4017