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