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