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