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