1 // SPDX-License-Identifier: GPL-2.0-or-later 2 #define _GNU_SOURCE /* memmem() */ 3 #include <subcmd/parse-options.h> 4 #include <stdlib.h> 5 #include <string.h> 6 #include <libgen.h> 7 #include <stdio.h> 8 #include <ctype.h> 9 10 #include <objtool/objtool.h> 11 #include <objtool/warn.h> 12 #include <objtool/arch.h> 13 #include <objtool/klp.h> 14 #include <objtool/util.h> 15 #include <arch/special.h> 16 17 #include <linux/align.h> 18 #include <linux/objtool_types.h> 19 #include <linux/livepatch_external.h> 20 #include <linux/stringify.h> 21 #include <linux/string.h> 22 #include <linux/jhash.h> 23 24 #define sizeof_field(TYPE, MEMBER) sizeof((((TYPE *)0)->MEMBER)) 25 26 struct elfs { 27 struct elf *orig, *patched, *out; 28 const char *modname; 29 }; 30 31 struct export { 32 struct hlist_node hash; 33 char *mod, *sym; 34 }; 35 36 bool debug, debug_correlate, debug_clone; 37 int indent; 38 39 static const char * const klp_diff_usage[] = { 40 "objtool klp diff [<options>] <in1.o> <in2.o> <out.o>", 41 NULL, 42 }; 43 44 static const struct option klp_diff_options[] = { 45 OPT_GROUP("Options:"), 46 OPT_BOOLEAN('d', "debug", &debug, "enable all debug output"), 47 OPT_BOOLEAN(0, "debug-correlate", &debug_correlate, "enable correlation debug output"), 48 OPT_BOOLEAN(0, "debug-clone", &debug_clone, "enable cloning debug output"), 49 OPT_END(), 50 }; 51 52 static DEFINE_HASHTABLE(exports, 15); 53 54 static char *escape_str(const char *orig) 55 { 56 size_t len = 0; 57 const char *a; 58 char *b, *new; 59 60 for (a = orig; *a; a++) { 61 switch (*a) { 62 case '\001': len += 5; break; 63 case '\n': 64 case '\t': len += 2; break; 65 default: len++; 66 } 67 } 68 69 new = malloc(len + 1); 70 if (!new) 71 return NULL; 72 73 for (a = orig, b = new; *a; a++) { 74 switch (*a) { 75 case '\001': memcpy(b, "<SOH>", 5); b += 5; break; 76 case '\n': *b++ = '\\'; *b++ = 'n'; break; 77 case '\t': *b++ = '\\'; *b++ = 't'; break; 78 default: *b++ = *a; 79 } 80 } 81 82 *b = '\0'; 83 return new; 84 } 85 86 /* 87 * Convert a build-tree object path to a runtime module name: strip 88 * directory components, replace '-' with '_', and remove file 89 * extensions. Examples: 90 * 91 * "arch/x86/kvm/kvm" -> "kvm" 92 * "arch/x86/kvm/kvm-intel" -> "kvm_intel". 93 * 94 * Used by read_exports() to normalize Module.symvers entries and by 95 * __find_modname() as a fallback when .modinfo lacks a "name=" tag. 96 */ 97 static char *normalize_modname(char *name) 98 { 99 char *slash = strrchr(name, '/'); 100 101 if (slash) 102 name = slash + 1; 103 104 for (char *c = name; *c; c++) { 105 if (*c == '-') 106 *c = '_'; 107 else if (*c == '.') { 108 *c = '\0'; 109 break; 110 } 111 } 112 return name; 113 } 114 115 static int read_exports(void) 116 { 117 const char *symvers = "Module.symvers"; 118 char line[1024], *path = NULL; 119 unsigned int line_num = 1; 120 FILE *file; 121 122 file = fopen(symvers, "r"); 123 if (!file) { 124 path = top_level_dir(symvers); 125 if (!path) { 126 ERROR("can't open '%s', \"objtool diff\" should be run from the kernel tree", symvers); 127 return -1; 128 } 129 130 file = fopen(path, "r"); 131 if (!file) { 132 ERROR_GLIBC("fopen"); 133 return -1; 134 } 135 } 136 137 while (fgets(line, 1024, file)) { 138 char *sym, *mod, *type; 139 struct export *export; 140 141 sym = strchr(line, '\t'); 142 if (!sym) { 143 ERROR("malformed Module.symvers (sym) at line %d", line_num); 144 return -1; 145 } 146 147 *sym++ = '\0'; 148 149 mod = strchr(sym, '\t'); 150 if (!mod) { 151 ERROR("malformed Module.symvers (mod) at line %d", line_num); 152 return -1; 153 } 154 155 *mod++ = '\0'; 156 157 type = strchr(mod, '\t'); 158 if (!type) { 159 ERROR("malformed Module.symvers (type) at line %d", line_num); 160 return -1; 161 } 162 163 *type++ = '\0'; 164 165 if (*sym == '\0' || *mod == '\0') { 166 ERROR("malformed Module.symvers at line %d", line_num); 167 return -1; 168 } 169 170 export = calloc(1, sizeof(*export)); 171 if (!export) { 172 ERROR_GLIBC("calloc"); 173 return -1; 174 } 175 176 export->mod = strdup(mod); 177 if (!export->mod) { 178 ERROR_GLIBC("strdup"); 179 return -1; 180 } 181 182 if (strcmp(export->mod, "vmlinux")) 183 export->mod = normalize_modname(export->mod); 184 185 export->sym = strdup(sym); 186 if (!export->sym) { 187 ERROR_GLIBC("strdup"); 188 return -1; 189 } 190 191 hash_add(exports, &export->hash, str_hash(sym)); 192 } 193 194 free(path); 195 fclose(file); 196 197 return 0; 198 } 199 200 static int read_sym_checksums(struct elf *elf) 201 { 202 struct section *sec; 203 204 sec = find_section_by_name(elf, ".discard.sym_checksum"); 205 if (!sec) { 206 ERROR("'%s' missing .discard.sym_checksum section, file not processed by 'objtool klp checksum'?", 207 elf->name); 208 return -1; 209 } 210 211 if (!sec->rsec) { 212 ERROR("missing reloc section for .discard.sym_checksum"); 213 return -1; 214 } 215 216 if (sec_size(sec) % sizeof(struct sym_checksum)) { 217 ERROR("struct sym_checksum size mismatch"); 218 return -1; 219 } 220 221 for (int i = 0; i < sec_size(sec) / sizeof(struct sym_checksum); i++) { 222 struct sym_checksum *sym_checksum; 223 struct reloc *reloc; 224 struct symbol *sym; 225 226 sym_checksum = (struct sym_checksum *)sec->data->d_buf + i; 227 228 reloc = find_reloc_by_dest(elf, sec, i * sizeof(*sym_checksum)); 229 if (!reloc) { 230 ERROR("can't find reloc for sym_checksum[%d]", i); 231 return -1; 232 } 233 234 sym = reloc->sym; 235 236 if (is_sec_sym(sym)) { 237 ERROR("not sure how to handle section %s", sym->name); 238 return -1; 239 } 240 241 if (is_func_sym(sym) || is_object_sym(sym)) 242 sym->csum.checksum = sym_checksum->checksum; 243 } 244 245 return 0; 246 } 247 248 static struct symbol *first_file_symbol(struct elf *elf) 249 { 250 struct symbol *sym; 251 252 for_each_sym(elf, sym) { 253 if (is_file_sym(sym)) 254 return sym; 255 } 256 257 return NULL; 258 } 259 260 static struct symbol *next_file_symbol(struct elf *elf, struct symbol *sym) 261 { 262 for_each_sym_continue(elf, sym) { 263 if (is_file_sym(sym)) 264 return sym; 265 } 266 267 return NULL; 268 } 269 270 /* 271 * Certain static local variables should never be correlated. They will be 272 * used in place rather than referencing the originals. 273 */ 274 static bool is_uncorrelated_static_local(struct symbol *sym) 275 { 276 static const char * const vars[] = { 277 "__already_done", 278 "__func__", 279 "__key", 280 "__warned", 281 "_entry", 282 "_entry_ptr", 283 "_rs", 284 "descriptor", 285 "CSWTCH", 286 }; 287 const char *dot; 288 289 if (!is_object_sym(sym) || !is_local_sym(sym)) 290 return false; 291 292 /* WARN_ONCE, etc */ 293 if (!strcmp(sym->sec->name, ".data..once")) 294 return true; 295 296 dot = strchr(sym->name, '.'); 297 if (!dot) 298 return false; 299 300 for (int i = 0; i < ARRAY_SIZE(vars); i++) { 301 size_t len = strlen(vars[i]); 302 303 /* GCC: <var>.<id> */ 304 if (strstarts(sym->name, vars[i]) && (sym->name[len] == '.')) 305 return true; 306 307 /* Clang: <func>.<var>[.<id>] */ 308 if (strstarts(dot + 1, vars[i]) && 309 (dot[1 + len] == '.' || dot[1 + len] == '\0')) 310 return true; 311 } 312 313 return false; 314 } 315 316 /* 317 * .L symbols are assembler-local labels not present in kallsyms. They must 318 * never become KLP relocations; instead their data is cloned into the patch 319 * module. This covers .Ltmp* (Clang temp labels), .L__const.* (Clang local 320 * constants), and any other assembler-local pattern. 321 */ 322 static bool is_local_label(struct symbol *sym) 323 { 324 return strstarts(sym->name, ".L"); 325 } 326 327 static bool is_special_section(struct section *sec) 328 { 329 static const char * const specials[] = { 330 ".altinstructions", 331 ".kcfi_traps", 332 ".smp_locks", 333 "__bug_table", 334 "__ex_table", 335 "__jump_table", 336 "__mcount_loc", 337 338 /* 339 * Extract .static_call_sites here to inherit non-module 340 * preferential treatment. The later static call processing 341 * during klp module build will be skipped when it sees this 342 * section already exists. 343 */ 344 ".static_call_sites", 345 }; 346 347 static const char * const non_special_discards[] = { 348 ".discard.addressable", 349 ".discard.sym_checksum", 350 }; 351 352 if (is_text_sec(sec)) 353 return false; 354 355 for (int i = 0; i < ARRAY_SIZE(specials); i++) { 356 if (!strcmp(sec->name, specials[i])) 357 return true; 358 } 359 360 /* Most .discard data sections are special */ 361 for (int i = 0; i < ARRAY_SIZE(non_special_discards); i++) { 362 if (!strcmp(sec->name, non_special_discards[i])) 363 return false; 364 } 365 366 return strstarts(sec->name, ".discard."); 367 } 368 369 /* 370 * These sections are referenced by special sections but aren't considered 371 * special sections themselves. 372 */ 373 static bool is_special_section_aux(struct section *sec) 374 { 375 static const char * const specials_aux[] = { 376 ".altinstr_replacement", 377 ".altinstr_aux", 378 }; 379 380 for (int i = 0; i < ARRAY_SIZE(specials_aux); i++) { 381 if (!strcmp(sec->name, specials_aux[i])) 382 return true; 383 } 384 385 return false; 386 } 387 388 /* 389 * Symbols created by ___ADDRESSABLE() are only used to convince the toolchain 390 * not to optimize out the referenced symbol. 391 */ 392 static bool is_addressable_sym(struct symbol *sym) 393 { 394 return !strcmp(sym->sec->name, ".discard.addressable"); 395 } 396 397 /* 398 * ABS symbols are typically assembly .set/.equ constants which are never 399 * referenced by relocations. (Exclude FILE symbols which are also SHN_ABS.) 400 */ 401 static bool is_abs_sym(struct symbol *sym) 402 { 403 return sym->sym.st_shndx == SHN_ABS && !is_file_sym(sym); 404 } 405 406 static bool is_initcall_sym(struct symbol *sym) 407 { 408 return strstarts(sym->name, "__initcall__") || 409 strstarts(sym->name, "__initstub__"); 410 } 411 412 /* 413 * Some .rodata is anonymous and can't be correlated due to there being no 414 * symbol names. 415 * 416 * The .rodata.cst* sections aren't technically anonymous, they're SHF_MERGE 417 * constant pool sections containing small fixed-size data (lookup tables, 418 * bitmasks) which are only read by value, so pointer equivalence isn't needed. 419 * They are typically referenced by UBSAN data sections. 420 */ 421 static bool is_anonymous_rodata(struct symbol *sym) 422 { 423 return is_rodata_sec(sym->sec) && 424 (!is_object_sym(sym) || strstarts(sym->sec->name, ".rodata.cst")); 425 } 426 427 /* 428 * These symbols should never be correlated, so their local patched versions 429 * are used instead of linking to the originals. 430 */ 431 static bool dont_correlate(struct symbol *sym) 432 { 433 return is_file_sym(sym) || 434 is_null_sym(sym) || 435 is_sec_sym(sym) || 436 is_abs_sym(sym) || 437 is_prefix_func(sym) || 438 is_uncorrelated_static_local(sym) || 439 is_local_label(sym) || 440 is_string_sec(sym->sec) || 441 is_anonymous_rodata(sym) || 442 is_initcall_sym(sym) || 443 is_addressable_sym(sym) || 444 is_special_section(sym->sec) || 445 is_special_section_aux(sym->sec); 446 } 447 448 static const char *llvm_suffix(const char *name) 449 { 450 return strstr(name, ".llvm."); 451 } 452 453 static bool is_llvm_sym(struct symbol *sym) 454 { 455 return llvm_suffix(sym->name); 456 } 457 458 /* 459 * Determine if two symbols have compatible source file origins: 460 * 461 * - If both symbols are local, only return true if they belong to the same 462 * ELF file symbol. 463 * 464 * - If both symbols are global, always return true, as globals don't have 465 * file associations. 466 * 467 * - If they have different scopes, also return true, as the patch might have 468 * changed the symbol's scope. 469 * 470 * Works for both same-ELF (direct pointer compare) and cross-ELF 471 * (compare via file->twin) cases. 472 */ 473 static bool maybe_same_file(struct symbol *sym1, struct symbol *sym2) 474 { 475 if (!sym1->file || !sym2->file) 476 return true; 477 if (sym1->file == sym2->file) 478 return true; 479 return sym1->file->twin == sym2->file; 480 } 481 482 /* 483 * Similar to maybe_same_file(), but strict: no scope changes allowed. 484 * 485 * Works for both same-ELF (direct pointer compare) and cross-ELF 486 * (compare via file->twin) cases. 487 */ 488 static bool same_file(struct symbol *sym1, struct symbol *sym2) 489 { 490 if (llvm_suffix(sym1->name) && llvm_suffix(sym2->name)) 491 return true; 492 if (!sym1->file && !sym2->file) 493 return true; 494 if (!sym1->file || !sym2->file) 495 return false; 496 if (sym1->file == sym2->file) 497 return true; 498 return sym1->file->twin == sym2->file; 499 } 500 501 /* 502 * Is it a local symbol, or at least was it local in the translation unit 503 * before LLVM promoted it? 504 */ 505 static bool is_tu_local_sym(struct symbol *sym) 506 { 507 return is_local_sym(sym) || is_llvm_sym(sym); 508 } 509 510 /* 511 * Try to find sym1's twin in patched using deterministic matching. 512 * 513 * Multiple symbols can share a demangled name (e.g., static functions in 514 * different TUs). This function counts same-named candidates through a 515 * funnel of progressively tighter filters. Each level is a strict subset 516 * of the previous one. 517 * 518 * The widest level that yields a 1:1 match wins. Narrower levels are only 519 * needed when the wider level is ambiguous (count > 1). 520 * 521 * Candidates are pre-filtered by maybe_same_file(), which narrows most 522 * local symbols to their own TU. For example, 19 different static 523 * type_show() functions across vmlinux.o each see only one candidate after 524 * pre-filtering, so they match immediately at Level 1. 525 * 526 * Level 1 (name): Works when the demangled name is unique after 527 * pre-filtering. Handles most symbols: unique globals like copy_signal(), 528 * or per-TU locals like pcspkr_probe(). 529 * 530 * Level 2 (scope): Filters by local-vs-global (TU-local-vs-not). Example: 531 * parse_header() exists as both a static and a global function. Level 1 532 * sees both (same demangled name), but Level 2 separates them by scope. 533 * 534 * Level 3 (file): Strict file matching via same_file(), which rejects scope 535 * changes. Example: LLVM-promoted foo.llvm.12345 (global, no FILE symbol) 536 * vs genuine local foo (has FILE symbol). Both are TU-local so Level 2 537 * can't distinguish them, but same_file() rejects the pair because one has 538 * a file association and the other doesn't. 539 * 540 * Level 4 (checksum): Distinguishes by function checksum. Example: 541 * usb_devnode.llvm.AAA and usb_devnode.llvm.BBB are two LLVM-promoted 542 * functions from different TUs with the same demangled name. After a TU 543 * change, the .llvm. hashes change but the functions themselves may be 544 * unchanged. Level 4 matches each to the patched candidate with the 545 * same checksum. 546 */ 547 static struct symbol *find_twin(struct elfs *e, struct symbol *sym1) 548 { 549 struct symbol *name_last = NULL, *scope_last = NULL, 550 *file_last = NULL, *csum_last = NULL; 551 unsigned int name_orig = 0, name_patched = 0; 552 unsigned int scope_orig = 0, scope_patched = 0; 553 unsigned int file_orig = 0, file_patched = 0; 554 unsigned int csum_orig = 0, csum_patched = 0; 555 struct symbol *sym2, *match = NULL; 556 557 /* Count orig candidates */ 558 for_each_sym_by_demangled_name(e->orig, sym1->demangled_name, sym2) { 559 if (sym2->twin || sym1->type != sym2->type || sym2->dont_correlate || 560 (!maybe_same_file(sym1, sym2))) 561 continue; 562 563 /* Level 1: name match (widest filter) */ 564 name_orig++; 565 566 /* Level 2: scope (scope changes allowed) */ 567 if (is_tu_local_sym(sym1) != is_tu_local_sym(sym2)) 568 continue; 569 scope_orig++; 570 571 /* Level 3: file (scope changes disallowed) */ 572 if (!same_file(sym1, sym2)) 573 continue; 574 file_orig++; 575 576 /* Level 4: checksum (unchanged symbols) */ 577 if (sym1->len != sym2->len || !sym1->csum.checksum || 578 sym1->csum.checksum != sym2->csum.checksum) 579 continue; 580 csum_orig++; 581 } 582 583 /* Count patched candidates */ 584 for_each_sym_by_demangled_name(e->patched, sym1->demangled_name, sym2) { 585 if (sym2->twin || sym1->type != sym2->type || sym2->dont_correlate || 586 !maybe_same_file(sym1, sym2)) 587 continue; 588 589 /* Level 1 */ 590 name_patched++; 591 name_last = sym2; 592 593 /* Level 2 */ 594 if (is_tu_local_sym(sym1) != is_tu_local_sym(sym2)) 595 continue; 596 scope_patched++; 597 scope_last = sym2; 598 599 /* Level 3 */ 600 if (!same_file(sym1, sym2)) 601 continue; 602 file_patched++; 603 file_last = sym2; 604 605 /* Level 4 */ 606 if (sym1->len != sym2->len || !sym1->csum.checksum || 607 sym1->csum.checksum != sym2->csum.checksum) 608 continue; 609 csum_patched++; 610 csum_last = sym2; 611 } 612 613 /* Return the widest level that yields a unique (1:1) match */ 614 if (name_orig == 1 && name_patched == 1) 615 match = name_last; 616 else if (scope_orig == 1 && scope_patched == 1) 617 match = scope_last; 618 else if (file_orig == 1 && file_patched == 1) 619 match = file_last; 620 else if (csum_orig == 1 && csum_patched == 1) 621 match = csum_last; 622 623 if (!match) 624 return NULL; 625 626 if (name_orig != 1 || name_patched != 1) 627 dbg_correlate("find_twin(): %s%s -> %s%s", 628 sym1->name, is_func_sym(sym1) ? "()" : "", 629 match->name, is_func_sym(match) ? "()" : ""); 630 631 return match; 632 } 633 634 struct llvm_suffix_pair { 635 struct hlist_node hash; 636 const char *orig; 637 const char *patched; 638 }; 639 640 static DECLARE_HASHTABLE(suffix_map, 7); 641 642 /* 643 * Build a mapping of known orig-to-patched LLVM suffixes based on 644 * already-correlated symbol pairs. All promoted symbols from the same TU 645 * share the same .llvm.<hash> suffix, so one correlated pair seeds the map 646 * for the entire TU. 647 */ 648 static int update_suffix_map(struct elf *elf) 649 { 650 struct llvm_suffix_pair *entry; 651 struct symbol *sym; 652 653 for_each_sym(elf, sym) { 654 const char *s1, *s2; 655 bool found; 656 657 if (!sym->twin) 658 continue; 659 660 s1 = llvm_suffix(sym->name); 661 s2 = llvm_suffix(sym->twin->name); 662 663 if (!s1 || !s2) 664 continue; 665 666 found = false; 667 hash_for_each_possible(suffix_map, entry, hash, str_hash(s1)) { 668 if (!strcmp(entry->orig, s1)) { 669 found = true; 670 break; 671 } 672 } 673 if (found) 674 continue; 675 676 entry = calloc(1, sizeof(*entry)); 677 if (!entry) { 678 ERROR_GLIBC("calloc"); 679 return -1; 680 } 681 682 entry->orig = s1; 683 entry->patched = s2; 684 hash_add(suffix_map, &entry->hash, str_hash(s1)); 685 } 686 687 return 0; 688 } 689 690 /* 691 * Match by translating the symbol's .llvm.<hash> suffix through the suffix 692 * map to find the corresponding hash suffix for the patched object. 693 * 694 * Example: In the original kernel, TU drivers/base/core.c contains 695 * foo.llvm.12345 and bar.llvm.12345 (same TU, same hash). After patching, 696 * they become foo.llvm.67890 and bar.llvm.67890. If foo was already 697 * correlated by find_twin() (e.g., unique by name), the suffix map records 698 * .llvm.12345 -> .llvm.67890. When processing bar.llvm.12345, this 699 * function looks up .llvm.12345, gets .llvm.67890, constructs the name 700 * bar.llvm.67890, and finds the match. 701 */ 702 static struct symbol *find_twin_suffixed(struct elf *elf, struct symbol *sym1) 703 { 704 const char *suffix, *patched_suffix = NULL; 705 struct symbol *sym2, *match = NULL; 706 char name[SYM_NAME_LEN]; 707 struct llvm_suffix_pair *entry; 708 int count = 0; 709 710 suffix = llvm_suffix(sym1->name); 711 if (!suffix) 712 return NULL; 713 714 hash_for_each_possible(suffix_map, entry, hash, str_hash(suffix)) { 715 if (!strcmp(entry->orig, suffix)) { 716 patched_suffix = entry->patched; 717 break; 718 } 719 } 720 if (!patched_suffix) 721 return NULL; 722 723 if (snprintf_check(name, SYM_NAME_LEN, "%s%s", 724 sym1->demangled_name, patched_suffix)) 725 return NULL; 726 727 for_each_sym_by_name(elf, name, sym2) { 728 if (sym2->twin || sym1->type != sym2->type || sym2->dont_correlate) 729 continue; 730 count++; 731 match = sym2; 732 } 733 734 if (count != 1) 735 return NULL; 736 737 dbg_correlate("find_suffixed_twin(): %s%s -> %s%s", 738 sym1->name, is_func_sym(sym1) ? "()" : "", 739 match->name, is_func_sym(match) ? "()" : ""); 740 741 return match; 742 } 743 744 /* 745 * Last-resort positional matching. 746 * 747 * Finds a symbol with the same position in the symbol table among 748 * same-demangled-name candidates, similar to livepatch sympos. Note that 749 * LLVM-promoted symbols are globals, which come after locals in the symbol 750 * table, so we have to be careful not to compare different scopes. 751 * 752 * Example: arch/x86/events/intel/core.c defines many __quirk variables via 753 * X86_MATCH_*() macros. In the symbol table they appear as __quirk.90, 754 * __quirk.97, __quirk.101, etc., all with demangled name __quirk, same 755 * scope, and same FILE symbol. No deterministic filter can distinguish 756 * them, so they're matched by position: the 1st __quirk in orig matches the 757 * 1st in patched, the 2nd matches the 2nd, etc. 758 * 759 * This is less deterministic than the other strategies, so it's done last. 760 */ 761 static struct symbol *find_twin_positional(struct elfs *e, struct symbol *sym1) 762 { 763 unsigned int idx_orig = 0, idx_patched = 0; 764 unsigned int sym1_pos = 0; 765 struct symbol *sym2, *match = NULL; 766 767 for_each_sym_by_demangled_name(e->orig, sym1->demangled_name, sym2) { 768 if (sym2->twin || sym1->type != sym2->type || sym2->dont_correlate || 769 !maybe_same_file(sym1, sym2)) 770 continue; 771 if (is_tu_local_sym(sym1) != is_tu_local_sym(sym2) || 772 is_llvm_sym(sym1) != is_llvm_sym(sym2)) 773 continue; 774 if (sym1 == sym2) 775 sym1_pos = idx_orig; 776 idx_orig++; 777 } 778 779 for_each_sym_by_demangled_name(e->patched, sym1->demangled_name, sym2) { 780 if (sym2->twin || sym1->type != sym2->type || sym2->dont_correlate || 781 !maybe_same_file(sym1, sym2)) 782 continue; 783 if (is_tu_local_sym(sym1) != is_tu_local_sym(sym2) || 784 is_llvm_sym(sym1) != is_llvm_sym(sym2)) 785 continue; 786 if (idx_patched == sym1_pos) 787 match = sym2; 788 idx_patched++; 789 } 790 791 if (idx_orig != idx_patched) 792 return NULL; 793 794 dbg_correlate("find_twin_positional(): %s%s -> %s%s", 795 sym1->name, is_func_sym(sym1) ? "()" : "", 796 match->name, is_func_sym(match) ? "()" : ""); 797 798 return match; 799 } 800 801 /* 802 * Correlate symbols between the orig and patched objects. This is a 803 * prerequisite for detecting changed functions, as well as for properly 804 * translating relocations so they point to the correct symbol. 805 */ 806 static int correlate_symbols(struct elfs *e) 807 { 808 struct symbol *file1_sym, *file2_sym; 809 struct symbol *sym1, *sym2; 810 bool progress; 811 812 for_each_sym(e->orig, sym1) 813 sym1->dont_correlate = dont_correlate(sym1); 814 for_each_sym(e->patched, sym2) 815 sym2->dont_correlate = dont_correlate(sym2); 816 817 /* Correlate FILE symbols */ 818 file1_sym = first_file_symbol(e->orig); 819 file2_sym = first_file_symbol(e->patched); 820 821 for (; ; file1_sym = next_file_symbol(e->orig, file1_sym), 822 file2_sym = next_file_symbol(e->patched, file2_sym)) { 823 824 if (!file1_sym && file2_sym) { 825 ERROR("FILE symbol mismatch: NULL != %s", file2_sym->name); 826 return -1; 827 } 828 829 if (file1_sym && !file2_sym) { 830 ERROR("FILE symbol mismatch: %s != NULL", file1_sym->name); 831 return -1; 832 } 833 834 if (!file1_sym) 835 break; 836 837 if (strcmp(file1_sym->name, file2_sym->name)) { 838 ERROR("FILE symbol mismatch: %s != %s", file1_sym->name, file2_sym->name); 839 return -1; 840 } 841 842 file1_sym->twin = file2_sym; 843 file2_sym->twin = file1_sym; 844 } 845 846 847 /* 848 * Correlate in two phases: loop deterministic levels until no more 849 * progress, then use positional fallback for the rest. This prevents 850 * the nondeterministic positional matching from stealing symbols that 851 * have deterministic matches. 852 */ 853 hash_init(suffix_map); 854 do { 855 progress = false; 856 for_each_sym(e->orig, sym1) { 857 if (sym1->twin || sym1->dont_correlate) 858 continue; 859 sym2 = find_twin(e, sym1); 860 if (!sym2) 861 continue; 862 sym1->twin = sym2; 863 sym2->twin = sym1; 864 progress = true; 865 } 866 867 if (update_suffix_map(e->orig)) 868 return -1; 869 870 for_each_sym(e->orig, sym1) { 871 if (sym1->twin || sym1->dont_correlate) 872 continue; 873 sym2 = find_twin_suffixed(e->patched, sym1); 874 if (!sym2) 875 continue; 876 sym1->twin = sym2; 877 sym2->twin = sym1; 878 progress = true; 879 } 880 } while (progress); 881 882 for_each_sym(e->orig, sym1) { 883 if (sym1->twin || sym1->dont_correlate) 884 continue; 885 sym2 = find_twin_positional(e, sym1); 886 if (!sym2) 887 continue; 888 sym1->twin = sym2; 889 sym2->twin = sym1; 890 } 891 892 for_each_sym(e->orig, sym1) { 893 if (sym1->twin || sym1->dont_correlate) 894 continue; 895 WARN("no correlation: %s", sym1->name); 896 } 897 898 return 0; 899 } 900 901 static int clone_sym_relocs(struct elfs *e, struct symbol *patched_sym); 902 903 static struct symbol *__clone_symbol(struct elf *elf, struct symbol *patched_sym, 904 bool data_too) 905 { 906 struct section *out_sec = NULL; 907 unsigned long offset = 0; 908 struct symbol *out_sym; 909 910 if (data_too && !is_undef_sym(patched_sym)) { 911 struct section *patched_sec = patched_sym->sec; 912 913 out_sec = find_section_by_name(elf, patched_sec->name); 914 if (!out_sec) { 915 out_sec = elf_create_section(elf, patched_sec->name, 0, 916 patched_sec->sh.sh_entsize, 917 patched_sec->sh.sh_type, 918 patched_sec->sh.sh_addralign, 919 patched_sec->sh.sh_flags); 920 if (!out_sec) 921 return NULL; 922 } 923 924 if (is_string_sec(patched_sym->sec)) { 925 out_sym = elf_create_section_symbol(elf, out_sec); 926 if (!out_sym) 927 return NULL; 928 929 goto sym_created; 930 } 931 932 if (!is_sec_sym(patched_sym)) 933 offset = ALIGN(sec_size(out_sec), out_sec->sh.sh_addralign); 934 935 if (patched_sym->len || is_sec_sym(patched_sym)) { 936 void *data = NULL; 937 size_t size; 938 939 /* bss doesn't have data */ 940 if (patched_sym->sec->data && patched_sym->sec->data->d_buf) 941 data = patched_sym->sec->data->d_buf + patched_sym->offset; 942 943 if (is_sec_sym(patched_sym)) 944 size = sec_size(patched_sym->sec); 945 else 946 size = patched_sym->len; 947 948 if (!elf_add_data(elf, out_sec, data, size)) 949 return NULL; 950 } 951 } 952 953 out_sym = elf_create_symbol(elf, patched_sym->name, out_sec, 954 patched_sym->bind, patched_sym->type, 955 offset, patched_sym->len); 956 if (!out_sym) 957 return NULL; 958 959 sym_created: 960 patched_sym->clone = out_sym; 961 out_sym->clone = patched_sym; 962 963 return out_sym; 964 } 965 966 static const char *sym_type(struct symbol *sym) 967 { 968 switch (sym->type) { 969 case STT_NOTYPE: return "NOTYPE"; 970 case STT_OBJECT: return "OBJECT"; 971 case STT_FUNC: return "FUNC"; 972 case STT_SECTION: return "SECTION"; 973 case STT_FILE: return "FILE"; 974 default: return "UNKNOWN"; 975 } 976 } 977 978 static const char *sym_bind(struct symbol *sym) 979 { 980 switch (sym->bind) { 981 case STB_LOCAL: return "LOCAL"; 982 case STB_GLOBAL: return "GLOBAL"; 983 case STB_WEAK: return "WEAK"; 984 default: return "UNKNOWN"; 985 } 986 } 987 988 /* 989 * Copy a symbol to the output object, optionally including its data and 990 * relocations. 991 */ 992 static struct symbol *clone_symbol(struct elfs *e, struct symbol *patched_sym, 993 bool data_too) 994 { 995 struct symbol *pfx; 996 997 if (patched_sym->clone) 998 return patched_sym->clone; 999 1000 dbg_clone("%s%s", patched_sym->name, data_too ? " [+DATA]" : ""); 1001 1002 /* Make sure the prefix gets cloned first */ 1003 if (is_func_sym(patched_sym) && data_too) { 1004 pfx = get_func_prefix(patched_sym); 1005 if (pfx) 1006 clone_symbol(e, pfx, true); 1007 } 1008 1009 if (!__clone_symbol(e->out, patched_sym, data_too)) 1010 return NULL; 1011 1012 if (data_too && clone_sym_relocs(e, patched_sym)) 1013 return NULL; 1014 1015 return patched_sym->clone; 1016 } 1017 1018 static void mark_included_function(struct symbol *func) 1019 { 1020 struct symbol *pfx; 1021 1022 func->included = 1; 1023 1024 /* Include prefix function */ 1025 pfx = get_func_prefix(func); 1026 if (pfx) 1027 pfx->included = 1; 1028 1029 /* Make sure .cold parent+child always stay together */ 1030 if (func->cfunc && func->cfunc != func) 1031 func->cfunc->included = 1; 1032 if (func->pfunc && func->pfunc != func) 1033 func->pfunc->included = 1; 1034 } 1035 1036 /* 1037 * Copy all changed functions (and their dependencies) from the patched object 1038 * to the output object. 1039 */ 1040 static int mark_changed_functions(struct elfs *e) 1041 { 1042 struct symbol *orig_sym, *patched_sym; 1043 bool changed = false; 1044 1045 /* Find changed functions */ 1046 for_each_sym(e->orig, orig_sym) { 1047 if (orig_sym->dont_correlate) 1048 continue; 1049 1050 patched_sym = orig_sym->twin; 1051 if (!patched_sym) 1052 continue; 1053 1054 if (orig_sym->csum.checksum != patched_sym->csum.checksum) { 1055 if (!is_func_sym(orig_sym)) { 1056 ERROR("changed data: %s", orig_sym->name); 1057 return -1; 1058 } 1059 1060 patched_sym->changed = 1; 1061 mark_included_function(patched_sym); 1062 changed = true; 1063 } 1064 } 1065 1066 /* Find added functions and print them */ 1067 for_each_sym(e->patched, patched_sym) { 1068 if (!is_func_sym(patched_sym) || patched_sym->dont_correlate) 1069 continue; 1070 1071 if (!patched_sym->twin) { 1072 printf("%s: new function: %s\n", objname, patched_sym->name); 1073 mark_included_function(patched_sym); 1074 changed = true; 1075 } 1076 } 1077 1078 /* Print changed functions */ 1079 for_each_sym(e->patched, patched_sym) { 1080 if (patched_sym->changed) 1081 printf("%s: changed function: %s\n", objname, patched_sym->name); 1082 } 1083 1084 return !changed ? 1 : 0; 1085 } 1086 1087 static int clone_included_functions(struct elfs *e) 1088 { 1089 struct symbol *patched_sym; 1090 1091 for_each_sym(e->patched, patched_sym) { 1092 if (patched_sym->included) { 1093 if (!clone_symbol(e, patched_sym, true)) 1094 return -1; 1095 } 1096 } 1097 1098 return 0; 1099 } 1100 1101 static struct export *find_export(struct symbol *sym) 1102 { 1103 struct export *export; 1104 1105 hash_for_each_possible(exports, export, hash, str_hash(sym->name)) { 1106 if (!strcmp(export->sym, sym->name)) 1107 return export; 1108 } 1109 1110 return NULL; 1111 } 1112 1113 static const char *__find_modname(struct elfs *e) 1114 { 1115 struct section *sec; 1116 char *name; 1117 1118 sec = find_section_by_name(e->orig, ".modinfo"); 1119 if (!sec) { 1120 ERROR("missing .modinfo section"); 1121 return NULL; 1122 } 1123 1124 name = memmem(sec->data->d_buf, sec_size(sec), "\0name=", 6); 1125 if (name) 1126 return name + 6; 1127 1128 name = strdup(e->orig->name); 1129 if (!name) { 1130 ERROR_GLIBC("strdup"); 1131 return NULL; 1132 } 1133 1134 return normalize_modname(name); 1135 } 1136 1137 /* Get the object's module name as defined by the kernel (and klp_object) */ 1138 static const char *find_modname(struct elfs *e) 1139 { 1140 const char *modname; 1141 1142 if (e->modname) 1143 return e->modname; 1144 1145 modname = __find_modname(e); 1146 e->modname = modname; 1147 return modname; 1148 } 1149 1150 /* 1151 * Copying a function from its native compiled environment to a kernel module 1152 * removes its natural access to local functions/variables and unexported 1153 * globals. References to such symbols need to be converted to KLP relocs so 1154 * the kernel arch relocation code knows to apply them and where to find the 1155 * symbols. Particularly, duplicate static symbols need to be disambiguated. 1156 */ 1157 static bool klp_reloc_needed(struct reloc *patched_reloc) 1158 { 1159 struct symbol *patched_sym = patched_reloc->sym; 1160 struct export *export; 1161 1162 /* no external symbol to reference */ 1163 if (patched_sym->dont_correlate) 1164 return false; 1165 1166 /* For included functions, a regular reloc will do. */ 1167 if (patched_sym->included) 1168 return false; 1169 1170 /* 1171 * If exported by a module, it has to be a klp reloc. Thanks to the 1172 * clusterfunk that is late module patching, the patch module is 1173 * allowed to be loaded before any modules it depends on. 1174 * 1175 * If exported by vmlinux, a normal reloc will do. 1176 */ 1177 export = find_export(patched_sym); 1178 if (export) 1179 return strcmp(export->mod, "vmlinux"); 1180 1181 if (!patched_sym->twin) { 1182 /* 1183 * Presumably the symbol and its reference were added by the 1184 * patch. The symbol could be defined in this .o or in another 1185 * .o in the patch module. 1186 * 1187 * This check needs to be *after* the export check due to the 1188 * possibility of the patch adding a new UNDEF reference to an 1189 * exported symbol. 1190 */ 1191 return false; 1192 } 1193 1194 /* Unexported symbol which lives in the original vmlinux or module. */ 1195 return true; 1196 } 1197 1198 /* Return -1 error, 0 success, 1 skip */ 1199 static int convert_reloc_sym_to_secsym(struct elf *elf, struct reloc *reloc) 1200 { 1201 struct symbol *sym = reloc->sym; 1202 struct section *sec = sym->sec; 1203 1204 if (is_sec_sym(sym)) 1205 return 0; 1206 1207 if (!sec->sym && !elf_create_section_symbol(elf, sec)) 1208 return -1; 1209 1210 reloc->sym = sec->sym; 1211 set_reloc_sym(elf, reloc, sec->sym->idx); 1212 set_reloc_addend(elf, reloc, sym->offset + reloc_addend(reloc)); 1213 return 0; 1214 } 1215 1216 /* Return -1 error, 0 success, 1 skip */ 1217 static int convert_reloc_secsym_to_sym(struct elf *elf, struct reloc *reloc) 1218 { 1219 struct symbol *sym = reloc->sym; 1220 struct section *sec = sym->sec; 1221 1222 if (!is_sec_sym(sym)) 1223 return 0; 1224 1225 /* If the symbol has a dedicated section, it's easy to find */ 1226 sym = find_symbol_by_offset(sec, 0); 1227 if (sym && sym->len == sec_size(sec)) 1228 goto found_sym; 1229 1230 /* No dedicated section; find the symbol manually */ 1231 sym = find_symbol_containing_inclusive(sec, arch_adjusted_addend(reloc)); 1232 if (!sym) { 1233 /* 1234 * This is presumably an .altinstr_replacement section which is 1235 * empty due to it only having zero-length replacement(s). 1236 */ 1237 if (!sec_size(sec)) 1238 return 1; 1239 1240 /* 1241 * .rodata is a mixed bag of named objects and anonymous data. 1242 * 1243 * Convert section symbol references to named object symbols 1244 * when possible, to preserve pointer identity for const 1245 * structs like file_operations. Otherwise a section symbol is 1246 * fine. 1247 */ 1248 if (is_rodata_sec(sec)) 1249 return 0; 1250 1251 /* 1252 * This can happen for special section references to weak code 1253 * whose symbol has been stripped by the linker. 1254 */ 1255 return -1; 1256 } 1257 1258 found_sym: 1259 reloc->sym = sym; 1260 set_reloc_sym(elf, reloc, sym->idx); 1261 set_reloc_addend(elf, reloc, reloc_addend(reloc) - sym->offset); 1262 return 0; 1263 } 1264 1265 /* 1266 * Sections with anonymous or uncorrelated data (strings, UBSAN data, Clang 1267 * anonymous constants) need section symbol references. 1268 */ 1269 static bool is_uncorrelated_section(struct section *sec) 1270 { 1271 return is_string_sec(sec) || 1272 strstarts(sec->name, ".data..Lubsan") || /* GCC */ 1273 strstarts(sec->name, ".data..L__unnamed_") || /* Clang */ 1274 strstarts(sec->name, ".data..Lanon."); /* Clang */ 1275 } 1276 1277 /* 1278 * Convert a relocation symbol reference to the needed format: either a section 1279 * symbol or the underlying symbol itself. Return -1 error, 0 success, 1 skip. 1280 */ 1281 static int convert_reloc_sym(struct elf *elf, struct reloc *reloc) 1282 { 1283 struct section *sec = reloc->sym->sec; 1284 1285 if (reloc_type(reloc) == R_NONE) 1286 return 1; 1287 1288 if (is_uncorrelated_section(sec)) 1289 return convert_reloc_sym_to_secsym(elf, reloc); 1290 1291 /* Everything else: references should use named symbols. */ 1292 return convert_reloc_secsym_to_sym(elf, reloc); 1293 } 1294 1295 /* 1296 * Convert a regular relocation to a klp relocation (sort of). 1297 */ 1298 static int clone_reloc_klp(struct elfs *e, struct reloc *patched_reloc, 1299 struct section *sec, unsigned long offset, 1300 struct export *export) 1301 { 1302 struct symbol *patched_sym = patched_reloc->sym; 1303 s64 addend = reloc_addend(patched_reloc); 1304 const char *sym_modname, *sym_orig_name; 1305 static struct section *klp_relocs; 1306 char tombstone_name[SYM_NAME_LEN]; 1307 struct symbol *sym, *klp_sym; 1308 unsigned long klp_reloc_off; 1309 char sym_name[SYM_NAME_LEN]; 1310 struct klp_reloc klp_reloc; 1311 unsigned long sympos; 1312 1313 if (!patched_sym->twin) { 1314 ERROR("unexpected klp reloc for new symbol %s", patched_sym->name); 1315 return -1; 1316 } 1317 1318 /* 1319 * Keep the original reloc intact for now to avoid breaking objtool run 1320 * which relies on proper relocations for many of its features. This 1321 * reloc now targets a functionally dead tombstone symbol and will be 1322 * disabled later by "objtool klp post-link". 1323 * 1324 * Convert the symbol to UNDEF/WEAK and rename to 1325 * .klp.tombstone.sym_name to prevent modpost from printing warnings or 1326 * creating false module dependencies. The prefix is hidden from the 1327 * objtool run itself by read_symbols(). 1328 */ 1329 1330 sym = patched_sym->clone; 1331 if (!sym) { 1332 if (snprintf_check(tombstone_name, SYM_NAME_LEN, 1333 KLP_TOMBSTONE_PREFIX "%s", patched_sym->name)) 1334 return -1; 1335 1336 sym = elf_create_symbol(e->out, tombstone_name, NULL, 1337 STB_WEAK, patched_sym->type, 0, 0); 1338 if (!sym) 1339 return -1; 1340 1341 patched_sym->clone = sym; 1342 sym->clone = patched_sym; 1343 } 1344 1345 if (!elf_create_reloc(e->out, sec, offset, sym, addend, reloc_type(patched_reloc))) 1346 return -1; 1347 1348 /* 1349 * Create the KLP symbol. 1350 */ 1351 1352 if (export) { 1353 sym_modname = export->mod; 1354 sym_orig_name = export->sym; 1355 sympos = 0; 1356 } else { 1357 sym_modname = find_modname(e); 1358 if (!sym_modname) 1359 return -1; 1360 1361 sym_orig_name = patched_sym->twin->name; 1362 sympos = klp_find_sympos(e->orig, patched_sym->twin); 1363 if (sympos == ULONG_MAX) 1364 return -1; 1365 } 1366 1367 /* symbol format: .klp.sym.modname.sym_name,sympos */ 1368 if (snprintf_check(sym_name, SYM_NAME_LEN, KLP_SYM_PREFIX "%s.%s,%ld", 1369 sym_modname, sym_orig_name, sympos)) 1370 return -1; 1371 1372 klp_sym = find_symbol_by_name(e->out, sym_name); 1373 if (!klp_sym) { 1374 __dbg_clone("%s", sym_name); 1375 1376 /* STB_WEAK: avoid modpost undefined symbol warnings */ 1377 klp_sym = elf_create_symbol(e->out, sym_name, NULL, 1378 STB_WEAK, patched_sym->type, 0, 0); 1379 if (!klp_sym) 1380 return -1; 1381 } 1382 1383 /* 1384 * Create the __klp_relocs entry. This will be converted to an actual 1385 * KLP rela by "objtool klp post-link". 1386 * 1387 * This intermediate step is necessary to prevent corruption by the 1388 * linker, which doesn't know how to properly handle two rela sections 1389 * applying to the same base section. 1390 */ 1391 1392 if (!klp_relocs) { 1393 klp_relocs = elf_create_section(e->out, KLP_RELOCS_SEC, 0, 1394 0, SHT_PROGBITS, 8, SHF_ALLOC); 1395 if (!klp_relocs) 1396 return -1; 1397 } 1398 1399 klp_reloc_off = sec_size(klp_relocs); 1400 memset(&klp_reloc, 0, sizeof(klp_reloc)); 1401 1402 klp_reloc.type = reloc_type(patched_reloc); 1403 if (!elf_add_data(e->out, klp_relocs, &klp_reloc, sizeof(klp_reloc))) 1404 return -1; 1405 1406 /* klp_reloc.offset */ 1407 if (!sec->sym && !elf_create_section_symbol(e->out, sec)) 1408 return -1; 1409 1410 if (!elf_create_reloc(e->out, klp_relocs, 1411 klp_reloc_off + offsetof(struct klp_reloc, offset), 1412 sec->sym, offset, R_ABS64)) 1413 return -1; 1414 1415 /* klp_reloc.sym */ 1416 if (!elf_create_reloc(e->out, klp_relocs, 1417 klp_reloc_off + offsetof(struct klp_reloc, sym), 1418 klp_sym, addend, R_ABS64)) 1419 return -1; 1420 1421 return 0; 1422 } 1423 1424 #define dbg_clone_reloc(sec, offset, patched_sym, addend, export, klp) \ 1425 dbg_clone("%s+0x%lx: %s%s0x%lx [%s%s%s%s%s%s]", \ 1426 sec->name, offset, patched_sym->name, \ 1427 addend >= 0 ? "+" : "-", labs(addend), \ 1428 sym_type(patched_sym), \ 1429 is_sec_sym(patched_sym) ? "" : " ", \ 1430 is_sec_sym(patched_sym) ? "" : sym_bind(patched_sym), \ 1431 is_undef_sym(patched_sym) ? " UNDEF" : "", \ 1432 export ? " EXPORTED" : "", \ 1433 klp ? " KLP" : "") 1434 1435 /* Copy a reloc and its symbol to the output object */ 1436 static int clone_reloc(struct elfs *e, struct reloc *patched_reloc, 1437 struct section *sec, unsigned long offset) 1438 { 1439 struct symbol *patched_sym = patched_reloc->sym; 1440 struct export *export = find_export(patched_sym); 1441 long addend = reloc_addend(patched_reloc); 1442 struct symbol *out_sym; 1443 bool klp; 1444 1445 klp = klp_reloc_needed(patched_reloc); 1446 1447 dbg_clone_reloc(sec, offset, patched_sym, addend, export, klp); 1448 1449 if (klp) { 1450 if (clone_reloc_klp(e, patched_reloc, sec, offset, export)) 1451 return -1; 1452 1453 return 0; 1454 } 1455 1456 /* 1457 * Why !export sets 'data_too': 1458 * 1459 * Unexported non-klp symbols need to live in the patch module, 1460 * otherwise there will be unresolved symbols. Notably, this includes: 1461 * 1462 * - New functions/data 1463 * - String sections 1464 * - Special section entries 1465 * - Uncorrelated static local variables 1466 * - UBSAN sections 1467 */ 1468 out_sym = clone_symbol(e, patched_sym, patched_sym->included || !export); 1469 if (!out_sym) 1470 return -1; 1471 1472 /* 1473 * For strings, all references use section symbols, thanks to 1474 * convert_reloc_sym(). clone_symbol() has cloned an empty 1475 * version of the string section. Now copy the string itself. 1476 */ 1477 if (is_string_sec(patched_sym->sec)) { 1478 const char *str = patched_sym->sec->data->d_buf + addend; 1479 1480 __dbg_clone("\"%s\"", escape_str(str)); 1481 1482 addend = elf_add_string(e->out, out_sym->sec, str); 1483 if (addend == -1) 1484 return -1; 1485 } 1486 1487 if (!elf_create_reloc(e->out, sec, offset, out_sym, addend, 1488 reloc_type(patched_reloc))) 1489 return -1; 1490 1491 return 0; 1492 } 1493 1494 /* Copy all relocs needed for a symbol's contents */ 1495 static int clone_sym_relocs(struct elfs *e, struct symbol *patched_sym) 1496 { 1497 struct section *patched_rsec = patched_sym->sec->rsec; 1498 struct reloc *patched_reloc; 1499 unsigned long start, end; 1500 struct symbol *out_sym; 1501 1502 out_sym = patched_sym->clone; 1503 if (!out_sym) { 1504 ERROR("no clone for %s", patched_sym->name); 1505 return -1; 1506 } 1507 1508 if (!patched_rsec) 1509 return 0; 1510 1511 if (!is_sec_sym(patched_sym) && !patched_sym->len) 1512 return 0; 1513 1514 if (is_string_sec(patched_sym->sec)) 1515 return 0; 1516 1517 if (is_sec_sym(patched_sym)) { 1518 start = 0; 1519 end = sec_size(patched_sym->sec); 1520 } else { 1521 start = patched_sym->offset; 1522 end = start + patched_sym->len; 1523 } 1524 1525 for_each_reloc(patched_rsec, patched_reloc) { 1526 unsigned long offset; 1527 int ret; 1528 1529 if (reloc_offset(patched_reloc) < start || 1530 reloc_offset(patched_reloc) >= end) 1531 continue; 1532 1533 /* 1534 * Skip any reloc referencing .altinstr_aux. Its code is 1535 * always patched by alternatives. See ALTERNATIVE_TERNARY(). 1536 */ 1537 if (patched_reloc->sym->sec && 1538 !strcmp(patched_reloc->sym->sec->name, ".altinstr_aux")) 1539 continue; 1540 1541 ret = convert_reloc_sym(e->patched, patched_reloc); 1542 if (ret < 0) { 1543 ERROR_FUNC(patched_rsec->base, reloc_offset(patched_reloc), 1544 "failed to convert reloc sym '%s' to its proper format", 1545 patched_reloc->sym->name); 1546 return -1; 1547 } 1548 if (ret > 0) 1549 continue; 1550 1551 offset = out_sym->offset + (reloc_offset(patched_reloc) - patched_sym->offset); 1552 1553 if (clone_reloc(e, patched_reloc, out_sym->sec, offset)) 1554 return -1; 1555 } 1556 return 0; 1557 1558 } 1559 1560 static int create_fake_symbol(struct elf *elf, struct section *sec, 1561 unsigned long offset, size_t size) 1562 { 1563 char name[SYM_NAME_LEN]; 1564 unsigned int type; 1565 static int ctr; 1566 char *c; 1567 1568 if (snprintf_check(name, SYM_NAME_LEN, "%s_%d", sec->name, ctr++)) 1569 return -1; 1570 1571 for (c = name; *c; c++) 1572 if (*c == '.') 1573 *c = '_'; 1574 1575 /* 1576 * STT_NOTYPE: Prevent objtool from validating .altinstr_replacement 1577 * while still allowing objdump to disassemble it. 1578 */ 1579 type = is_text_sec(sec) ? STT_NOTYPE : STT_OBJECT; 1580 return elf_create_symbol(elf, name, sec, STB_LOCAL, type, offset, size) ? 0 : -1; 1581 } 1582 1583 /* 1584 * Special sections (alternatives, etc) are basically arrays of structs. 1585 * For all the special sections, create a symbol for each struct entry. This 1586 * is a bit cumbersome, but it makes the extracting of the individual entries 1587 * much more straightforward. 1588 * 1589 * There are three ways to identify the entry sizes for a special section: 1590 * 1591 * 1) ELF section header sh_entsize: Ideally this would be used almost 1592 * everywhere. But unfortunately the toolchains make it difficult. The 1593 * assembler .[push]section directive syntax only takes entsize when 1594 * combined with SHF_MERGE. But Clang disallows combining SHF_MERGE with 1595 * SHF_WRITE. And some special sections do need to be writable. 1596 * 1597 * Another place this wouldn't work is .altinstr_replacement, whose entries 1598 * don't have a fixed size. 1599 * 1600 * 2) ANNOTATE_DATA_SPECIAL: This is a lightweight objtool annotation which 1601 * points to the beginning of each entry. The size of the entry is then 1602 * inferred by the location of the subsequent annotation (or end of 1603 * section). 1604 * 1605 * 3) Simple array of pointers: If the special section is just a basic array of 1606 * pointers, the entry size can be inferred by the number of relocations. 1607 * No annotations needed. 1608 * 1609 * Note I also tried to create per-entry symbols at the time of creation, in 1610 * the original [inline] asm. Unfortunately, creating uniquely named symbols 1611 * is trickier than one might think, especially with Clang inline asm. I 1612 * eventually just gave up trying to make that work, in favor of using 1613 * ANNOTATE_DATA_SPECIAL and creating the symbols here after the fact. 1614 */ 1615 static int create_fake_symbols(struct elf *elf) 1616 { 1617 struct section *sec; 1618 struct reloc *reloc; 1619 1620 /* 1621 * 1) Make symbols for all the ANNOTATE_DATA_SPECIAL entries: 1622 */ 1623 1624 sec = find_section_by_name(elf, ".discard.annotate_data"); 1625 if (!sec || !sec->rsec) 1626 goto entsize; 1627 1628 for_each_reloc(sec->rsec, reloc) { 1629 unsigned long offset, size; 1630 struct reloc *next_reloc; 1631 1632 if (annotype(elf, sec, reloc) != ANNOTYPE_DATA_SPECIAL) 1633 continue; 1634 1635 offset = reloc_addend(reloc); 1636 1637 size = 0; 1638 next_reloc = reloc; 1639 for_each_reloc_continue(sec->rsec, next_reloc) { 1640 if (annotype(elf, sec, next_reloc) != ANNOTYPE_DATA_SPECIAL || 1641 next_reloc->sym->sec != reloc->sym->sec) 1642 continue; 1643 1644 size = reloc_addend(next_reloc) - offset; 1645 break; 1646 } 1647 1648 if (!size) 1649 size = sec_size(reloc->sym->sec) - offset; 1650 1651 if (create_fake_symbol(elf, reloc->sym->sec, offset, size)) 1652 return -1; 1653 } 1654 1655 /* 1656 * 2) Make symbols for sh_entsize, and simple arrays of pointers: 1657 */ 1658 entsize: 1659 for_each_sec(elf, sec) { 1660 unsigned int entry_size; 1661 unsigned long offset; 1662 1663 if (!is_special_section(sec) || find_symbol_by_offset(sec, 0)) 1664 continue; 1665 1666 if (!sec->rsec) { 1667 ERROR("%s: missing special section relocations", sec->name); 1668 return -1; 1669 } 1670 1671 entry_size = sec->sh.sh_entsize; 1672 if (!entry_size) { 1673 entry_size = arch_reloc_size(sec->rsec->relocs); 1674 if (sec_size(sec) != entry_size * sec_num_entries(sec->rsec)) { 1675 ERROR("%s: missing special section entsize or annotations", sec->name); 1676 return -1; 1677 } 1678 } 1679 1680 for (offset = 0; offset < sec_size(sec); offset += entry_size) { 1681 if (create_fake_symbol(elf, sec, offset, entry_size)) 1682 return -1; 1683 } 1684 } 1685 1686 return 0; 1687 } 1688 1689 /* Keep a special section entry if it references an included function */ 1690 static bool should_keep_special_sym(struct elf *elf, struct symbol *sym) 1691 { 1692 bool annotate_insn = !strcmp(sym->sec->name, ".discard.annotate_insn"); 1693 struct reloc *reloc; 1694 1695 if (is_sec_sym(sym) || !sym->sec->rsec) 1696 return false; 1697 1698 sym_for_each_reloc(elf, sym, reloc) { 1699 if (convert_reloc_sym(elf, reloc)) 1700 continue; 1701 1702 if (!reloc->sym->clone || is_undef_sym(reloc->sym->clone)) 1703 continue; 1704 1705 /* 1706 * Keep special section references to cloned functions. 1707 * In some cases annotate_insn can also reference cloned alt 1708 * replacement fake symbols; keep those references as well. 1709 */ 1710 if (is_func_sym(reloc->sym) || 1711 (annotate_insn && is_notype_sym(reloc->sym))) 1712 return true; 1713 } 1714 1715 return false; 1716 } 1717 1718 /* 1719 * Klp relocations aren't allowed for __jump_table and .static_call_sites if 1720 * the referenced symbol lives in a kernel module, because such klp relocs may 1721 * be applied after static branch/call init, resulting in code corruption. 1722 * 1723 * Validate a special section entry to avoid that. Note that an inert 1724 * tracepoint or pr_debug() is harmless enough, in that case just skip the 1725 * entry and print a warning. Otherwise, return an error. 1726 * 1727 * TODO: This is only a temporary limitation which will be fixed when livepatch 1728 * adds support for submodules: fully self-contained modules which are embedded 1729 * in the top-level livepatch module's data and which can be loaded on demand 1730 * when their corresponding to-be-patched module gets loaded. Then klp relocs 1731 * can be retired. 1732 * 1733 * Return: 1734 * -1: error: validation failed 1735 * 1: warning: disabled tracepoint or pr_debug() 1736 * 0: success 1737 */ 1738 static int validate_special_section_klp_reloc(struct elfs *e, struct symbol *sym) 1739 { 1740 bool static_branch = !strcmp(sym->sec->name, "__jump_table"); 1741 bool static_call = !strcmp(sym->sec->name, ".static_call_sites"); 1742 const char *code_sym = NULL; 1743 unsigned long code_offset = 0; 1744 struct reloc *reloc; 1745 int ret = 0; 1746 1747 if (!static_branch && !static_call) 1748 return 0; 1749 1750 sym_for_each_reloc(e->patched, sym, reloc) { 1751 const char *sym_modname; 1752 struct export *export; 1753 1754 if (convert_reloc_sym(e->patched, reloc)) 1755 continue; 1756 1757 /* Static branch/call keys are always STT_OBJECT */ 1758 if (reloc->sym->type != STT_OBJECT) { 1759 1760 /* Save code location which can be printed below */ 1761 if (reloc->sym->type == STT_FUNC && !code_sym) { 1762 code_sym = reloc->sym->name; 1763 code_offset = reloc_addend(reloc); 1764 } 1765 1766 continue; 1767 } 1768 1769 if (!klp_reloc_needed(reloc)) 1770 continue; 1771 1772 export = find_export(reloc->sym); 1773 if (export) { 1774 sym_modname = export->mod; 1775 } else { 1776 sym_modname = find_modname(e); 1777 if (!sym_modname) 1778 return -1; 1779 } 1780 1781 /* vmlinux keys are ok */ 1782 if (!strcmp(sym_modname, "vmlinux")) 1783 continue; 1784 1785 if (!code_sym) 1786 code_sym = "<unknown>"; 1787 1788 if (static_branch) { 1789 if (strstarts(reloc->sym->name, "__tracepoint_")) { 1790 WARN("%s: disabling unsupported tracepoint %s", 1791 code_sym, reloc->sym->name + 13); 1792 ret = 1; 1793 continue; 1794 } 1795 1796 if (strstr(reloc->sym->name, "__UNIQUE_ID_ddebug_")) { 1797 WARN("%s: disabling unsupported pr_debug()", 1798 code_sym); 1799 ret = 1; 1800 continue; 1801 } 1802 1803 ERROR("%s+0x%lx: unsupported static branch key %s. Use static_key_enabled() instead", 1804 code_sym, code_offset, reloc->sym->name); 1805 return -1; 1806 } 1807 1808 /* static call */ 1809 if (strstarts(reloc->sym->name, "__SCK__tp_func_")) { 1810 ret = 1; 1811 continue; 1812 } 1813 1814 ERROR("%s()+0x%lx: unsupported static call key %s. Use KLP_STATIC_CALL() instead", 1815 code_sym, code_offset, reloc->sym->name); 1816 return -1; 1817 } 1818 1819 return ret; 1820 } 1821 1822 static int clone_special_section(struct elfs *e, struct section *patched_sec) 1823 { 1824 struct symbol *patched_sym; 1825 1826 /* 1827 * Extract all special section symbols (and their dependencies) which 1828 * reference included functions. 1829 */ 1830 sec_for_each_sym(patched_sec, patched_sym) { 1831 int ret; 1832 1833 if (!is_object_sym(patched_sym)) 1834 continue; 1835 1836 if (!should_keep_special_sym(e->patched, patched_sym)) 1837 continue; 1838 1839 ret = validate_special_section_klp_reloc(e, patched_sym); 1840 if (ret < 0) 1841 return -1; 1842 if (ret > 0) 1843 continue; 1844 1845 if (!clone_symbol(e, patched_sym, true)) 1846 return -1; 1847 } 1848 1849 return 0; 1850 } 1851 1852 /* Extract only the needed bits from special sections */ 1853 static int clone_special_sections(struct elfs *e) 1854 { 1855 struct section *sec, *annotate_insn = NULL; 1856 1857 for_each_sec(e->patched, sec) { 1858 if (is_special_section(sec)) { 1859 if (!strcmp(sec->name, ".discard.annotate_insn")) { 1860 annotate_insn = sec; 1861 continue; 1862 } 1863 if (clone_special_section(e, sec)) 1864 return -1; 1865 } 1866 } 1867 1868 /* 1869 * Do .discard.annotate_insn last, it can reference other special 1870 * sections (alt replacements) so they need to be cloned first. 1871 */ 1872 if (annotate_insn) { 1873 if (clone_special_section(e, annotate_insn)) 1874 return -1; 1875 } 1876 1877 return 0; 1878 } 1879 1880 /* 1881 * Create .init.klp_objects and .init.klp_funcs sections which are intermediate 1882 * sections provided as input to the patch module's init code for building the 1883 * klp_patch, klp_object and klp_func structs for the livepatch API. 1884 */ 1885 static int create_klp_sections(struct elfs *e) 1886 { 1887 size_t obj_size = sizeof(struct klp_object_ext); 1888 size_t func_size = sizeof(struct klp_func_ext); 1889 struct section *obj_sec, *funcs_sec, *str_sec; 1890 struct symbol *funcs_sym, *str_sym, *sym; 1891 char sym_name[SYM_NAME_LEN]; 1892 unsigned int nr_funcs = 0; 1893 const char *modname; 1894 void *obj_data; 1895 s64 addend; 1896 1897 obj_sec = elf_create_section_pair(e->out, KLP_OBJECTS_SEC, obj_size, 0, 0); 1898 if (!obj_sec) 1899 return -1; 1900 1901 funcs_sec = elf_create_section_pair(e->out, KLP_FUNCS_SEC, func_size, 0, 0); 1902 if (!funcs_sec) 1903 return -1; 1904 1905 funcs_sym = elf_create_section_symbol(e->out, funcs_sec); 1906 if (!funcs_sym) 1907 return -1; 1908 1909 str_sec = elf_create_section(e->out, KLP_STRINGS_SEC, 0, 0, 1910 SHT_PROGBITS, 1, 1911 SHF_ALLOC | SHF_STRINGS | SHF_MERGE); 1912 if (!str_sec) 1913 return -1; 1914 1915 if (elf_add_string(e->out, str_sec, "") == -1) 1916 return -1; 1917 1918 str_sym = elf_create_section_symbol(e->out, str_sec); 1919 if (!str_sym) 1920 return -1; 1921 1922 /* allocate klp_object_ext */ 1923 obj_data = elf_add_data(e->out, obj_sec, NULL, obj_size); 1924 if (!obj_data) 1925 return -1; 1926 1927 modname = find_modname(e); 1928 if (!modname) 1929 return -1; 1930 1931 /* klp_object_ext.name */ 1932 if (strcmp(modname, "vmlinux")) { 1933 addend = elf_add_string(e->out, str_sec, modname); 1934 if (addend == -1) 1935 return -1; 1936 1937 if (!elf_create_reloc(e->out, obj_sec, 1938 offsetof(struct klp_object_ext, name), 1939 str_sym, addend, R_ABS64)) 1940 return -1; 1941 } 1942 1943 /* klp_object_ext.funcs */ 1944 if (!elf_create_reloc(e->out, obj_sec, offsetof(struct klp_object_ext, funcs), 1945 funcs_sym, 0, R_ABS64)) 1946 return -1; 1947 1948 for_each_sym(e->out, sym) { 1949 unsigned long offset = nr_funcs * func_size; 1950 unsigned long sympos; 1951 void *func_data; 1952 1953 if (!is_func_sym(sym) || is_cold_func(sym) || 1954 !sym->clone || !sym->clone->changed) 1955 continue; 1956 1957 /* allocate klp_func_ext */ 1958 func_data = elf_add_data(e->out, funcs_sec, NULL, func_size); 1959 if (!func_data) 1960 return -1; 1961 1962 /* klp_func_ext.old_name */ 1963 addend = elf_add_string(e->out, str_sec, sym->clone->twin->name); 1964 if (addend == -1) 1965 return -1; 1966 1967 if (!elf_create_reloc(e->out, funcs_sec, 1968 offset + offsetof(struct klp_func_ext, old_name), 1969 str_sym, addend, R_ABS64)) 1970 return -1; 1971 1972 /* klp_func_ext.new_func */ 1973 if (!elf_create_reloc(e->out, funcs_sec, 1974 offset + offsetof(struct klp_func_ext, new_func), 1975 sym, 0, R_ABS64)) 1976 return -1; 1977 1978 /* klp_func_ext.sympos */ 1979 BUILD_BUG_ON(sizeof(sympos) != sizeof_field(struct klp_func_ext, sympos)); 1980 sympos = klp_find_sympos(e->orig, sym->clone->twin); 1981 if (sympos == ULONG_MAX) 1982 return -1; 1983 memcpy(func_data + offsetof(struct klp_func_ext, sympos), &sympos, 1984 sizeof_field(struct klp_func_ext, sympos)); 1985 1986 nr_funcs++; 1987 } 1988 1989 /* klp_object_ext.nr_funcs */ 1990 BUILD_BUG_ON(sizeof(nr_funcs) != sizeof_field(struct klp_object_ext, nr_funcs)); 1991 memcpy(obj_data + offsetof(struct klp_object_ext, nr_funcs), &nr_funcs, 1992 sizeof_field(struct klp_object_ext, nr_funcs)); 1993 1994 /* 1995 * Find callback pointers created by KLP_PRE_PATCH_CALLBACK() and 1996 * friends, and add them to the klp object. 1997 */ 1998 1999 if (snprintf_check(sym_name, SYM_NAME_LEN, KLP_PRE_PATCH_PREFIX "%s", modname)) 2000 return -1; 2001 2002 sym = find_symbol_by_name(e->out, sym_name); 2003 if (sym) { 2004 struct reloc *reloc; 2005 2006 reloc = find_reloc_by_dest(e->out, sym->sec, sym->offset); 2007 2008 if (!elf_create_reloc(e->out, obj_sec, 2009 offsetof(struct klp_object_ext, callbacks) + 2010 offsetof(struct klp_callbacks, pre_patch), 2011 reloc->sym, reloc_addend(reloc), R_ABS64)) 2012 return -1; 2013 } 2014 2015 if (snprintf_check(sym_name, SYM_NAME_LEN, KLP_POST_PATCH_PREFIX "%s", modname)) 2016 return -1; 2017 2018 sym = find_symbol_by_name(e->out, sym_name); 2019 if (sym) { 2020 struct reloc *reloc; 2021 2022 reloc = find_reloc_by_dest(e->out, sym->sec, sym->offset); 2023 2024 if (!elf_create_reloc(e->out, obj_sec, 2025 offsetof(struct klp_object_ext, callbacks) + 2026 offsetof(struct klp_callbacks, post_patch), 2027 reloc->sym, reloc_addend(reloc), R_ABS64)) 2028 return -1; 2029 } 2030 2031 if (snprintf_check(sym_name, SYM_NAME_LEN, KLP_PRE_UNPATCH_PREFIX "%s", modname)) 2032 return -1; 2033 2034 sym = find_symbol_by_name(e->out, sym_name); 2035 if (sym) { 2036 struct reloc *reloc; 2037 2038 reloc = find_reloc_by_dest(e->out, sym->sec, sym->offset); 2039 2040 if (!elf_create_reloc(e->out, obj_sec, 2041 offsetof(struct klp_object_ext, callbacks) + 2042 offsetof(struct klp_callbacks, pre_unpatch), 2043 reloc->sym, reloc_addend(reloc), R_ABS64)) 2044 return -1; 2045 } 2046 2047 if (snprintf_check(sym_name, SYM_NAME_LEN, KLP_POST_UNPATCH_PREFIX "%s", modname)) 2048 return -1; 2049 2050 sym = find_symbol_by_name(e->out, sym_name); 2051 if (sym) { 2052 struct reloc *reloc; 2053 2054 reloc = find_reloc_by_dest(e->out, sym->sec, sym->offset); 2055 2056 if (!elf_create_reloc(e->out, obj_sec, 2057 offsetof(struct klp_object_ext, callbacks) + 2058 offsetof(struct klp_callbacks, post_unpatch), 2059 reloc->sym, reloc_addend(reloc), R_ABS64)) 2060 return -1; 2061 } 2062 2063 return 0; 2064 } 2065 2066 /* 2067 * Copy all .modinfo import_ns= tags to ensure all namespaced exported symbols 2068 * can be accessed via normal relocs. 2069 */ 2070 static int copy_import_ns(struct elfs *e) 2071 { 2072 struct section *patched_sec, *out_sec = NULL; 2073 char *import_ns, *data_end; 2074 2075 patched_sec = find_section_by_name(e->patched, ".modinfo"); 2076 if (!patched_sec) 2077 return 0; 2078 2079 import_ns = patched_sec->data->d_buf; 2080 if (!import_ns) 2081 return 0; 2082 2083 for (data_end = import_ns + sec_size(patched_sec); 2084 import_ns < data_end; 2085 import_ns += strlen(import_ns) + 1) { 2086 2087 import_ns = memmem(import_ns, data_end - import_ns, "import_ns=", 10); 2088 if (!import_ns) 2089 return 0; 2090 2091 if (!out_sec) { 2092 out_sec = find_section_by_name(e->out, ".modinfo"); 2093 if (!out_sec) { 2094 out_sec = elf_create_section(e->out, ".modinfo", 0, 2095 patched_sec->sh.sh_entsize, 2096 patched_sec->sh.sh_type, 2097 patched_sec->sh.sh_addralign, 2098 patched_sec->sh.sh_flags); 2099 if (!out_sec) 2100 return -1; 2101 } 2102 } 2103 2104 if (!elf_add_data(e->out, out_sec, import_ns, strlen(import_ns) + 1)) 2105 return -1; 2106 } 2107 2108 return 0; 2109 } 2110 2111 int cmd_klp_diff(int argc, const char **argv) 2112 { 2113 struct elfs e = {0}; 2114 int ret; 2115 2116 argc = parse_options(argc, argv, klp_diff_options, klp_diff_usage, 0); 2117 if (argc != 3) 2118 usage_with_options(klp_diff_usage, klp_diff_options); 2119 2120 if (debug) { 2121 debug_correlate = true; 2122 debug_clone = true; 2123 } 2124 2125 objname = argv[0]; 2126 2127 e.orig = elf_open_read(argv[0], O_RDONLY); 2128 e.patched = elf_open_read(argv[1], O_RDONLY); 2129 e.out = NULL; 2130 2131 if (!e.orig || !e.patched) 2132 return -1; 2133 2134 if (klp_sympos_init(e.orig)) 2135 return -1; 2136 2137 if (read_exports()) 2138 return -1; 2139 2140 if (read_sym_checksums(e.orig)) 2141 return -1; 2142 2143 if (read_sym_checksums(e.patched)) 2144 return -1; 2145 2146 if (correlate_symbols(&e)) 2147 return -1; 2148 2149 ret = mark_changed_functions(&e); 2150 if (ret < 0) 2151 return -1; 2152 if (ret > 0) 2153 return 0; 2154 2155 e.out = elf_create_file(&e.orig->ehdr, argv[2]); 2156 if (!e.out) 2157 return -1; 2158 2159 /* 2160 * Special section fake symbols are needed so that individual special 2161 * section entries can be extracted by clone_special_sections(). 2162 * 2163 * Note the fake symbols are also needed by clone_included_functions() 2164 * because __WARN_printf() call sites add references to bug table 2165 * entries in the calling functions. 2166 */ 2167 if (create_fake_symbols(e.patched)) 2168 return -1; 2169 2170 if (clone_included_functions(&e)) 2171 return -1; 2172 2173 if (clone_special_sections(&e)) 2174 return -1; 2175 2176 if (create_klp_sections(&e)) 2177 return -1; 2178 2179 if (copy_import_ns(&e)) 2180 return -1; 2181 2182 if (elf_write(e.out)) 2183 return -1; 2184 2185 return elf_close(e.out); 2186 } 2187