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