xref: /linux/tools/objtool/klp-diff.c (revision dfa35434d7f20142fedd7120277b1044a0a2bb64)
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 	const char *sym_modname, *sym_orig_name, *sec_objname;
1348 	struct symbol *patched_sym = patched_reloc->sym;
1349 	s64 addend = reloc_addend(patched_reloc);
1350 	char tombstone_name[SYM_NAME_LEN];
1351 	struct symbol *sym, *klp_sym;
1352 	unsigned long klp_reloc_off;
1353 	struct section *klp_relocs;
1354 	char sec_name[SEC_NAME_LEN];
1355 	char sym_name[SYM_NAME_LEN];
1356 	struct klp_reloc klp_reloc;
1357 	unsigned long sympos;
1358 
1359 	if (!patched_sym->twin) {
1360 		if (!export) {
1361 			ERROR("unexpected klp reloc for new symbol %s", patched_sym->name);
1362 			return -1;
1363 		}
1364 
1365 		if (strcmp(export->mod, "vmlinux") &&
1366 		    !has_module_dep(e, export->mod)) {
1367 			ERROR("%s: new reference to %s (exported by %s) would create an undeclared module dependency",
1368 			      patched_sym->name, export->sym, export->mod);
1369 			return -1;
1370 		}
1371 	}
1372 
1373 	/*
1374 	 * Keep the original reloc intact for now to avoid breaking objtool run
1375 	 * which relies on proper relocations for many of its features.  This
1376 	 * reloc now targets a functionally dead tombstone symbol and will be
1377 	 * disabled later by "objtool klp post-link".
1378 	 *
1379 	 * Convert the symbol to UNDEF/WEAK and rename to
1380 	 * .klp.tombstone.sym_name to prevent modpost from printing warnings or
1381 	 * creating false module dependencies.  The prefix is hidden from the
1382 	 * objtool run itself by read_symbols().
1383 	 */
1384 
1385 	sym = patched_sym->clone;
1386 	if (!sym) {
1387 		if (snprintf_check(tombstone_name, SYM_NAME_LEN,
1388 				   KLP_TOMBSTONE_PREFIX "%s", patched_sym->name))
1389 			return -1;
1390 
1391 		sym = elf_create_symbol(e->out, tombstone_name, NULL,
1392 					STB_WEAK, patched_sym->type, 0, 0);
1393 		if (!sym)
1394 			return -1;
1395 
1396 		patched_sym->clone = sym;
1397 		sym->clone = patched_sym;
1398 	}
1399 
1400 	if (!elf_create_reloc(e->out, sec, offset, sym, addend, reloc_type(patched_reloc)))
1401 		return -1;
1402 
1403 	/*
1404 	 * Create the KLP symbol.
1405 	 */
1406 
1407 	if (export) {
1408 		sym_modname = export->mod;
1409 		sym_orig_name = export->sym;
1410 		sympos = 0;
1411 	} else {
1412 		sym_modname = find_modname(e);
1413 		if (!sym_modname)
1414 			return -1;
1415 
1416 		sym_orig_name = patched_sym->twin->name;
1417 		sympos = klp_find_sympos(e->orig, patched_sym->twin);
1418 		if (sympos == ULONG_MAX)
1419 			return -1;
1420 	}
1421 
1422 	/* symbol format: .klp.sym.modname.sym_name,sympos */
1423 	if (snprintf_check(sym_name, SYM_NAME_LEN, KLP_SYM_PREFIX "%s.%s,%ld",
1424 		      sym_modname, sym_orig_name, sympos))
1425 		return -1;
1426 
1427 	klp_sym = find_symbol_by_name(e->out, sym_name);
1428 	if (!klp_sym) {
1429 		__dbg_clone("%s", sym_name);
1430 
1431 		/* STB_WEAK: avoid modpost undefined symbol warnings */
1432 		klp_sym = elf_create_symbol(e->out, sym_name, NULL,
1433 					    STB_WEAK, patched_sym->type, 0, 0);
1434 		if (!klp_sym)
1435 			return -1;
1436 	}
1437 
1438 	/*
1439 	 * Create the __klp_relocs.<objname> entry.  This will be converted to
1440 	 * an actual KLP rela by "objtool klp post-link".
1441 	 *
1442 	 * This intermediate step is necessary to prevent corruption by the
1443 	 * linker, which doesn't know how to properly handle two rela sections
1444 	 * applying to the same base section.
1445 	 *
1446 	 * The objname decides when the reloc gets applied.  A reference to a
1447 	 * vmlinux symbol goes in the vmlinux section so it gets applied when
1448 	 * the patch module loads.  Everything else goes in the patched
1449 	 * object's section, applied when the patched module is loaded.
1450 	 */
1451 
1452 	if (!strcmp(sym_modname, "vmlinux")) {
1453 		sec_objname = "vmlinux";
1454 	} else {
1455 		sec_objname = find_modname(e);
1456 		if (!sec_objname)
1457 			return -1;
1458 	}
1459 
1460 	/* section format: __klp_relocs.objname */
1461 	if (snprintf_check(sec_name, SEC_NAME_LEN,
1462 			   KLP_RELOCS_SEC ".%s", sec_objname))
1463 		return -1;
1464 
1465 	klp_relocs = find_section_by_name(e->out, sec_name);
1466 	if (!klp_relocs) {
1467 		klp_relocs = elf_create_section(e->out, sec_name, 0,
1468 						0, SHT_PROGBITS, 8, SHF_ALLOC);
1469 		if (!klp_relocs)
1470 			return -1;
1471 	}
1472 
1473 	klp_reloc_off = sec_size(klp_relocs);
1474 	memset(&klp_reloc, 0, sizeof(klp_reloc));
1475 
1476 	klp_reloc.type = reloc_type(patched_reloc);
1477 	if (!elf_add_data(e->out, klp_relocs, &klp_reloc, sizeof(klp_reloc)))
1478 		return -1;
1479 
1480 	/* klp_reloc.offset */
1481 	if (!sec->sym && !elf_create_section_symbol(e->out, sec))
1482 		return -1;
1483 
1484 	if (!elf_create_reloc(e->out, klp_relocs,
1485 			      klp_reloc_off + offsetof(struct klp_reloc, offset),
1486 			      sec->sym, offset, R_ABS64))
1487 		return -1;
1488 
1489 	/* klp_reloc.sym */
1490 	if (!elf_create_reloc(e->out, klp_relocs,
1491 			      klp_reloc_off + offsetof(struct klp_reloc, sym),
1492 			      klp_sym, addend, R_ABS64))
1493 		return -1;
1494 
1495 	return 0;
1496 }
1497 
1498 #define dbg_clone_reloc(sec, offset, patched_sym, addend, export, klp)			\
1499 	dbg_clone("%s+0x%lx: %s%s0x%lx [%s%s%s%s%s%s]",					\
1500 		   sec->name, offset, patched_sym->name,				\
1501 		   addend >= 0 ? "+" : "-", labs(addend),				\
1502 		   sym_type(patched_sym),						\
1503 		   is_sec_sym(patched_sym) ? "" : " ",					\
1504 		   is_sec_sym(patched_sym) ? "" : sym_bind(patched_sym),		\
1505 		   is_undef_sym(patched_sym) ? " UNDEF" : "",				\
1506 		   export ? " EXPORTED" : "",						\
1507 		   klp ? " KLP" : "")
1508 
1509 /* Copy a reloc and its symbol to the output object */
1510 static int clone_reloc(struct elfs *e, struct reloc *patched_reloc,
1511 			struct section *sec, unsigned long offset)
1512 {
1513 	struct symbol *patched_sym = patched_reloc->sym;
1514 	struct export *export = find_export(patched_sym);
1515 	long addend = reloc_addend(patched_reloc);
1516 	struct symbol *out_sym;
1517 	bool klp;
1518 
1519 	klp = klp_reloc_needed(patched_reloc);
1520 
1521 	dbg_clone_reloc(sec, offset, patched_sym, addend, export, klp);
1522 
1523 	if (klp) {
1524 		if (clone_reloc_klp(e, patched_reloc, sec, offset, export))
1525 			return -1;
1526 
1527 		return 0;
1528 	}
1529 
1530 	/*
1531 	 * Why !export sets 'data_too':
1532 	 *
1533 	 * Unexported non-klp symbols need to live in the patch module,
1534 	 * otherwise there will be unresolved symbols.  Notably, this includes:
1535 	 *
1536 	 *   - New functions/data
1537 	 *   - String sections
1538 	 *   - Special section entries
1539 	 *   - Uncorrelated static local variables
1540 	 *   - UBSAN sections
1541 	 */
1542 	out_sym = clone_symbol(e, patched_sym, patched_sym->included || !export);
1543 	if (!out_sym)
1544 		return -1;
1545 
1546 	/*
1547 	 * For strings, all references use section symbols, thanks to
1548 	 * convert_reloc_sym().  clone_symbol() has cloned an empty
1549 	 * version of the string section.  Now copy the string itself.
1550 	 */
1551 	if (is_string_sec(patched_sym->sec)) {
1552 		const char *str = patched_sym->sec->data->d_buf + addend;
1553 
1554 		__dbg_clone("\"%s\"", escape_str(str));
1555 
1556 		addend = elf_add_string(e->out, out_sym->sec, str);
1557 		if (addend == -1)
1558 			return -1;
1559 	}
1560 
1561 	if (!elf_create_reloc(e->out, sec, offset, out_sym, addend,
1562 			      reloc_type(patched_reloc)))
1563 		return -1;
1564 
1565 	return 0;
1566 }
1567 
1568 /* Copy all relocs needed for a symbol's contents */
1569 static int clone_sym_relocs(struct elfs *e, struct symbol *patched_sym)
1570 {
1571 	struct section *patched_rsec = patched_sym->sec->rsec;
1572 	struct reloc *patched_reloc;
1573 	unsigned long start, end;
1574 	struct symbol *out_sym;
1575 
1576 	out_sym = patched_sym->clone;
1577 	if (!out_sym) {
1578 		ERROR("no clone for %s", patched_sym->name);
1579 		return -1;
1580 	}
1581 
1582 	if (!patched_rsec)
1583 		return 0;
1584 
1585 	if (!is_sec_sym(patched_sym) && !patched_sym->len)
1586 		return 0;
1587 
1588 	if (is_string_sec(patched_sym->sec))
1589 		return 0;
1590 
1591 	if (is_sec_sym(patched_sym)) {
1592 		start = 0;
1593 		end = sec_size(patched_sym->sec);
1594 	} else {
1595 		start = patched_sym->offset;
1596 		end = start + patched_sym->len;
1597 	}
1598 
1599 	for_each_reloc(patched_rsec, patched_reloc) {
1600 		unsigned long offset;
1601 		int ret;
1602 
1603 		if (reloc_offset(patched_reloc) < start ||
1604 		    reloc_offset(patched_reloc) >= end)
1605 			continue;
1606 
1607 		/*
1608 		 * Skip any reloc referencing .altinstr_aux.  Its code is
1609 		 * always patched by alternatives.  See ALTERNATIVE_TERNARY().
1610 		 */
1611 		if (patched_reloc->sym->sec &&
1612 		    !strcmp(patched_reloc->sym->sec->name, ".altinstr_aux"))
1613 			continue;
1614 
1615 		if (arch_alt_ignore_new_reloc(patched_sym->sec,
1616 					      reloc_offset(patched_reloc)))
1617 			continue;
1618 
1619 		ret = convert_reloc_sym(e->patched, patched_reloc);
1620 		if (ret < 0) {
1621 			ERROR_FUNC(patched_rsec->base, reloc_offset(patched_reloc),
1622 				   "failed to convert reloc sym '%s' to its proper format",
1623 				   patched_reloc->sym->name);
1624 			return -1;
1625 		}
1626 		if (ret > 0)
1627 			continue;
1628 
1629 		offset = out_sym->offset + (reloc_offset(patched_reloc) - patched_sym->offset);
1630 
1631 		if (clone_reloc(e, patched_reloc, out_sym->sec, offset))
1632 			return -1;
1633 	}
1634 	return 0;
1635 
1636 }
1637 
1638 static int create_fake_symbol(struct elf *elf, struct section *sec,
1639 			      unsigned long offset, size_t size)
1640 {
1641 	char name[SYM_NAME_LEN];
1642 	struct symbol *sym;
1643 	unsigned int type;
1644 	static int ctr;
1645 	char *c;
1646 
1647 	if (snprintf_check(name, SYM_NAME_LEN, "%s_%d", sec->name, ctr++))
1648 		return -1;
1649 
1650 	for (c = name; *c; c++)
1651 		if (*c == '.')
1652 			*c = '_';
1653 
1654 	/*
1655 	 * STT_NOTYPE: Prevent objtool from validating .altinstr_replacement
1656 	 *	       while still allowing objdump to disassemble it.
1657 	 */
1658 	type = is_text_sec(sec) ? STT_NOTYPE : STT_OBJECT;
1659 
1660 	sym = elf_create_symbol(elf, name, sec, STB_LOCAL, type, offset, size);
1661 	if (!sym)
1662 		return -1;
1663 
1664 	sym->fake = 1;
1665 	return 0;
1666 }
1667 
1668 static bool has_fake_symbols(struct section *sec)
1669 {
1670 	struct symbol *sym;
1671 
1672 	sec_for_each_sym(sec, sym)
1673 		if (sym->fake)
1674 			return true;
1675 
1676 	return false;
1677 }
1678 
1679 /*
1680  * Special sections (alternatives, etc) are basically arrays of structs.
1681  * For all the special sections, create a symbol for each struct entry.  This
1682  * is a bit cumbersome, but it makes the extracting of the individual entries
1683  * much more straightforward.
1684  *
1685  * There are three ways to identify the entry sizes for a special section:
1686  *
1687  * 1) ELF section header sh_entsize: Ideally this would be used almost
1688  *    everywhere.  But unfortunately the toolchains make it difficult.  The
1689  *    assembler .[push]section directive syntax only takes entsize when
1690  *    combined with SHF_MERGE.  But Clang disallows combining SHF_MERGE with
1691  *    SHF_WRITE.  And some special sections do need to be writable.
1692  *
1693  *    Another place this wouldn't work is .altinstr_replacement, whose entries
1694  *    don't have a fixed size.
1695  *
1696  * 2) ANNOTATE_DATA_SPECIAL: This is a lightweight objtool annotation which
1697  *    points to the beginning of each entry.  The size of the entry is then
1698  *    inferred by the location of the subsequent annotation (or end of
1699  *    section).
1700  *
1701  * 3) Simple array of pointers: If the special section is just a basic array of
1702  *    pointers, the entry size can be inferred by the number of relocations.
1703  *    No annotations needed.
1704  *
1705  * Note I also tried to create per-entry symbols at the time of creation, in
1706  * the original [inline] asm.  Unfortunately, creating uniquely named symbols
1707  * is trickier than one might think, especially with Clang inline asm.  I
1708  * eventually just gave up trying to make that work, in favor of using
1709  * ANNOTATE_DATA_SPECIAL and creating the symbols here after the fact.
1710  */
1711 static int create_fake_symbols(struct elf *elf)
1712 {
1713 	struct section *sec;
1714 	struct reloc *reloc;
1715 
1716 	/*
1717 	 * 1) Make symbols for all the ANNOTATE_DATA_SPECIAL entries:
1718 	 */
1719 
1720 	sec = find_section_by_name(elf, ".discard.annotate_data");
1721 	if (!sec || !sec->rsec)
1722 		goto entsize;
1723 
1724 	for_each_reloc(sec->rsec, reloc) {
1725 		unsigned long offset, size;
1726 		struct reloc *next_reloc;
1727 		bool last = true;
1728 
1729 		if (annotype(elf, sec, reloc) != ANNOTYPE_DATA_SPECIAL)
1730 			continue;
1731 
1732 		offset = reloc_addend(reloc);
1733 
1734 		/*
1735 		 * Find the start of the next entry so the fake symbol size can
1736 		 * be calculated.
1737 		 */
1738 		next_reloc = reloc;
1739 		for_each_reloc_continue(sec->rsec, next_reloc) {
1740 			if (annotype(elf, sec, next_reloc) != ANNOTYPE_DATA_SPECIAL ||
1741 			    next_reloc->sym->sec != reloc->sym->sec)
1742 				continue;
1743 
1744 			size = reloc_addend(next_reloc) - offset;
1745 			last = false;
1746 			break;
1747 		}
1748 
1749 		/*
1750 		 * If no next entry found, this is the last entry, so its size
1751 		 * is from the current offset to the end of the section.
1752 		 */
1753 		if (last)
1754 			size = sec_size(reloc->sym->sec) - offset;
1755 
1756 		if (create_fake_symbol(elf, reloc->sym->sec, offset, size))
1757 			return -1;
1758 	}
1759 
1760 	/*
1761 	 * 2) Make symbols for sh_entsize, and simple arrays of pointers:
1762 	 */
1763 entsize:
1764 	for_each_sec(elf, sec) {
1765 		unsigned int entry_size;
1766 		unsigned long offset;
1767 
1768 		if (!is_special_section(sec))
1769 			continue;
1770 
1771 		/* Skip sections already handled by step 1 above */
1772 		if (has_fake_symbols(sec))
1773 			continue;
1774 
1775 		if (!sec->rsec) {
1776 			ERROR("%s: missing special section relocations", sec->name);
1777 			return -1;
1778 		}
1779 
1780 		entry_size = sec->sh.sh_entsize;
1781 		if (!entry_size) {
1782 			entry_size = arch_reloc_size(sec->rsec->relocs);
1783 			if (sec_size(sec) != entry_size * sec_num_entries(sec->rsec)) {
1784 				ERROR("%s: missing special section entsize or annotations", sec->name);
1785 				return -1;
1786 			}
1787 		}
1788 
1789 		for (offset = 0; offset < sec_size(sec); offset += entry_size) {
1790 			if (create_fake_symbol(elf, sec, offset, entry_size))
1791 				return -1;
1792 		}
1793 	}
1794 
1795 	return 0;
1796 }
1797 
1798 /* Keep a special section entry if it references an included function */
1799 static bool should_keep_special_sym(struct elf *elf, struct symbol *sym)
1800 {
1801 	bool annotate_insn = !strcmp(sym->sec->name, ".discard.annotate_insn");
1802 	struct reloc *reloc;
1803 
1804 	if (is_sec_sym(sym) || !sym->sec->rsec)
1805 		return false;
1806 
1807 	sym_for_each_reloc(elf, sym, reloc) {
1808 		if (convert_reloc_sym(elf, reloc))
1809 			continue;
1810 
1811 		if (!reloc->sym->clone || is_undef_sym(reloc->sym->clone))
1812 			continue;
1813 
1814 		/*
1815 		 * Keep special section references to cloned functions.
1816 		 * In some cases annotate_insn can also reference cloned alt
1817 		 * replacement fake symbols; keep those references as well.
1818 		 */
1819 		if (is_func_sym(reloc->sym) ||
1820 		    (annotate_insn && is_notype_sym(reloc->sym)))
1821 			return true;
1822 	}
1823 
1824 	return false;
1825 }
1826 
1827 /*
1828  * Klp relocations aren't allowed for __jump_table and .static_call_sites if
1829  * the referenced symbol lives in a kernel module, because such klp relocs may
1830  * be applied after static branch/call init, resulting in code corruption.
1831  *
1832  * Validate a special section entry to avoid that.  Note that an inert
1833  * tracepoint or pr_debug() is harmless enough, in that case just skip the
1834  * entry and print a warning.  Otherwise, return an error.
1835  *
1836  * TODO: This is only a temporary limitation which will be fixed when livepatch
1837  * adds support for submodules: fully self-contained modules which are embedded
1838  * in the top-level livepatch module's data and which can be loaded on demand
1839  * when their corresponding to-be-patched module gets loaded.  Then klp relocs
1840  * can be retired.
1841  *
1842  * Return:
1843  *   -1: error: validation failed
1844  *    1: warning: disabled tracepoint or pr_debug()
1845  *    0: success
1846  */
1847 static int validate_special_section_klp_reloc(struct elfs *e, struct symbol *sym)
1848 {
1849 	bool static_branch = !strcmp(sym->sec->name, "__jump_table");
1850 	bool static_call   = !strcmp(sym->sec->name, ".static_call_sites");
1851 	const char *code_sym = NULL;
1852 	unsigned long code_offset = 0;
1853 	struct reloc *reloc;
1854 	int ret = 0;
1855 
1856 	if (!static_branch && !static_call)
1857 		return 0;
1858 
1859 	sym_for_each_reloc(e->patched, sym, reloc) {
1860 		const char *sym_modname;
1861 		struct export *export;
1862 
1863 		if (convert_reloc_sym(e->patched, reloc))
1864 			continue;
1865 
1866 		/* Static branch/call keys are always STT_OBJECT */
1867 		if (reloc->sym->type != STT_OBJECT) {
1868 
1869 			/* Save code location which can be printed below */
1870 			if (reloc->sym->type == STT_FUNC && !code_sym) {
1871 				code_sym = reloc->sym->name;
1872 				code_offset = reloc_addend(reloc);
1873 			}
1874 
1875 			continue;
1876 		}
1877 
1878 		if (!klp_reloc_needed(reloc))
1879 			continue;
1880 
1881 		export = find_export(reloc->sym);
1882 		if (export) {
1883 			sym_modname = export->mod;
1884 		} else {
1885 			sym_modname = find_modname(e);
1886 			if (!sym_modname)
1887 				return -1;
1888 		}
1889 
1890 		/* vmlinux keys are ok */
1891 		if (!strcmp(sym_modname, "vmlinux"))
1892 			continue;
1893 
1894 		if (!code_sym)
1895 			code_sym = "<unknown>";
1896 
1897 		if (static_branch) {
1898 			if (strstarts(reloc->sym->name, "__tracepoint_")) {
1899 				WARN("%s: disabling unsupported tracepoint %s",
1900 				     code_sym, reloc->sym->name + 13);
1901 				ret = 1;
1902 				continue;
1903 			}
1904 
1905 			if (strstr(reloc->sym->name, "__UNIQUE_ID_ddebug_")) {
1906 				WARN("%s: disabling unsupported pr_debug()",
1907 				     code_sym);
1908 				ret = 1;
1909 				continue;
1910 			}
1911 
1912 			ERROR("%s+0x%lx: unsupported static branch key %s.  Use static_key_enabled() instead",
1913 			      code_sym, code_offset, reloc->sym->name);
1914 			return -1;
1915 		}
1916 
1917 		/* static call */
1918 		if (strstarts(reloc->sym->name, "__SCK__tp_func_")) {
1919 			ret = 1;
1920 			continue;
1921 		}
1922 
1923 		ERROR("%s()+0x%lx: unsupported static call key %s.  Use KLP_STATIC_CALL() instead",
1924 		      code_sym, code_offset, reloc->sym->name);
1925 		return -1;
1926 	}
1927 
1928 	return ret;
1929 }
1930 
1931 static int clone_special_section(struct elfs *e, struct section *patched_sec)
1932 {
1933 	struct symbol *patched_sym;
1934 
1935 	/*
1936 	 * Extract all special section symbols (and their dependencies) which
1937 	 * reference included functions.
1938 	 */
1939 	sec_for_each_sym(patched_sec, patched_sym) {
1940 		int ret;
1941 
1942 		if (!is_object_sym(patched_sym))
1943 			continue;
1944 
1945 		if (!should_keep_special_sym(e->patched, patched_sym))
1946 			continue;
1947 
1948 		ret = validate_special_section_klp_reloc(e, patched_sym);
1949 		if (ret < 0)
1950 			return -1;
1951 		if (ret > 0)
1952 			continue;
1953 
1954 		if (!clone_symbol(e, patched_sym, true))
1955 			return -1;
1956 	}
1957 
1958 	return 0;
1959 }
1960 
1961 /* Extract only the needed bits from special sections */
1962 static int clone_special_sections(struct elfs *e)
1963 {
1964 	struct section *sec, *annotate_insn = NULL;
1965 
1966 	for_each_sec(e->patched, sec) {
1967 		if (is_special_section(sec)) {
1968 			if (!strcmp(sec->name, ".discard.annotate_insn")) {
1969 				annotate_insn = sec;
1970 				continue;
1971 			}
1972 			if (clone_special_section(e, sec))
1973 				return -1;
1974 		}
1975 	}
1976 
1977 	/*
1978 	 * Do .discard.annotate_insn last, it can reference other special
1979 	 * sections (alt replacements) so they need to be cloned first.
1980 	 */
1981 	if (annotate_insn) {
1982 		if (clone_special_section(e, annotate_insn))
1983 			return -1;
1984 	}
1985 
1986 	return 0;
1987 }
1988 
1989 /*
1990  * Create .init.klp_objects and .init.klp_funcs sections which are intermediate
1991  * sections provided as input to the patch module's init code for building the
1992  * klp_patch, klp_object and klp_func structs for the livepatch API.
1993  */
1994 static int create_klp_sections(struct elfs *e)
1995 {
1996 	size_t obj_size  = sizeof(struct klp_object_ext);
1997 	size_t func_size = sizeof(struct klp_func_ext);
1998 	struct section *obj_sec, *funcs_sec, *str_sec;
1999 	struct symbol *funcs_sym, *str_sym, *sym;
2000 	char sym_name[SYM_NAME_LEN];
2001 	unsigned int nr_funcs = 0;
2002 	const char *modname;
2003 	void *obj_data;
2004 	s64 addend;
2005 
2006 	obj_sec  = elf_create_section_pair(e->out, KLP_OBJECTS_SEC, obj_size, 0, 0);
2007 	if (!obj_sec)
2008 		return -1;
2009 
2010 	funcs_sec = elf_create_section_pair(e->out, KLP_FUNCS_SEC, func_size, 0, 0);
2011 	if (!funcs_sec)
2012 		return -1;
2013 
2014 	funcs_sym = elf_create_section_symbol(e->out, funcs_sec);
2015 	if (!funcs_sym)
2016 		return -1;
2017 
2018 	str_sec = elf_create_section(e->out, KLP_STRINGS_SEC, 0, 0,
2019 				     SHT_PROGBITS, 1,
2020 				     SHF_ALLOC | SHF_STRINGS | SHF_MERGE);
2021 	if (!str_sec)
2022 		return -1;
2023 
2024 	if (elf_add_string(e->out, str_sec, "") == -1)
2025 		return -1;
2026 
2027 	str_sym = elf_create_section_symbol(e->out, str_sec);
2028 	if (!str_sym)
2029 		return -1;
2030 
2031 	/* allocate klp_object_ext */
2032 	obj_data = elf_add_data(e->out, obj_sec, NULL, obj_size);
2033 	if (!obj_data)
2034 		return -1;
2035 
2036 	modname = find_modname(e);
2037 	if (!modname)
2038 		return -1;
2039 
2040 	/* klp_object_ext.name */
2041 	if (strcmp(modname, "vmlinux")) {
2042 		addend = elf_add_string(e->out, str_sec, modname);
2043 		if (addend == -1)
2044 			return -1;
2045 
2046 		if (!elf_create_reloc(e->out, obj_sec,
2047 				      offsetof(struct klp_object_ext, name),
2048 				      str_sym, addend, R_ABS64))
2049 			return -1;
2050 	}
2051 
2052 	/* klp_object_ext.funcs */
2053 	if (!elf_create_reloc(e->out, obj_sec, offsetof(struct klp_object_ext, funcs),
2054 			      funcs_sym, 0, R_ABS64))
2055 		return -1;
2056 
2057 	for_each_sym(e->out, sym) {
2058 		unsigned long offset = nr_funcs * func_size;
2059 		unsigned long sympos;
2060 		void *func_data;
2061 
2062 		if (!is_func_sym(sym) || is_cold_func(sym) ||
2063 		    !sym->clone || !sym->clone->changed)
2064 			continue;
2065 
2066 		/* allocate klp_func_ext */
2067 		func_data = elf_add_data(e->out, funcs_sec, NULL, func_size);
2068 		if (!func_data)
2069 			return -1;
2070 
2071 		/* klp_func_ext.old_name */
2072 		addend = elf_add_string(e->out, str_sec, sym->clone->twin->name);
2073 		if (addend == -1)
2074 			return -1;
2075 
2076 		if (!elf_create_reloc(e->out, funcs_sec,
2077 				      offset + offsetof(struct klp_func_ext, old_name),
2078 				      str_sym, addend, R_ABS64))
2079 			return -1;
2080 
2081 		/* klp_func_ext.new_func */
2082 		if (!elf_create_reloc(e->out, funcs_sec,
2083 				      offset + offsetof(struct klp_func_ext, new_func),
2084 				      sym, 0, R_ABS64))
2085 			return -1;
2086 
2087 		/* klp_func_ext.sympos */
2088 		BUILD_BUG_ON(sizeof(sympos) != sizeof_field(struct klp_func_ext, sympos));
2089 		sympos = klp_find_sympos(e->orig, sym->clone->twin);
2090 		if (sympos == ULONG_MAX)
2091 			return -1;
2092 		memcpy(func_data + offsetof(struct klp_func_ext, sympos), &sympos,
2093 		       sizeof_field(struct klp_func_ext, sympos));
2094 
2095 		nr_funcs++;
2096 	}
2097 
2098 	/* klp_object_ext.nr_funcs */
2099 	BUILD_BUG_ON(sizeof(nr_funcs) != sizeof_field(struct klp_object_ext, nr_funcs));
2100 	memcpy(obj_data + offsetof(struct klp_object_ext, nr_funcs), &nr_funcs,
2101 	       sizeof_field(struct klp_object_ext, nr_funcs));
2102 
2103 	/*
2104 	 * Find callback pointers created by KLP_PRE_PATCH_CALLBACK() and
2105 	 * friends, and add them to the klp object.
2106 	 */
2107 
2108 	if (snprintf_check(sym_name, SYM_NAME_LEN, KLP_PRE_PATCH_PREFIX "%s", modname))
2109 		return -1;
2110 
2111 	sym = find_symbol_by_name(e->out, sym_name);
2112 	if (sym) {
2113 		struct reloc *reloc;
2114 
2115 		reloc = find_reloc_by_dest(e->out, sym->sec, sym->offset);
2116 
2117 		if (!elf_create_reloc(e->out, obj_sec,
2118 				      offsetof(struct klp_object_ext, callbacks) +
2119 				      offsetof(struct klp_callbacks, pre_patch),
2120 				      reloc->sym, reloc_addend(reloc), R_ABS64))
2121 			return -1;
2122 	}
2123 
2124 	if (snprintf_check(sym_name, SYM_NAME_LEN, KLP_POST_PATCH_PREFIX "%s", modname))
2125 		return -1;
2126 
2127 	sym = find_symbol_by_name(e->out, sym_name);
2128 	if (sym) {
2129 		struct reloc *reloc;
2130 
2131 		reloc = find_reloc_by_dest(e->out, sym->sec, sym->offset);
2132 
2133 		if (!elf_create_reloc(e->out, obj_sec,
2134 				      offsetof(struct klp_object_ext, callbacks) +
2135 				      offsetof(struct klp_callbacks, post_patch),
2136 				      reloc->sym, reloc_addend(reloc), R_ABS64))
2137 			return -1;
2138 	}
2139 
2140 	if (snprintf_check(sym_name, SYM_NAME_LEN, KLP_PRE_UNPATCH_PREFIX "%s", modname))
2141 		return -1;
2142 
2143 	sym = find_symbol_by_name(e->out, sym_name);
2144 	if (sym) {
2145 		struct reloc *reloc;
2146 
2147 		reloc = find_reloc_by_dest(e->out, sym->sec, sym->offset);
2148 
2149 		if (!elf_create_reloc(e->out, obj_sec,
2150 				      offsetof(struct klp_object_ext, callbacks) +
2151 				      offsetof(struct klp_callbacks, pre_unpatch),
2152 				      reloc->sym, reloc_addend(reloc), R_ABS64))
2153 			return -1;
2154 	}
2155 
2156 	if (snprintf_check(sym_name, SYM_NAME_LEN, KLP_POST_UNPATCH_PREFIX "%s", modname))
2157 		return -1;
2158 
2159 	sym = find_symbol_by_name(e->out, sym_name);
2160 	if (sym) {
2161 		struct reloc *reloc;
2162 
2163 		reloc = find_reloc_by_dest(e->out, sym->sec, sym->offset);
2164 
2165 		if (!elf_create_reloc(e->out, obj_sec,
2166 				      offsetof(struct klp_object_ext, callbacks) +
2167 				      offsetof(struct klp_callbacks, post_unpatch),
2168 				      reloc->sym, reloc_addend(reloc), R_ABS64))
2169 			return -1;
2170 	}
2171 
2172 	return 0;
2173 }
2174 
2175 /*
2176  * Copy all .modinfo import_ns= tags to ensure all namespaced exported symbols
2177  * can be accessed via normal relocs.
2178  */
2179 static int copy_import_ns(struct elfs *e)
2180 {
2181 	struct section *patched_sec, *out_sec = NULL;
2182 	char *import_ns, *data_end;
2183 
2184 	patched_sec = find_section_by_name(e->patched, ".modinfo");
2185 	if (!patched_sec)
2186 		return 0;
2187 
2188 	import_ns = patched_sec->data->d_buf;
2189 	if (!import_ns)
2190 		return 0;
2191 
2192 	for (data_end = import_ns + sec_size(patched_sec);
2193 	     import_ns < data_end;
2194 	     import_ns += strlen(import_ns) + 1) {
2195 
2196 		import_ns = memmem(import_ns, data_end - import_ns, "import_ns=", 10);
2197 		if (!import_ns)
2198 			return 0;
2199 
2200 		if (!out_sec) {
2201 			out_sec = find_section_by_name(e->out, ".modinfo");
2202 			if (!out_sec) {
2203 				out_sec = elf_create_section(e->out, ".modinfo", 0,
2204 							     patched_sec->sh.sh_entsize,
2205 							     patched_sec->sh.sh_type,
2206 							     patched_sec->sh.sh_addralign,
2207 							     patched_sec->sh.sh_flags);
2208 				if (!out_sec)
2209 					return -1;
2210 			}
2211 		}
2212 
2213 		if (!elf_add_data(e->out, out_sec, import_ns, strlen(import_ns) + 1))
2214 			return -1;
2215 	}
2216 
2217 	return 0;
2218 }
2219 
2220 int cmd_klp_diff(int argc, const char **argv)
2221 {
2222 	struct elfs e = {0};
2223 	int ret;
2224 
2225 	argc = parse_options(argc, argv, klp_diff_options, klp_diff_usage, 0);
2226 	if (argc != 3)
2227 		usage_with_options(klp_diff_usage, klp_diff_options);
2228 
2229 	if (debug) {
2230 		debug_correlate = true;
2231 		debug_clone = true;
2232 	}
2233 
2234 	objname = argv[0];
2235 
2236 	e.orig = elf_open_read(argv[0], O_RDONLY);
2237 	e.patched = elf_open_read(argv[1], O_RDONLY);
2238 	e.out = NULL;
2239 
2240 	if (!e.orig || !e.patched)
2241 		return -1;
2242 
2243 	if (klp_sympos_init(e.orig))
2244 		return -1;
2245 
2246 	if (read_exports())
2247 		return -1;
2248 
2249 	if (read_sym_checksums(e.orig))
2250 		return -1;
2251 
2252 	if (read_sym_checksums(e.patched))
2253 		return -1;
2254 
2255 	if (correlate_symbols(&e))
2256 		return -1;
2257 
2258 	ret = mark_changed_functions(&e);
2259 	if (ret < 0)
2260 		return -1;
2261 	if (ret > 0)
2262 		return 0;
2263 
2264 	e.out = elf_create_file(&e.orig->ehdr, argv[2]);
2265 	if (!e.out)
2266 		return -1;
2267 
2268 	/*
2269 	 * Special section fake symbols are needed so that individual special
2270 	 * section entries can be extracted by clone_special_sections().
2271 	 *
2272 	 * Note the fake symbols are also needed by clone_included_functions()
2273 	 * because __WARN_printf() call sites add references to bug table
2274 	 * entries in the calling functions.
2275 	 */
2276 	if (create_fake_symbols(e.patched))
2277 		return -1;
2278 
2279 	if (clone_included_functions(&e))
2280 		return -1;
2281 
2282 	if (clone_special_sections(&e))
2283 		return -1;
2284 
2285 	if (create_klp_sections(&e))
2286 		return -1;
2287 
2288 	if (copy_import_ns(&e))
2289 		return -1;
2290 
2291 	if  (elf_write(e.out))
2292 		return -1;
2293 
2294 	return elf_close(e.out);
2295 }
2296