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