xref: /linux/tools/objtool/check.c (revision 2f804aca48322f02a8f44cca540663845ee80fb1)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C) 2015-2017 Josh Poimboeuf <jpoimboe@redhat.com>
4  */
5 
6 #include <string.h>
7 #include <stdlib.h>
8 #include <inttypes.h>
9 #include <sys/mman.h>
10 
11 #include <arch/elf.h>
12 #include <objtool/builtin.h>
13 #include <objtool/cfi.h>
14 #include <objtool/arch.h>
15 #include <objtool/check.h>
16 #include <objtool/special.h>
17 #include <objtool/warn.h>
18 #include <objtool/endianness.h>
19 
20 #include <linux/objtool_types.h>
21 #include <linux/hashtable.h>
22 #include <linux/kernel.h>
23 #include <linux/static_call_types.h>
24 
25 struct alternative {
26 	struct alternative *next;
27 	struct instruction *insn;
28 	bool skip_orig;
29 };
30 
31 static unsigned long nr_cfi, nr_cfi_reused, nr_cfi_cache;
32 
33 static struct cfi_init_state initial_func_cfi;
34 static struct cfi_state init_cfi;
35 static struct cfi_state func_cfi;
36 
37 struct instruction *find_insn(struct objtool_file *file,
38 			      struct section *sec, unsigned long offset)
39 {
40 	struct instruction *insn;
41 
42 	hash_for_each_possible(file->insn_hash, insn, hash, sec_offset_hash(sec, offset)) {
43 		if (insn->sec == sec && insn->offset == offset)
44 			return insn;
45 	}
46 
47 	return NULL;
48 }
49 
50 struct instruction *next_insn_same_sec(struct objtool_file *file,
51 				       struct instruction *insn)
52 {
53 	if (insn->idx == INSN_CHUNK_MAX)
54 		return find_insn(file, insn->sec, insn->offset + insn->len);
55 
56 	insn++;
57 	if (!insn->len)
58 		return NULL;
59 
60 	return insn;
61 }
62 
63 static struct instruction *next_insn_same_func(struct objtool_file *file,
64 					       struct instruction *insn)
65 {
66 	struct instruction *next = next_insn_same_sec(file, insn);
67 	struct symbol *func = insn_func(insn);
68 
69 	if (!func)
70 		return NULL;
71 
72 	if (next && insn_func(next) == func)
73 		return next;
74 
75 	/* Check if we're already in the subfunction: */
76 	if (func == func->cfunc)
77 		return NULL;
78 
79 	/* Move to the subfunction: */
80 	return find_insn(file, func->cfunc->sec, func->cfunc->offset);
81 }
82 
83 static struct instruction *prev_insn_same_sec(struct objtool_file *file,
84 					      struct instruction *insn)
85 {
86 	if (insn->idx == 0) {
87 		if (insn->prev_len)
88 			return find_insn(file, insn->sec, insn->offset - insn->prev_len);
89 		return NULL;
90 	}
91 
92 	return insn - 1;
93 }
94 
95 static struct instruction *prev_insn_same_sym(struct objtool_file *file,
96 					      struct instruction *insn)
97 {
98 	struct instruction *prev = prev_insn_same_sec(file, insn);
99 
100 	if (prev && insn_func(prev) == insn_func(insn))
101 		return prev;
102 
103 	return NULL;
104 }
105 
106 #define for_each_insn(file, insn)					\
107 	for (struct section *__sec, *__fake = (struct section *)1;	\
108 	     __fake; __fake = NULL)					\
109 		for_each_sec(file, __sec)				\
110 			sec_for_each_insn(file, __sec, insn)
111 
112 #define func_for_each_insn(file, func, insn)				\
113 	for (insn = find_insn(file, func->sec, func->offset);		\
114 	     insn;							\
115 	     insn = next_insn_same_func(file, insn))
116 
117 #define sym_for_each_insn(file, sym, insn)				\
118 	for (insn = find_insn(file, sym->sec, sym->offset);		\
119 	     insn && insn->offset < sym->offset + sym->len;		\
120 	     insn = next_insn_same_sec(file, insn))
121 
122 #define sym_for_each_insn_continue_reverse(file, sym, insn)		\
123 	for (insn = prev_insn_same_sec(file, insn);			\
124 	     insn && insn->offset >= sym->offset;			\
125 	     insn = prev_insn_same_sec(file, insn))
126 
127 #define sec_for_each_insn_from(file, insn)				\
128 	for (; insn; insn = next_insn_same_sec(file, insn))
129 
130 #define sec_for_each_insn_continue(file, insn)				\
131 	for (insn = next_insn_same_sec(file, insn); insn;		\
132 	     insn = next_insn_same_sec(file, insn))
133 
134 static inline struct symbol *insn_call_dest(struct instruction *insn)
135 {
136 	if (insn->type == INSN_JUMP_DYNAMIC ||
137 	    insn->type == INSN_CALL_DYNAMIC)
138 		return NULL;
139 
140 	return insn->_call_dest;
141 }
142 
143 static inline struct reloc *insn_jump_table(struct instruction *insn)
144 {
145 	if (insn->type == INSN_JUMP_DYNAMIC ||
146 	    insn->type == INSN_CALL_DYNAMIC)
147 		return insn->_jump_table;
148 
149 	return NULL;
150 }
151 
152 static bool is_jump_table_jump(struct instruction *insn)
153 {
154 	struct alt_group *alt_group = insn->alt_group;
155 
156 	if (insn_jump_table(insn))
157 		return true;
158 
159 	/* Retpoline alternative for a jump table? */
160 	return alt_group && alt_group->orig_group &&
161 	       insn_jump_table(alt_group->orig_group->first_insn);
162 }
163 
164 static bool is_sibling_call(struct instruction *insn)
165 {
166 	/*
167 	 * Assume only STT_FUNC calls have jump-tables.
168 	 */
169 	if (insn_func(insn)) {
170 		/* An indirect jump is either a sibling call or a jump to a table. */
171 		if (insn->type == INSN_JUMP_DYNAMIC)
172 			return !is_jump_table_jump(insn);
173 	}
174 
175 	/* add_jump_destinations() sets insn_call_dest(insn) for sibling calls. */
176 	return (is_static_jump(insn) && insn_call_dest(insn));
177 }
178 
179 /*
180  * This checks to see if the given function is a "noreturn" function.
181  *
182  * For global functions which are outside the scope of this object file, we
183  * have to keep a manual list of them.
184  *
185  * For local functions, we have to detect them manually by simply looking for
186  * the lack of a return instruction.
187  */
188 static bool __dead_end_function(struct objtool_file *file, struct symbol *func,
189 				int recursion)
190 {
191 	int i;
192 	struct instruction *insn;
193 	bool empty = true;
194 
195 	/*
196 	 * Unfortunately these have to be hard coded because the noreturn
197 	 * attribute isn't provided in ELF data. Keep 'em sorted.
198 	 */
199 	static const char * const global_noreturns[] = {
200 		"__invalid_creds",
201 		"__module_put_and_kthread_exit",
202 		"__reiserfs_panic",
203 		"__stack_chk_fail",
204 		"__ubsan_handle_builtin_unreachable",
205 		"arch_call_rest_init",
206 		"arch_cpu_idle_dead",
207 		"btrfs_assertfail",
208 		"cpu_bringup_and_idle",
209 		"cpu_startup_entry",
210 		"do_exit",
211 		"do_group_exit",
212 		"do_task_dead",
213 		"ex_handler_msr_mce",
214 		"fortify_panic",
215 		"hlt_play_dead",
216 		"hv_ghcb_terminate",
217 		"kthread_complete_and_exit",
218 		"kthread_exit",
219 		"kunit_try_catch_throw",
220 		"lbug_with_loc",
221 		"machine_real_restart",
222 		"make_task_dead",
223 		"mpt_halt_firmware",
224 		"nmi_panic_self_stop",
225 		"panic",
226 		"panic_smp_self_stop",
227 		"rest_init",
228 		"resume_play_dead",
229 		"rewind_stack_and_make_dead",
230 		"sev_es_terminate",
231 		"snp_abort",
232 		"start_kernel",
233 		"stop_this_cpu",
234 		"usercopy_abort",
235 		"x86_64_start_kernel",
236 		"x86_64_start_reservations",
237 		"xen_cpu_bringup_again",
238 		"xen_start_kernel",
239 	};
240 
241 	if (!func)
242 		return false;
243 
244 	if (func->bind == STB_GLOBAL || func->bind == STB_WEAK)
245 		for (i = 0; i < ARRAY_SIZE(global_noreturns); i++)
246 			if (!strcmp(func->name, global_noreturns[i]))
247 				return true;
248 
249 	if (func->bind == STB_WEAK)
250 		return false;
251 
252 	if (!func->len)
253 		return false;
254 
255 	insn = find_insn(file, func->sec, func->offset);
256 	if (!insn || !insn_func(insn))
257 		return false;
258 
259 	func_for_each_insn(file, func, insn) {
260 		empty = false;
261 
262 		if (insn->type == INSN_RETURN)
263 			return false;
264 	}
265 
266 	if (empty)
267 		return false;
268 
269 	/*
270 	 * A function can have a sibling call instead of a return.  In that
271 	 * case, the function's dead-end status depends on whether the target
272 	 * of the sibling call returns.
273 	 */
274 	func_for_each_insn(file, func, insn) {
275 		if (is_sibling_call(insn)) {
276 			struct instruction *dest = insn->jump_dest;
277 
278 			if (!dest)
279 				/* sibling call to another file */
280 				return false;
281 
282 			/* local sibling call */
283 			if (recursion == 5) {
284 				/*
285 				 * Infinite recursion: two functions have
286 				 * sibling calls to each other.  This is a very
287 				 * rare case.  It means they aren't dead ends.
288 				 */
289 				return false;
290 			}
291 
292 			return __dead_end_function(file, insn_func(dest), recursion+1);
293 		}
294 	}
295 
296 	return true;
297 }
298 
299 static bool dead_end_function(struct objtool_file *file, struct symbol *func)
300 {
301 	return __dead_end_function(file, func, 0);
302 }
303 
304 static void init_cfi_state(struct cfi_state *cfi)
305 {
306 	int i;
307 
308 	for (i = 0; i < CFI_NUM_REGS; i++) {
309 		cfi->regs[i].base = CFI_UNDEFINED;
310 		cfi->vals[i].base = CFI_UNDEFINED;
311 	}
312 	cfi->cfa.base = CFI_UNDEFINED;
313 	cfi->drap_reg = CFI_UNDEFINED;
314 	cfi->drap_offset = -1;
315 }
316 
317 static void init_insn_state(struct objtool_file *file, struct insn_state *state,
318 			    struct section *sec)
319 {
320 	memset(state, 0, sizeof(*state));
321 	init_cfi_state(&state->cfi);
322 
323 	/*
324 	 * We need the full vmlinux for noinstr validation, otherwise we can
325 	 * not correctly determine insn_call_dest(insn)->sec (external symbols
326 	 * do not have a section).
327 	 */
328 	if (opts.link && opts.noinstr && sec)
329 		state->noinstr = sec->noinstr;
330 }
331 
332 static struct cfi_state *cfi_alloc(void)
333 {
334 	struct cfi_state *cfi = calloc(sizeof(struct cfi_state), 1);
335 	if (!cfi) {
336 		WARN("calloc failed");
337 		exit(1);
338 	}
339 	nr_cfi++;
340 	return cfi;
341 }
342 
343 static int cfi_bits;
344 static struct hlist_head *cfi_hash;
345 
346 static inline bool cficmp(struct cfi_state *cfi1, struct cfi_state *cfi2)
347 {
348 	return memcmp((void *)cfi1 + sizeof(cfi1->hash),
349 		      (void *)cfi2 + sizeof(cfi2->hash),
350 		      sizeof(struct cfi_state) - sizeof(struct hlist_node));
351 }
352 
353 static inline u32 cfi_key(struct cfi_state *cfi)
354 {
355 	return jhash((void *)cfi + sizeof(cfi->hash),
356 		     sizeof(*cfi) - sizeof(cfi->hash), 0);
357 }
358 
359 static struct cfi_state *cfi_hash_find_or_add(struct cfi_state *cfi)
360 {
361 	struct hlist_head *head = &cfi_hash[hash_min(cfi_key(cfi), cfi_bits)];
362 	struct cfi_state *obj;
363 
364 	hlist_for_each_entry(obj, head, hash) {
365 		if (!cficmp(cfi, obj)) {
366 			nr_cfi_cache++;
367 			return obj;
368 		}
369 	}
370 
371 	obj = cfi_alloc();
372 	*obj = *cfi;
373 	hlist_add_head(&obj->hash, head);
374 
375 	return obj;
376 }
377 
378 static void cfi_hash_add(struct cfi_state *cfi)
379 {
380 	struct hlist_head *head = &cfi_hash[hash_min(cfi_key(cfi), cfi_bits)];
381 
382 	hlist_add_head(&cfi->hash, head);
383 }
384 
385 static void *cfi_hash_alloc(unsigned long size)
386 {
387 	cfi_bits = max(10, ilog2(size));
388 	cfi_hash = mmap(NULL, sizeof(struct hlist_head) << cfi_bits,
389 			PROT_READ|PROT_WRITE,
390 			MAP_PRIVATE|MAP_ANON, -1, 0);
391 	if (cfi_hash == (void *)-1L) {
392 		WARN("mmap fail cfi_hash");
393 		cfi_hash = NULL;
394 	}  else if (opts.stats) {
395 		printf("cfi_bits: %d\n", cfi_bits);
396 	}
397 
398 	return cfi_hash;
399 }
400 
401 static unsigned long nr_insns;
402 static unsigned long nr_insns_visited;
403 
404 /*
405  * Call the arch-specific instruction decoder for all the instructions and add
406  * them to the global instruction list.
407  */
408 static int decode_instructions(struct objtool_file *file)
409 {
410 	struct section *sec;
411 	struct symbol *func;
412 	unsigned long offset;
413 	struct instruction *insn;
414 	int ret;
415 
416 	for_each_sec(file, sec) {
417 		struct instruction *insns = NULL;
418 		u8 prev_len = 0;
419 		u8 idx = 0;
420 
421 		if (!(sec->sh.sh_flags & SHF_EXECINSTR))
422 			continue;
423 
424 		if (strcmp(sec->name, ".altinstr_replacement") &&
425 		    strcmp(sec->name, ".altinstr_aux") &&
426 		    strncmp(sec->name, ".discard.", 9))
427 			sec->text = true;
428 
429 		if (!strcmp(sec->name, ".noinstr.text") ||
430 		    !strcmp(sec->name, ".entry.text") ||
431 		    !strcmp(sec->name, ".cpuidle.text") ||
432 		    !strncmp(sec->name, ".text.__x86.", 12))
433 			sec->noinstr = true;
434 
435 		/*
436 		 * .init.text code is ran before userspace and thus doesn't
437 		 * strictly need retpolines, except for modules which are
438 		 * loaded late, they very much do need retpoline in their
439 		 * .init.text
440 		 */
441 		if (!strcmp(sec->name, ".init.text") && !opts.module)
442 			sec->init = true;
443 
444 		for (offset = 0; offset < sec->sh.sh_size; offset += insn->len) {
445 			if (!insns || idx == INSN_CHUNK_MAX) {
446 				insns = calloc(sizeof(*insn), INSN_CHUNK_SIZE);
447 				if (!insns) {
448 					WARN("malloc failed");
449 					return -1;
450 				}
451 				idx = 0;
452 			} else {
453 				idx++;
454 			}
455 			insn = &insns[idx];
456 			insn->idx = idx;
457 
458 			INIT_LIST_HEAD(&insn->call_node);
459 			insn->sec = sec;
460 			insn->offset = offset;
461 			insn->prev_len = prev_len;
462 
463 			ret = arch_decode_instruction(file, sec, offset,
464 						      sec->sh.sh_size - offset,
465 						      insn);
466 			if (ret)
467 				return ret;
468 
469 			prev_len = insn->len;
470 
471 			/*
472 			 * By default, "ud2" is a dead end unless otherwise
473 			 * annotated, because GCC 7 inserts it for certain
474 			 * divide-by-zero cases.
475 			 */
476 			if (insn->type == INSN_BUG)
477 				insn->dead_end = true;
478 
479 			hash_add(file->insn_hash, &insn->hash, sec_offset_hash(sec, insn->offset));
480 			nr_insns++;
481 		}
482 
483 //		printf("%s: last chunk used: %d\n", sec->name, (int)idx);
484 
485 		sec_for_each_sym(sec, func) {
486 			if (func->type != STT_NOTYPE && func->type != STT_FUNC)
487 				continue;
488 
489 			if (func->offset == sec->sh.sh_size) {
490 				/* Heuristic: likely an "end" symbol */
491 				if (func->type == STT_NOTYPE)
492 					continue;
493 				WARN("%s(): STT_FUNC at end of section",
494 				     func->name);
495 				return -1;
496 			}
497 
498 			if (func->return_thunk || func->alias != func)
499 				continue;
500 
501 			if (!find_insn(file, sec, func->offset)) {
502 				WARN("%s(): can't find starting instruction",
503 				     func->name);
504 				return -1;
505 			}
506 
507 			sym_for_each_insn(file, func, insn) {
508 				insn->sym = func;
509 				if (func->type == STT_FUNC &&
510 				    insn->type == INSN_ENDBR &&
511 				    list_empty(&insn->call_node)) {
512 					if (insn->offset == func->offset) {
513 						list_add_tail(&insn->call_node, &file->endbr_list);
514 						file->nr_endbr++;
515 					} else {
516 						file->nr_endbr_int++;
517 					}
518 				}
519 			}
520 		}
521 	}
522 
523 	if (opts.stats)
524 		printf("nr_insns: %lu\n", nr_insns);
525 
526 	return 0;
527 }
528 
529 /*
530  * Read the pv_ops[] .data table to find the static initialized values.
531  */
532 static int add_pv_ops(struct objtool_file *file, const char *symname)
533 {
534 	struct symbol *sym, *func;
535 	unsigned long off, end;
536 	struct reloc *rel;
537 	int idx;
538 
539 	sym = find_symbol_by_name(file->elf, symname);
540 	if (!sym)
541 		return 0;
542 
543 	off = sym->offset;
544 	end = off + sym->len;
545 	for (;;) {
546 		rel = find_reloc_by_dest_range(file->elf, sym->sec, off, end - off);
547 		if (!rel)
548 			break;
549 
550 		func = rel->sym;
551 		if (func->type == STT_SECTION)
552 			func = find_symbol_by_offset(rel->sym->sec, rel->addend);
553 
554 		idx = (rel->offset - sym->offset) / sizeof(unsigned long);
555 
556 		objtool_pv_add(file, idx, func);
557 
558 		off = rel->offset + 1;
559 		if (off > end)
560 			break;
561 	}
562 
563 	return 0;
564 }
565 
566 /*
567  * Allocate and initialize file->pv_ops[].
568  */
569 static int init_pv_ops(struct objtool_file *file)
570 {
571 	static const char *pv_ops_tables[] = {
572 		"pv_ops",
573 		"xen_cpu_ops",
574 		"xen_irq_ops",
575 		"xen_mmu_ops",
576 		NULL,
577 	};
578 	const char *pv_ops;
579 	struct symbol *sym;
580 	int idx, nr;
581 
582 	if (!opts.noinstr)
583 		return 0;
584 
585 	file->pv_ops = NULL;
586 
587 	sym = find_symbol_by_name(file->elf, "pv_ops");
588 	if (!sym)
589 		return 0;
590 
591 	nr = sym->len / sizeof(unsigned long);
592 	file->pv_ops = calloc(sizeof(struct pv_state), nr);
593 	if (!file->pv_ops)
594 		return -1;
595 
596 	for (idx = 0; idx < nr; idx++)
597 		INIT_LIST_HEAD(&file->pv_ops[idx].targets);
598 
599 	for (idx = 0; (pv_ops = pv_ops_tables[idx]); idx++)
600 		add_pv_ops(file, pv_ops);
601 
602 	return 0;
603 }
604 
605 static struct instruction *find_last_insn(struct objtool_file *file,
606 					  struct section *sec)
607 {
608 	struct instruction *insn = NULL;
609 	unsigned int offset;
610 	unsigned int end = (sec->sh.sh_size > 10) ? sec->sh.sh_size - 10 : 0;
611 
612 	for (offset = sec->sh.sh_size - 1; offset >= end && !insn; offset--)
613 		insn = find_insn(file, sec, offset);
614 
615 	return insn;
616 }
617 
618 /*
619  * Mark "ud2" instructions and manually annotated dead ends.
620  */
621 static int add_dead_ends(struct objtool_file *file)
622 {
623 	struct section *sec;
624 	struct reloc *reloc;
625 	struct instruction *insn;
626 
627 	/*
628 	 * Check for manually annotated dead ends.
629 	 */
630 	sec = find_section_by_name(file->elf, ".rela.discard.unreachable");
631 	if (!sec)
632 		goto reachable;
633 
634 	list_for_each_entry(reloc, &sec->reloc_list, list) {
635 		if (reloc->sym->type != STT_SECTION) {
636 			WARN("unexpected relocation symbol type in %s", sec->name);
637 			return -1;
638 		}
639 		insn = find_insn(file, reloc->sym->sec, reloc->addend);
640 		if (insn)
641 			insn = prev_insn_same_sec(file, insn);
642 		else if (reloc->addend == reloc->sym->sec->sh.sh_size) {
643 			insn = find_last_insn(file, reloc->sym->sec);
644 			if (!insn) {
645 				WARN("can't find unreachable insn at %s+0x%" PRIx64,
646 				     reloc->sym->sec->name, reloc->addend);
647 				return -1;
648 			}
649 		} else {
650 			WARN("can't find unreachable insn at %s+0x%" PRIx64,
651 			     reloc->sym->sec->name, reloc->addend);
652 			return -1;
653 		}
654 
655 		insn->dead_end = true;
656 	}
657 
658 reachable:
659 	/*
660 	 * These manually annotated reachable checks are needed for GCC 4.4,
661 	 * where the Linux unreachable() macro isn't supported.  In that case
662 	 * GCC doesn't know the "ud2" is fatal, so it generates code as if it's
663 	 * not a dead end.
664 	 */
665 	sec = find_section_by_name(file->elf, ".rela.discard.reachable");
666 	if (!sec)
667 		return 0;
668 
669 	list_for_each_entry(reloc, &sec->reloc_list, list) {
670 		if (reloc->sym->type != STT_SECTION) {
671 			WARN("unexpected relocation symbol type in %s", sec->name);
672 			return -1;
673 		}
674 		insn = find_insn(file, reloc->sym->sec, reloc->addend);
675 		if (insn)
676 			insn = prev_insn_same_sec(file, insn);
677 		else if (reloc->addend == reloc->sym->sec->sh.sh_size) {
678 			insn = find_last_insn(file, reloc->sym->sec);
679 			if (!insn) {
680 				WARN("can't find reachable insn at %s+0x%" PRIx64,
681 				     reloc->sym->sec->name, reloc->addend);
682 				return -1;
683 			}
684 		} else {
685 			WARN("can't find reachable insn at %s+0x%" PRIx64,
686 			     reloc->sym->sec->name, reloc->addend);
687 			return -1;
688 		}
689 
690 		insn->dead_end = false;
691 	}
692 
693 	return 0;
694 }
695 
696 static int create_static_call_sections(struct objtool_file *file)
697 {
698 	struct section *sec;
699 	struct static_call_site *site;
700 	struct instruction *insn;
701 	struct symbol *key_sym;
702 	char *key_name, *tmp;
703 	int idx;
704 
705 	sec = find_section_by_name(file->elf, ".static_call_sites");
706 	if (sec) {
707 		INIT_LIST_HEAD(&file->static_call_list);
708 		WARN("file already has .static_call_sites section, skipping");
709 		return 0;
710 	}
711 
712 	if (list_empty(&file->static_call_list))
713 		return 0;
714 
715 	idx = 0;
716 	list_for_each_entry(insn, &file->static_call_list, call_node)
717 		idx++;
718 
719 	sec = elf_create_section(file->elf, ".static_call_sites", SHF_WRITE,
720 				 sizeof(struct static_call_site), idx);
721 	if (!sec)
722 		return -1;
723 
724 	idx = 0;
725 	list_for_each_entry(insn, &file->static_call_list, call_node) {
726 
727 		site = (struct static_call_site *)sec->data->d_buf + idx;
728 		memset(site, 0, sizeof(struct static_call_site));
729 
730 		/* populate reloc for 'addr' */
731 		if (elf_add_reloc_to_insn(file->elf, sec,
732 					  idx * sizeof(struct static_call_site),
733 					  R_X86_64_PC32,
734 					  insn->sec, insn->offset))
735 			return -1;
736 
737 		/* find key symbol */
738 		key_name = strdup(insn_call_dest(insn)->name);
739 		if (!key_name) {
740 			perror("strdup");
741 			return -1;
742 		}
743 		if (strncmp(key_name, STATIC_CALL_TRAMP_PREFIX_STR,
744 			    STATIC_CALL_TRAMP_PREFIX_LEN)) {
745 			WARN("static_call: trampoline name malformed: %s", key_name);
746 			free(key_name);
747 			return -1;
748 		}
749 		tmp = key_name + STATIC_CALL_TRAMP_PREFIX_LEN - STATIC_CALL_KEY_PREFIX_LEN;
750 		memcpy(tmp, STATIC_CALL_KEY_PREFIX_STR, STATIC_CALL_KEY_PREFIX_LEN);
751 
752 		key_sym = find_symbol_by_name(file->elf, tmp);
753 		if (!key_sym) {
754 			if (!opts.module) {
755 				WARN("static_call: can't find static_call_key symbol: %s", tmp);
756 				free(key_name);
757 				return -1;
758 			}
759 
760 			/*
761 			 * For modules(), the key might not be exported, which
762 			 * means the module can make static calls but isn't
763 			 * allowed to change them.
764 			 *
765 			 * In that case we temporarily set the key to be the
766 			 * trampoline address.  This is fixed up in
767 			 * static_call_add_module().
768 			 */
769 			key_sym = insn_call_dest(insn);
770 		}
771 		free(key_name);
772 
773 		/* populate reloc for 'key' */
774 		if (elf_add_reloc(file->elf, sec,
775 				  idx * sizeof(struct static_call_site) + 4,
776 				  R_X86_64_PC32, key_sym,
777 				  is_sibling_call(insn) * STATIC_CALL_SITE_TAIL))
778 			return -1;
779 
780 		idx++;
781 	}
782 
783 	return 0;
784 }
785 
786 static int create_retpoline_sites_sections(struct objtool_file *file)
787 {
788 	struct instruction *insn;
789 	struct section *sec;
790 	int idx;
791 
792 	sec = find_section_by_name(file->elf, ".retpoline_sites");
793 	if (sec) {
794 		WARN("file already has .retpoline_sites, skipping");
795 		return 0;
796 	}
797 
798 	idx = 0;
799 	list_for_each_entry(insn, &file->retpoline_call_list, call_node)
800 		idx++;
801 
802 	if (!idx)
803 		return 0;
804 
805 	sec = elf_create_section(file->elf, ".retpoline_sites", 0,
806 				 sizeof(int), idx);
807 	if (!sec) {
808 		WARN("elf_create_section: .retpoline_sites");
809 		return -1;
810 	}
811 
812 	idx = 0;
813 	list_for_each_entry(insn, &file->retpoline_call_list, call_node) {
814 
815 		int *site = (int *)sec->data->d_buf + idx;
816 		*site = 0;
817 
818 		if (elf_add_reloc_to_insn(file->elf, sec,
819 					  idx * sizeof(int),
820 					  R_X86_64_PC32,
821 					  insn->sec, insn->offset)) {
822 			WARN("elf_add_reloc_to_insn: .retpoline_sites");
823 			return -1;
824 		}
825 
826 		idx++;
827 	}
828 
829 	return 0;
830 }
831 
832 static int create_return_sites_sections(struct objtool_file *file)
833 {
834 	struct instruction *insn;
835 	struct section *sec;
836 	int idx;
837 
838 	sec = find_section_by_name(file->elf, ".return_sites");
839 	if (sec) {
840 		WARN("file already has .return_sites, skipping");
841 		return 0;
842 	}
843 
844 	idx = 0;
845 	list_for_each_entry(insn, &file->return_thunk_list, call_node)
846 		idx++;
847 
848 	if (!idx)
849 		return 0;
850 
851 	sec = elf_create_section(file->elf, ".return_sites", 0,
852 				 sizeof(int), idx);
853 	if (!sec) {
854 		WARN("elf_create_section: .return_sites");
855 		return -1;
856 	}
857 
858 	idx = 0;
859 	list_for_each_entry(insn, &file->return_thunk_list, call_node) {
860 
861 		int *site = (int *)sec->data->d_buf + idx;
862 		*site = 0;
863 
864 		if (elf_add_reloc_to_insn(file->elf, sec,
865 					  idx * sizeof(int),
866 					  R_X86_64_PC32,
867 					  insn->sec, insn->offset)) {
868 			WARN("elf_add_reloc_to_insn: .return_sites");
869 			return -1;
870 		}
871 
872 		idx++;
873 	}
874 
875 	return 0;
876 }
877 
878 static int create_ibt_endbr_seal_sections(struct objtool_file *file)
879 {
880 	struct instruction *insn;
881 	struct section *sec;
882 	int idx;
883 
884 	sec = find_section_by_name(file->elf, ".ibt_endbr_seal");
885 	if (sec) {
886 		WARN("file already has .ibt_endbr_seal, skipping");
887 		return 0;
888 	}
889 
890 	idx = 0;
891 	list_for_each_entry(insn, &file->endbr_list, call_node)
892 		idx++;
893 
894 	if (opts.stats) {
895 		printf("ibt: ENDBR at function start: %d\n", file->nr_endbr);
896 		printf("ibt: ENDBR inside functions:  %d\n", file->nr_endbr_int);
897 		printf("ibt: superfluous ENDBR:       %d\n", idx);
898 	}
899 
900 	if (!idx)
901 		return 0;
902 
903 	sec = elf_create_section(file->elf, ".ibt_endbr_seal", 0,
904 				 sizeof(int), idx);
905 	if (!sec) {
906 		WARN("elf_create_section: .ibt_endbr_seal");
907 		return -1;
908 	}
909 
910 	idx = 0;
911 	list_for_each_entry(insn, &file->endbr_list, call_node) {
912 
913 		int *site = (int *)sec->data->d_buf + idx;
914 		struct symbol *sym = insn->sym;
915 		*site = 0;
916 
917 		if (opts.module && sym && sym->type == STT_FUNC &&
918 		    insn->offset == sym->offset &&
919 		    (!strcmp(sym->name, "init_module") ||
920 		     !strcmp(sym->name, "cleanup_module")))
921 			WARN("%s(): not an indirect call target", sym->name);
922 
923 		if (elf_add_reloc_to_insn(file->elf, sec,
924 					  idx * sizeof(int),
925 					  R_X86_64_PC32,
926 					  insn->sec, insn->offset)) {
927 			WARN("elf_add_reloc_to_insn: .ibt_endbr_seal");
928 			return -1;
929 		}
930 
931 		idx++;
932 	}
933 
934 	return 0;
935 }
936 
937 static int create_cfi_sections(struct objtool_file *file)
938 {
939 	struct section *sec;
940 	struct symbol *sym;
941 	unsigned int *loc;
942 	int idx;
943 
944 	sec = find_section_by_name(file->elf, ".cfi_sites");
945 	if (sec) {
946 		INIT_LIST_HEAD(&file->call_list);
947 		WARN("file already has .cfi_sites section, skipping");
948 		return 0;
949 	}
950 
951 	idx = 0;
952 	for_each_sym(file, sym) {
953 		if (sym->type != STT_FUNC)
954 			continue;
955 
956 		if (strncmp(sym->name, "__cfi_", 6))
957 			continue;
958 
959 		idx++;
960 	}
961 
962 	sec = elf_create_section(file->elf, ".cfi_sites", 0, sizeof(unsigned int), idx);
963 	if (!sec)
964 		return -1;
965 
966 	idx = 0;
967 	for_each_sym(file, sym) {
968 		if (sym->type != STT_FUNC)
969 			continue;
970 
971 		if (strncmp(sym->name, "__cfi_", 6))
972 			continue;
973 
974 		loc = (unsigned int *)sec->data->d_buf + idx;
975 		memset(loc, 0, sizeof(unsigned int));
976 
977 		if (elf_add_reloc_to_insn(file->elf, sec,
978 					  idx * sizeof(unsigned int),
979 					  R_X86_64_PC32,
980 					  sym->sec, sym->offset))
981 			return -1;
982 
983 		idx++;
984 	}
985 
986 	return 0;
987 }
988 
989 static int create_mcount_loc_sections(struct objtool_file *file)
990 {
991 	int addrsize = elf_class_addrsize(file->elf);
992 	struct instruction *insn;
993 	struct section *sec;
994 	int idx;
995 
996 	sec = find_section_by_name(file->elf, "__mcount_loc");
997 	if (sec) {
998 		INIT_LIST_HEAD(&file->mcount_loc_list);
999 		WARN("file already has __mcount_loc section, skipping");
1000 		return 0;
1001 	}
1002 
1003 	if (list_empty(&file->mcount_loc_list))
1004 		return 0;
1005 
1006 	idx = 0;
1007 	list_for_each_entry(insn, &file->mcount_loc_list, call_node)
1008 		idx++;
1009 
1010 	sec = elf_create_section(file->elf, "__mcount_loc", 0, addrsize, idx);
1011 	if (!sec)
1012 		return -1;
1013 
1014 	sec->sh.sh_addralign = addrsize;
1015 
1016 	idx = 0;
1017 	list_for_each_entry(insn, &file->mcount_loc_list, call_node) {
1018 		void *loc;
1019 
1020 		loc = sec->data->d_buf + idx;
1021 		memset(loc, 0, addrsize);
1022 
1023 		if (elf_add_reloc_to_insn(file->elf, sec, idx,
1024 					  addrsize == sizeof(u64) ? R_ABS64 : R_ABS32,
1025 					  insn->sec, insn->offset))
1026 			return -1;
1027 
1028 		idx += addrsize;
1029 	}
1030 
1031 	return 0;
1032 }
1033 
1034 static int create_direct_call_sections(struct objtool_file *file)
1035 {
1036 	struct instruction *insn;
1037 	struct section *sec;
1038 	unsigned int *loc;
1039 	int idx;
1040 
1041 	sec = find_section_by_name(file->elf, ".call_sites");
1042 	if (sec) {
1043 		INIT_LIST_HEAD(&file->call_list);
1044 		WARN("file already has .call_sites section, skipping");
1045 		return 0;
1046 	}
1047 
1048 	if (list_empty(&file->call_list))
1049 		return 0;
1050 
1051 	idx = 0;
1052 	list_for_each_entry(insn, &file->call_list, call_node)
1053 		idx++;
1054 
1055 	sec = elf_create_section(file->elf, ".call_sites", 0, sizeof(unsigned int), idx);
1056 	if (!sec)
1057 		return -1;
1058 
1059 	idx = 0;
1060 	list_for_each_entry(insn, &file->call_list, call_node) {
1061 
1062 		loc = (unsigned int *)sec->data->d_buf + idx;
1063 		memset(loc, 0, sizeof(unsigned int));
1064 
1065 		if (elf_add_reloc_to_insn(file->elf, sec,
1066 					  idx * sizeof(unsigned int),
1067 					  R_X86_64_PC32,
1068 					  insn->sec, insn->offset))
1069 			return -1;
1070 
1071 		idx++;
1072 	}
1073 
1074 	return 0;
1075 }
1076 
1077 /*
1078  * Warnings shouldn't be reported for ignored functions.
1079  */
1080 static void add_ignores(struct objtool_file *file)
1081 {
1082 	struct instruction *insn;
1083 	struct section *sec;
1084 	struct symbol *func;
1085 	struct reloc *reloc;
1086 
1087 	sec = find_section_by_name(file->elf, ".rela.discard.func_stack_frame_non_standard");
1088 	if (!sec)
1089 		return;
1090 
1091 	list_for_each_entry(reloc, &sec->reloc_list, list) {
1092 		switch (reloc->sym->type) {
1093 		case STT_FUNC:
1094 			func = reloc->sym;
1095 			break;
1096 
1097 		case STT_SECTION:
1098 			func = find_func_by_offset(reloc->sym->sec, reloc->addend);
1099 			if (!func)
1100 				continue;
1101 			break;
1102 
1103 		default:
1104 			WARN("unexpected relocation symbol type in %s: %d", sec->name, reloc->sym->type);
1105 			continue;
1106 		}
1107 
1108 		func_for_each_insn(file, func, insn)
1109 			insn->ignore = true;
1110 	}
1111 }
1112 
1113 /*
1114  * This is a whitelist of functions that is allowed to be called with AC set.
1115  * The list is meant to be minimal and only contains compiler instrumentation
1116  * ABI and a few functions used to implement *_{to,from}_user() functions.
1117  *
1118  * These functions must not directly change AC, but may PUSHF/POPF.
1119  */
1120 static const char *uaccess_safe_builtin[] = {
1121 	/* KASAN */
1122 	"kasan_report",
1123 	"kasan_check_range",
1124 	/* KASAN out-of-line */
1125 	"__asan_loadN_noabort",
1126 	"__asan_load1_noabort",
1127 	"__asan_load2_noabort",
1128 	"__asan_load4_noabort",
1129 	"__asan_load8_noabort",
1130 	"__asan_load16_noabort",
1131 	"__asan_storeN_noabort",
1132 	"__asan_store1_noabort",
1133 	"__asan_store2_noabort",
1134 	"__asan_store4_noabort",
1135 	"__asan_store8_noabort",
1136 	"__asan_store16_noabort",
1137 	"__kasan_check_read",
1138 	"__kasan_check_write",
1139 	/* KASAN in-line */
1140 	"__asan_report_load_n_noabort",
1141 	"__asan_report_load1_noabort",
1142 	"__asan_report_load2_noabort",
1143 	"__asan_report_load4_noabort",
1144 	"__asan_report_load8_noabort",
1145 	"__asan_report_load16_noabort",
1146 	"__asan_report_store_n_noabort",
1147 	"__asan_report_store1_noabort",
1148 	"__asan_report_store2_noabort",
1149 	"__asan_report_store4_noabort",
1150 	"__asan_report_store8_noabort",
1151 	"__asan_report_store16_noabort",
1152 	/* KCSAN */
1153 	"__kcsan_check_access",
1154 	"__kcsan_mb",
1155 	"__kcsan_wmb",
1156 	"__kcsan_rmb",
1157 	"__kcsan_release",
1158 	"kcsan_found_watchpoint",
1159 	"kcsan_setup_watchpoint",
1160 	"kcsan_check_scoped_accesses",
1161 	"kcsan_disable_current",
1162 	"kcsan_enable_current_nowarn",
1163 	/* KCSAN/TSAN */
1164 	"__tsan_func_entry",
1165 	"__tsan_func_exit",
1166 	"__tsan_read_range",
1167 	"__tsan_write_range",
1168 	"__tsan_read1",
1169 	"__tsan_read2",
1170 	"__tsan_read4",
1171 	"__tsan_read8",
1172 	"__tsan_read16",
1173 	"__tsan_write1",
1174 	"__tsan_write2",
1175 	"__tsan_write4",
1176 	"__tsan_write8",
1177 	"__tsan_write16",
1178 	"__tsan_read_write1",
1179 	"__tsan_read_write2",
1180 	"__tsan_read_write4",
1181 	"__tsan_read_write8",
1182 	"__tsan_read_write16",
1183 	"__tsan_volatile_read1",
1184 	"__tsan_volatile_read2",
1185 	"__tsan_volatile_read4",
1186 	"__tsan_volatile_read8",
1187 	"__tsan_volatile_read16",
1188 	"__tsan_volatile_write1",
1189 	"__tsan_volatile_write2",
1190 	"__tsan_volatile_write4",
1191 	"__tsan_volatile_write8",
1192 	"__tsan_volatile_write16",
1193 	"__tsan_atomic8_load",
1194 	"__tsan_atomic16_load",
1195 	"__tsan_atomic32_load",
1196 	"__tsan_atomic64_load",
1197 	"__tsan_atomic8_store",
1198 	"__tsan_atomic16_store",
1199 	"__tsan_atomic32_store",
1200 	"__tsan_atomic64_store",
1201 	"__tsan_atomic8_exchange",
1202 	"__tsan_atomic16_exchange",
1203 	"__tsan_atomic32_exchange",
1204 	"__tsan_atomic64_exchange",
1205 	"__tsan_atomic8_fetch_add",
1206 	"__tsan_atomic16_fetch_add",
1207 	"__tsan_atomic32_fetch_add",
1208 	"__tsan_atomic64_fetch_add",
1209 	"__tsan_atomic8_fetch_sub",
1210 	"__tsan_atomic16_fetch_sub",
1211 	"__tsan_atomic32_fetch_sub",
1212 	"__tsan_atomic64_fetch_sub",
1213 	"__tsan_atomic8_fetch_and",
1214 	"__tsan_atomic16_fetch_and",
1215 	"__tsan_atomic32_fetch_and",
1216 	"__tsan_atomic64_fetch_and",
1217 	"__tsan_atomic8_fetch_or",
1218 	"__tsan_atomic16_fetch_or",
1219 	"__tsan_atomic32_fetch_or",
1220 	"__tsan_atomic64_fetch_or",
1221 	"__tsan_atomic8_fetch_xor",
1222 	"__tsan_atomic16_fetch_xor",
1223 	"__tsan_atomic32_fetch_xor",
1224 	"__tsan_atomic64_fetch_xor",
1225 	"__tsan_atomic8_fetch_nand",
1226 	"__tsan_atomic16_fetch_nand",
1227 	"__tsan_atomic32_fetch_nand",
1228 	"__tsan_atomic64_fetch_nand",
1229 	"__tsan_atomic8_compare_exchange_strong",
1230 	"__tsan_atomic16_compare_exchange_strong",
1231 	"__tsan_atomic32_compare_exchange_strong",
1232 	"__tsan_atomic64_compare_exchange_strong",
1233 	"__tsan_atomic8_compare_exchange_weak",
1234 	"__tsan_atomic16_compare_exchange_weak",
1235 	"__tsan_atomic32_compare_exchange_weak",
1236 	"__tsan_atomic64_compare_exchange_weak",
1237 	"__tsan_atomic8_compare_exchange_val",
1238 	"__tsan_atomic16_compare_exchange_val",
1239 	"__tsan_atomic32_compare_exchange_val",
1240 	"__tsan_atomic64_compare_exchange_val",
1241 	"__tsan_atomic_thread_fence",
1242 	"__tsan_atomic_signal_fence",
1243 	"__tsan_unaligned_read16",
1244 	"__tsan_unaligned_write16",
1245 	/* KCOV */
1246 	"write_comp_data",
1247 	"check_kcov_mode",
1248 	"__sanitizer_cov_trace_pc",
1249 	"__sanitizer_cov_trace_const_cmp1",
1250 	"__sanitizer_cov_trace_const_cmp2",
1251 	"__sanitizer_cov_trace_const_cmp4",
1252 	"__sanitizer_cov_trace_const_cmp8",
1253 	"__sanitizer_cov_trace_cmp1",
1254 	"__sanitizer_cov_trace_cmp2",
1255 	"__sanitizer_cov_trace_cmp4",
1256 	"__sanitizer_cov_trace_cmp8",
1257 	"__sanitizer_cov_trace_switch",
1258 	/* KMSAN */
1259 	"kmsan_copy_to_user",
1260 	"kmsan_report",
1261 	"kmsan_unpoison_entry_regs",
1262 	"kmsan_unpoison_memory",
1263 	"__msan_chain_origin",
1264 	"__msan_get_context_state",
1265 	"__msan_instrument_asm_store",
1266 	"__msan_metadata_ptr_for_load_1",
1267 	"__msan_metadata_ptr_for_load_2",
1268 	"__msan_metadata_ptr_for_load_4",
1269 	"__msan_metadata_ptr_for_load_8",
1270 	"__msan_metadata_ptr_for_load_n",
1271 	"__msan_metadata_ptr_for_store_1",
1272 	"__msan_metadata_ptr_for_store_2",
1273 	"__msan_metadata_ptr_for_store_4",
1274 	"__msan_metadata_ptr_for_store_8",
1275 	"__msan_metadata_ptr_for_store_n",
1276 	"__msan_poison_alloca",
1277 	"__msan_warning",
1278 	/* UBSAN */
1279 	"ubsan_type_mismatch_common",
1280 	"__ubsan_handle_type_mismatch",
1281 	"__ubsan_handle_type_mismatch_v1",
1282 	"__ubsan_handle_shift_out_of_bounds",
1283 	"__ubsan_handle_load_invalid_value",
1284 	/* STACKLEAK */
1285 	"stackleak_track_stack",
1286 	/* misc */
1287 	"csum_partial_copy_generic",
1288 	"copy_mc_fragile",
1289 	"copy_mc_fragile_handle_tail",
1290 	"copy_mc_enhanced_fast_string",
1291 	"ftrace_likely_update", /* CONFIG_TRACE_BRANCH_PROFILING */
1292 	"rep_stos_alternative",
1293 	"rep_movs_alternative",
1294 	"__copy_user_nocache",
1295 	NULL
1296 };
1297 
1298 static void add_uaccess_safe(struct objtool_file *file)
1299 {
1300 	struct symbol *func;
1301 	const char **name;
1302 
1303 	if (!opts.uaccess)
1304 		return;
1305 
1306 	for (name = uaccess_safe_builtin; *name; name++) {
1307 		func = find_symbol_by_name(file->elf, *name);
1308 		if (!func)
1309 			continue;
1310 
1311 		func->uaccess_safe = true;
1312 	}
1313 }
1314 
1315 /*
1316  * FIXME: For now, just ignore any alternatives which add retpolines.  This is
1317  * a temporary hack, as it doesn't allow ORC to unwind from inside a retpoline.
1318  * But it at least allows objtool to understand the control flow *around* the
1319  * retpoline.
1320  */
1321 static int add_ignore_alternatives(struct objtool_file *file)
1322 {
1323 	struct section *sec;
1324 	struct reloc *reloc;
1325 	struct instruction *insn;
1326 
1327 	sec = find_section_by_name(file->elf, ".rela.discard.ignore_alts");
1328 	if (!sec)
1329 		return 0;
1330 
1331 	list_for_each_entry(reloc, &sec->reloc_list, list) {
1332 		if (reloc->sym->type != STT_SECTION) {
1333 			WARN("unexpected relocation symbol type in %s", sec->name);
1334 			return -1;
1335 		}
1336 
1337 		insn = find_insn(file, reloc->sym->sec, reloc->addend);
1338 		if (!insn) {
1339 			WARN("bad .discard.ignore_alts entry");
1340 			return -1;
1341 		}
1342 
1343 		insn->ignore_alts = true;
1344 	}
1345 
1346 	return 0;
1347 }
1348 
1349 __weak bool arch_is_retpoline(struct symbol *sym)
1350 {
1351 	return false;
1352 }
1353 
1354 __weak bool arch_is_rethunk(struct symbol *sym)
1355 {
1356 	return false;
1357 }
1358 
1359 static struct reloc *insn_reloc(struct objtool_file *file, struct instruction *insn)
1360 {
1361 	struct reloc *reloc;
1362 
1363 	if (insn->no_reloc)
1364 		return NULL;
1365 
1366 	if (!file)
1367 		return NULL;
1368 
1369 	reloc = find_reloc_by_dest_range(file->elf, insn->sec,
1370 					 insn->offset, insn->len);
1371 	if (!reloc) {
1372 		insn->no_reloc = 1;
1373 		return NULL;
1374 	}
1375 
1376 	return reloc;
1377 }
1378 
1379 static void remove_insn_ops(struct instruction *insn)
1380 {
1381 	struct stack_op *op, *next;
1382 
1383 	for (op = insn->stack_ops; op; op = next) {
1384 		next = op->next;
1385 		free(op);
1386 	}
1387 	insn->stack_ops = NULL;
1388 }
1389 
1390 static void annotate_call_site(struct objtool_file *file,
1391 			       struct instruction *insn, bool sibling)
1392 {
1393 	struct reloc *reloc = insn_reloc(file, insn);
1394 	struct symbol *sym = insn_call_dest(insn);
1395 
1396 	if (!sym)
1397 		sym = reloc->sym;
1398 
1399 	/*
1400 	 * Alternative replacement code is just template code which is
1401 	 * sometimes copied to the original instruction. For now, don't
1402 	 * annotate it. (In the future we might consider annotating the
1403 	 * original instruction if/when it ever makes sense to do so.)
1404 	 */
1405 	if (!strcmp(insn->sec->name, ".altinstr_replacement"))
1406 		return;
1407 
1408 	if (sym->static_call_tramp) {
1409 		list_add_tail(&insn->call_node, &file->static_call_list);
1410 		return;
1411 	}
1412 
1413 	if (sym->retpoline_thunk) {
1414 		list_add_tail(&insn->call_node, &file->retpoline_call_list);
1415 		return;
1416 	}
1417 
1418 	/*
1419 	 * Many compilers cannot disable KCOV or sanitizer calls with a function
1420 	 * attribute so they need a little help, NOP out any such calls from
1421 	 * noinstr text.
1422 	 */
1423 	if (opts.hack_noinstr && insn->sec->noinstr && sym->profiling_func) {
1424 		if (reloc) {
1425 			reloc->type = R_NONE;
1426 			elf_write_reloc(file->elf, reloc);
1427 		}
1428 
1429 		elf_write_insn(file->elf, insn->sec,
1430 			       insn->offset, insn->len,
1431 			       sibling ? arch_ret_insn(insn->len)
1432 			               : arch_nop_insn(insn->len));
1433 
1434 		insn->type = sibling ? INSN_RETURN : INSN_NOP;
1435 
1436 		if (sibling) {
1437 			/*
1438 			 * We've replaced the tail-call JMP insn by two new
1439 			 * insn: RET; INT3, except we only have a single struct
1440 			 * insn here. Mark it retpoline_safe to avoid the SLS
1441 			 * warning, instead of adding another insn.
1442 			 */
1443 			insn->retpoline_safe = true;
1444 		}
1445 
1446 		return;
1447 	}
1448 
1449 	if (opts.mcount && sym->fentry) {
1450 		if (sibling)
1451 			WARN_INSN(insn, "tail call to __fentry__ !?!?");
1452 		if (opts.mnop) {
1453 			if (reloc) {
1454 				reloc->type = R_NONE;
1455 				elf_write_reloc(file->elf, reloc);
1456 			}
1457 
1458 			elf_write_insn(file->elf, insn->sec,
1459 				       insn->offset, insn->len,
1460 				       arch_nop_insn(insn->len));
1461 
1462 			insn->type = INSN_NOP;
1463 		}
1464 
1465 		list_add_tail(&insn->call_node, &file->mcount_loc_list);
1466 		return;
1467 	}
1468 
1469 	if (insn->type == INSN_CALL && !insn->sec->init)
1470 		list_add_tail(&insn->call_node, &file->call_list);
1471 
1472 	if (!sibling && dead_end_function(file, sym))
1473 		insn->dead_end = true;
1474 }
1475 
1476 static void add_call_dest(struct objtool_file *file, struct instruction *insn,
1477 			  struct symbol *dest, bool sibling)
1478 {
1479 	insn->_call_dest = dest;
1480 	if (!dest)
1481 		return;
1482 
1483 	/*
1484 	 * Whatever stack impact regular CALLs have, should be undone
1485 	 * by the RETURN of the called function.
1486 	 *
1487 	 * Annotated intra-function calls retain the stack_ops but
1488 	 * are converted to JUMP, see read_intra_function_calls().
1489 	 */
1490 	remove_insn_ops(insn);
1491 
1492 	annotate_call_site(file, insn, sibling);
1493 }
1494 
1495 static void add_retpoline_call(struct objtool_file *file, struct instruction *insn)
1496 {
1497 	/*
1498 	 * Retpoline calls/jumps are really dynamic calls/jumps in disguise,
1499 	 * so convert them accordingly.
1500 	 */
1501 	switch (insn->type) {
1502 	case INSN_CALL:
1503 		insn->type = INSN_CALL_DYNAMIC;
1504 		break;
1505 	case INSN_JUMP_UNCONDITIONAL:
1506 		insn->type = INSN_JUMP_DYNAMIC;
1507 		break;
1508 	case INSN_JUMP_CONDITIONAL:
1509 		insn->type = INSN_JUMP_DYNAMIC_CONDITIONAL;
1510 		break;
1511 	default:
1512 		return;
1513 	}
1514 
1515 	insn->retpoline_safe = true;
1516 
1517 	/*
1518 	 * Whatever stack impact regular CALLs have, should be undone
1519 	 * by the RETURN of the called function.
1520 	 *
1521 	 * Annotated intra-function calls retain the stack_ops but
1522 	 * are converted to JUMP, see read_intra_function_calls().
1523 	 */
1524 	remove_insn_ops(insn);
1525 
1526 	annotate_call_site(file, insn, false);
1527 }
1528 
1529 static void add_return_call(struct objtool_file *file, struct instruction *insn, bool add)
1530 {
1531 	/*
1532 	 * Return thunk tail calls are really just returns in disguise,
1533 	 * so convert them accordingly.
1534 	 */
1535 	insn->type = INSN_RETURN;
1536 	insn->retpoline_safe = true;
1537 
1538 	if (add)
1539 		list_add_tail(&insn->call_node, &file->return_thunk_list);
1540 }
1541 
1542 static bool is_first_func_insn(struct objtool_file *file,
1543 			       struct instruction *insn, struct symbol *sym)
1544 {
1545 	if (insn->offset == sym->offset)
1546 		return true;
1547 
1548 	/* Allow direct CALL/JMP past ENDBR */
1549 	if (opts.ibt) {
1550 		struct instruction *prev = prev_insn_same_sym(file, insn);
1551 
1552 		if (prev && prev->type == INSN_ENDBR &&
1553 		    insn->offset == sym->offset + prev->len)
1554 			return true;
1555 	}
1556 
1557 	return false;
1558 }
1559 
1560 /*
1561  * A sibling call is a tail-call to another symbol -- to differentiate from a
1562  * recursive tail-call which is to the same symbol.
1563  */
1564 static bool jump_is_sibling_call(struct objtool_file *file,
1565 				 struct instruction *from, struct instruction *to)
1566 {
1567 	struct symbol *fs = from->sym;
1568 	struct symbol *ts = to->sym;
1569 
1570 	/* Not a sibling call if from/to a symbol hole */
1571 	if (!fs || !ts)
1572 		return false;
1573 
1574 	/* Not a sibling call if not targeting the start of a symbol. */
1575 	if (!is_first_func_insn(file, to, ts))
1576 		return false;
1577 
1578 	/* Disallow sibling calls into STT_NOTYPE */
1579 	if (ts->type == STT_NOTYPE)
1580 		return false;
1581 
1582 	/* Must not be self to be a sibling */
1583 	return fs->pfunc != ts->pfunc;
1584 }
1585 
1586 /*
1587  * Find the destination instructions for all jumps.
1588  */
1589 static int add_jump_destinations(struct objtool_file *file)
1590 {
1591 	struct instruction *insn, *jump_dest;
1592 	struct reloc *reloc;
1593 	struct section *dest_sec;
1594 	unsigned long dest_off;
1595 
1596 	for_each_insn(file, insn) {
1597 		if (insn->jump_dest) {
1598 			/*
1599 			 * handle_group_alt() may have previously set
1600 			 * 'jump_dest' for some alternatives.
1601 			 */
1602 			continue;
1603 		}
1604 		if (!is_static_jump(insn))
1605 			continue;
1606 
1607 		reloc = insn_reloc(file, insn);
1608 		if (!reloc) {
1609 			dest_sec = insn->sec;
1610 			dest_off = arch_jump_destination(insn);
1611 		} else if (reloc->sym->type == STT_SECTION) {
1612 			dest_sec = reloc->sym->sec;
1613 			dest_off = arch_dest_reloc_offset(reloc->addend);
1614 		} else if (reloc->sym->retpoline_thunk) {
1615 			add_retpoline_call(file, insn);
1616 			continue;
1617 		} else if (reloc->sym->return_thunk) {
1618 			add_return_call(file, insn, true);
1619 			continue;
1620 		} else if (insn_func(insn)) {
1621 			/*
1622 			 * External sibling call or internal sibling call with
1623 			 * STT_FUNC reloc.
1624 			 */
1625 			add_call_dest(file, insn, reloc->sym, true);
1626 			continue;
1627 		} else if (reloc->sym->sec->idx) {
1628 			dest_sec = reloc->sym->sec;
1629 			dest_off = reloc->sym->sym.st_value +
1630 				   arch_dest_reloc_offset(reloc->addend);
1631 		} else {
1632 			/* non-func asm code jumping to another file */
1633 			continue;
1634 		}
1635 
1636 		jump_dest = find_insn(file, dest_sec, dest_off);
1637 		if (!jump_dest) {
1638 			struct symbol *sym = find_symbol_by_offset(dest_sec, dest_off);
1639 
1640 			/*
1641 			 * This is a special case for zen_untrain_ret().
1642 			 * It jumps to __x86_return_thunk(), but objtool
1643 			 * can't find the thunk's starting RET
1644 			 * instruction, because the RET is also in the
1645 			 * middle of another instruction.  Objtool only
1646 			 * knows about the outer instruction.
1647 			 */
1648 			if (sym && sym->return_thunk) {
1649 				add_return_call(file, insn, false);
1650 				continue;
1651 			}
1652 
1653 			WARN_INSN(insn, "can't find jump dest instruction at %s+0x%lx",
1654 				  dest_sec->name, dest_off);
1655 			return -1;
1656 		}
1657 
1658 		/*
1659 		 * Cross-function jump.
1660 		 */
1661 		if (insn_func(insn) && insn_func(jump_dest) &&
1662 		    insn_func(insn) != insn_func(jump_dest)) {
1663 
1664 			/*
1665 			 * For GCC 8+, create parent/child links for any cold
1666 			 * subfunctions.  This is _mostly_ redundant with a
1667 			 * similar initialization in read_symbols().
1668 			 *
1669 			 * If a function has aliases, we want the *first* such
1670 			 * function in the symbol table to be the subfunction's
1671 			 * parent.  In that case we overwrite the
1672 			 * initialization done in read_symbols().
1673 			 *
1674 			 * However this code can't completely replace the
1675 			 * read_symbols() code because this doesn't detect the
1676 			 * case where the parent function's only reference to a
1677 			 * subfunction is through a jump table.
1678 			 */
1679 			if (!strstr(insn_func(insn)->name, ".cold") &&
1680 			    strstr(insn_func(jump_dest)->name, ".cold")) {
1681 				insn_func(insn)->cfunc = insn_func(jump_dest);
1682 				insn_func(jump_dest)->pfunc = insn_func(insn);
1683 			}
1684 		}
1685 
1686 		if (jump_is_sibling_call(file, insn, jump_dest)) {
1687 			/*
1688 			 * Internal sibling call without reloc or with
1689 			 * STT_SECTION reloc.
1690 			 */
1691 			add_call_dest(file, insn, insn_func(jump_dest), true);
1692 			continue;
1693 		}
1694 
1695 		insn->jump_dest = jump_dest;
1696 	}
1697 
1698 	return 0;
1699 }
1700 
1701 static struct symbol *find_call_destination(struct section *sec, unsigned long offset)
1702 {
1703 	struct symbol *call_dest;
1704 
1705 	call_dest = find_func_by_offset(sec, offset);
1706 	if (!call_dest)
1707 		call_dest = find_symbol_by_offset(sec, offset);
1708 
1709 	return call_dest;
1710 }
1711 
1712 /*
1713  * Find the destination instructions for all calls.
1714  */
1715 static int add_call_destinations(struct objtool_file *file)
1716 {
1717 	struct instruction *insn;
1718 	unsigned long dest_off;
1719 	struct symbol *dest;
1720 	struct reloc *reloc;
1721 
1722 	for_each_insn(file, insn) {
1723 		if (insn->type != INSN_CALL)
1724 			continue;
1725 
1726 		reloc = insn_reloc(file, insn);
1727 		if (!reloc) {
1728 			dest_off = arch_jump_destination(insn);
1729 			dest = find_call_destination(insn->sec, dest_off);
1730 
1731 			add_call_dest(file, insn, dest, false);
1732 
1733 			if (insn->ignore)
1734 				continue;
1735 
1736 			if (!insn_call_dest(insn)) {
1737 				WARN_INSN(insn, "unannotated intra-function call");
1738 				return -1;
1739 			}
1740 
1741 			if (insn_func(insn) && insn_call_dest(insn)->type != STT_FUNC) {
1742 				WARN_INSN(insn, "unsupported call to non-function");
1743 				return -1;
1744 			}
1745 
1746 		} else if (reloc->sym->type == STT_SECTION) {
1747 			dest_off = arch_dest_reloc_offset(reloc->addend);
1748 			dest = find_call_destination(reloc->sym->sec, dest_off);
1749 			if (!dest) {
1750 				WARN_INSN(insn, "can't find call dest symbol at %s+0x%lx",
1751 					  reloc->sym->sec->name, dest_off);
1752 				return -1;
1753 			}
1754 
1755 			add_call_dest(file, insn, dest, false);
1756 
1757 		} else if (reloc->sym->retpoline_thunk) {
1758 			add_retpoline_call(file, insn);
1759 
1760 		} else
1761 			add_call_dest(file, insn, reloc->sym, false);
1762 	}
1763 
1764 	return 0;
1765 }
1766 
1767 /*
1768  * The .alternatives section requires some extra special care over and above
1769  * other special sections because alternatives are patched in place.
1770  */
1771 static int handle_group_alt(struct objtool_file *file,
1772 			    struct special_alt *special_alt,
1773 			    struct instruction *orig_insn,
1774 			    struct instruction **new_insn)
1775 {
1776 	struct instruction *last_new_insn = NULL, *insn, *nop = NULL;
1777 	struct alt_group *orig_alt_group, *new_alt_group;
1778 	unsigned long dest_off;
1779 
1780 	orig_alt_group = orig_insn->alt_group;
1781 	if (!orig_alt_group) {
1782 		struct instruction *last_orig_insn = NULL;
1783 
1784 		orig_alt_group = malloc(sizeof(*orig_alt_group));
1785 		if (!orig_alt_group) {
1786 			WARN("malloc failed");
1787 			return -1;
1788 		}
1789 		orig_alt_group->cfi = calloc(special_alt->orig_len,
1790 					     sizeof(struct cfi_state *));
1791 		if (!orig_alt_group->cfi) {
1792 			WARN("calloc failed");
1793 			return -1;
1794 		}
1795 
1796 		insn = orig_insn;
1797 		sec_for_each_insn_from(file, insn) {
1798 			if (insn->offset >= special_alt->orig_off + special_alt->orig_len)
1799 				break;
1800 
1801 			insn->alt_group = orig_alt_group;
1802 			last_orig_insn = insn;
1803 		}
1804 		orig_alt_group->orig_group = NULL;
1805 		orig_alt_group->first_insn = orig_insn;
1806 		orig_alt_group->last_insn = last_orig_insn;
1807 		orig_alt_group->nop = NULL;
1808 	} else {
1809 		if (orig_alt_group->last_insn->offset + orig_alt_group->last_insn->len -
1810 		    orig_alt_group->first_insn->offset != special_alt->orig_len) {
1811 			WARN_INSN(orig_insn, "weirdly overlapping alternative! %ld != %d",
1812 				  orig_alt_group->last_insn->offset +
1813 				  orig_alt_group->last_insn->len -
1814 				  orig_alt_group->first_insn->offset,
1815 				  special_alt->orig_len);
1816 			return -1;
1817 		}
1818 	}
1819 
1820 	new_alt_group = malloc(sizeof(*new_alt_group));
1821 	if (!new_alt_group) {
1822 		WARN("malloc failed");
1823 		return -1;
1824 	}
1825 
1826 	if (special_alt->new_len < special_alt->orig_len) {
1827 		/*
1828 		 * Insert a fake nop at the end to make the replacement
1829 		 * alt_group the same size as the original.  This is needed to
1830 		 * allow propagate_alt_cfi() to do its magic.  When the last
1831 		 * instruction affects the stack, the instruction after it (the
1832 		 * nop) will propagate the new state to the shared CFI array.
1833 		 */
1834 		nop = malloc(sizeof(*nop));
1835 		if (!nop) {
1836 			WARN("malloc failed");
1837 			return -1;
1838 		}
1839 		memset(nop, 0, sizeof(*nop));
1840 
1841 		nop->sec = special_alt->new_sec;
1842 		nop->offset = special_alt->new_off + special_alt->new_len;
1843 		nop->len = special_alt->orig_len - special_alt->new_len;
1844 		nop->type = INSN_NOP;
1845 		nop->sym = orig_insn->sym;
1846 		nop->alt_group = new_alt_group;
1847 		nop->ignore = orig_insn->ignore_alts;
1848 	}
1849 
1850 	if (!special_alt->new_len) {
1851 		*new_insn = nop;
1852 		goto end;
1853 	}
1854 
1855 	insn = *new_insn;
1856 	sec_for_each_insn_from(file, insn) {
1857 		struct reloc *alt_reloc;
1858 
1859 		if (insn->offset >= special_alt->new_off + special_alt->new_len)
1860 			break;
1861 
1862 		last_new_insn = insn;
1863 
1864 		insn->ignore = orig_insn->ignore_alts;
1865 		insn->sym = orig_insn->sym;
1866 		insn->alt_group = new_alt_group;
1867 
1868 		/*
1869 		 * Since alternative replacement code is copy/pasted by the
1870 		 * kernel after applying relocations, generally such code can't
1871 		 * have relative-address relocation references to outside the
1872 		 * .altinstr_replacement section, unless the arch's
1873 		 * alternatives code can adjust the relative offsets
1874 		 * accordingly.
1875 		 */
1876 		alt_reloc = insn_reloc(file, insn);
1877 		if (alt_reloc && arch_pc_relative_reloc(alt_reloc) &&
1878 		    !arch_support_alt_relocation(special_alt, insn, alt_reloc)) {
1879 
1880 			WARN_INSN(insn, "unsupported relocation in alternatives section");
1881 			return -1;
1882 		}
1883 
1884 		if (!is_static_jump(insn))
1885 			continue;
1886 
1887 		if (!insn->immediate)
1888 			continue;
1889 
1890 		dest_off = arch_jump_destination(insn);
1891 		if (dest_off == special_alt->new_off + special_alt->new_len) {
1892 			insn->jump_dest = next_insn_same_sec(file, orig_alt_group->last_insn);
1893 			if (!insn->jump_dest) {
1894 				WARN_INSN(insn, "can't find alternative jump destination");
1895 				return -1;
1896 			}
1897 		}
1898 	}
1899 
1900 	if (!last_new_insn) {
1901 		WARN_FUNC("can't find last new alternative instruction",
1902 			  special_alt->new_sec, special_alt->new_off);
1903 		return -1;
1904 	}
1905 
1906 end:
1907 	new_alt_group->orig_group = orig_alt_group;
1908 	new_alt_group->first_insn = *new_insn;
1909 	new_alt_group->last_insn = last_new_insn;
1910 	new_alt_group->nop = nop;
1911 	new_alt_group->cfi = orig_alt_group->cfi;
1912 	return 0;
1913 }
1914 
1915 /*
1916  * A jump table entry can either convert a nop to a jump or a jump to a nop.
1917  * If the original instruction is a jump, make the alt entry an effective nop
1918  * by just skipping the original instruction.
1919  */
1920 static int handle_jump_alt(struct objtool_file *file,
1921 			   struct special_alt *special_alt,
1922 			   struct instruction *orig_insn,
1923 			   struct instruction **new_insn)
1924 {
1925 	if (orig_insn->type != INSN_JUMP_UNCONDITIONAL &&
1926 	    orig_insn->type != INSN_NOP) {
1927 
1928 		WARN_INSN(orig_insn, "unsupported instruction at jump label");
1929 		return -1;
1930 	}
1931 
1932 	if (opts.hack_jump_label && special_alt->key_addend & 2) {
1933 		struct reloc *reloc = insn_reloc(file, orig_insn);
1934 
1935 		if (reloc) {
1936 			reloc->type = R_NONE;
1937 			elf_write_reloc(file->elf, reloc);
1938 		}
1939 		elf_write_insn(file->elf, orig_insn->sec,
1940 			       orig_insn->offset, orig_insn->len,
1941 			       arch_nop_insn(orig_insn->len));
1942 		orig_insn->type = INSN_NOP;
1943 	}
1944 
1945 	if (orig_insn->type == INSN_NOP) {
1946 		if (orig_insn->len == 2)
1947 			file->jl_nop_short++;
1948 		else
1949 			file->jl_nop_long++;
1950 
1951 		return 0;
1952 	}
1953 
1954 	if (orig_insn->len == 2)
1955 		file->jl_short++;
1956 	else
1957 		file->jl_long++;
1958 
1959 	*new_insn = next_insn_same_sec(file, orig_insn);
1960 	return 0;
1961 }
1962 
1963 /*
1964  * Read all the special sections which have alternate instructions which can be
1965  * patched in or redirected to at runtime.  Each instruction having alternate
1966  * instruction(s) has them added to its insn->alts list, which will be
1967  * traversed in validate_branch().
1968  */
1969 static int add_special_section_alts(struct objtool_file *file)
1970 {
1971 	struct list_head special_alts;
1972 	struct instruction *orig_insn, *new_insn;
1973 	struct special_alt *special_alt, *tmp;
1974 	struct alternative *alt;
1975 	int ret;
1976 
1977 	ret = special_get_alts(file->elf, &special_alts);
1978 	if (ret)
1979 		return ret;
1980 
1981 	list_for_each_entry_safe(special_alt, tmp, &special_alts, list) {
1982 
1983 		orig_insn = find_insn(file, special_alt->orig_sec,
1984 				      special_alt->orig_off);
1985 		if (!orig_insn) {
1986 			WARN_FUNC("special: can't find orig instruction",
1987 				  special_alt->orig_sec, special_alt->orig_off);
1988 			ret = -1;
1989 			goto out;
1990 		}
1991 
1992 		new_insn = NULL;
1993 		if (!special_alt->group || special_alt->new_len) {
1994 			new_insn = find_insn(file, special_alt->new_sec,
1995 					     special_alt->new_off);
1996 			if (!new_insn) {
1997 				WARN_FUNC("special: can't find new instruction",
1998 					  special_alt->new_sec,
1999 					  special_alt->new_off);
2000 				ret = -1;
2001 				goto out;
2002 			}
2003 		}
2004 
2005 		if (special_alt->group) {
2006 			if (!special_alt->orig_len) {
2007 				WARN_INSN(orig_insn, "empty alternative entry");
2008 				continue;
2009 			}
2010 
2011 			ret = handle_group_alt(file, special_alt, orig_insn,
2012 					       &new_insn);
2013 			if (ret)
2014 				goto out;
2015 		} else if (special_alt->jump_or_nop) {
2016 			ret = handle_jump_alt(file, special_alt, orig_insn,
2017 					      &new_insn);
2018 			if (ret)
2019 				goto out;
2020 		}
2021 
2022 		alt = malloc(sizeof(*alt));
2023 		if (!alt) {
2024 			WARN("malloc failed");
2025 			ret = -1;
2026 			goto out;
2027 		}
2028 
2029 		alt->insn = new_insn;
2030 		alt->skip_orig = special_alt->skip_orig;
2031 		orig_insn->ignore_alts |= special_alt->skip_alt;
2032 		alt->next = orig_insn->alts;
2033 		orig_insn->alts = alt;
2034 
2035 		list_del(&special_alt->list);
2036 		free(special_alt);
2037 	}
2038 
2039 	if (opts.stats) {
2040 		printf("jl\\\tNOP\tJMP\n");
2041 		printf("short:\t%ld\t%ld\n", file->jl_nop_short, file->jl_short);
2042 		printf("long:\t%ld\t%ld\n", file->jl_nop_long, file->jl_long);
2043 	}
2044 
2045 out:
2046 	return ret;
2047 }
2048 
2049 static int add_jump_table(struct objtool_file *file, struct instruction *insn,
2050 			    struct reloc *table)
2051 {
2052 	struct reloc *reloc = table;
2053 	struct instruction *dest_insn;
2054 	struct alternative *alt;
2055 	struct symbol *pfunc = insn_func(insn)->pfunc;
2056 	unsigned int prev_offset = 0;
2057 
2058 	/*
2059 	 * Each @reloc is a switch table relocation which points to the target
2060 	 * instruction.
2061 	 */
2062 	list_for_each_entry_from(reloc, &table->sec->reloc_list, list) {
2063 
2064 		/* Check for the end of the table: */
2065 		if (reloc != table && reloc->jump_table_start)
2066 			break;
2067 
2068 		/* Make sure the table entries are consecutive: */
2069 		if (prev_offset && reloc->offset != prev_offset + 8)
2070 			break;
2071 
2072 		/* Detect function pointers from contiguous objects: */
2073 		if (reloc->sym->sec == pfunc->sec &&
2074 		    reloc->addend == pfunc->offset)
2075 			break;
2076 
2077 		dest_insn = find_insn(file, reloc->sym->sec, reloc->addend);
2078 		if (!dest_insn)
2079 			break;
2080 
2081 		/* Make sure the destination is in the same function: */
2082 		if (!insn_func(dest_insn) || insn_func(dest_insn)->pfunc != pfunc)
2083 			break;
2084 
2085 		alt = malloc(sizeof(*alt));
2086 		if (!alt) {
2087 			WARN("malloc failed");
2088 			return -1;
2089 		}
2090 
2091 		alt->insn = dest_insn;
2092 		alt->next = insn->alts;
2093 		insn->alts = alt;
2094 		prev_offset = reloc->offset;
2095 	}
2096 
2097 	if (!prev_offset) {
2098 		WARN_INSN(insn, "can't find switch jump table");
2099 		return -1;
2100 	}
2101 
2102 	return 0;
2103 }
2104 
2105 /*
2106  * find_jump_table() - Given a dynamic jump, find the switch jump table
2107  * associated with it.
2108  */
2109 static struct reloc *find_jump_table(struct objtool_file *file,
2110 				      struct symbol *func,
2111 				      struct instruction *insn)
2112 {
2113 	struct reloc *table_reloc;
2114 	struct instruction *dest_insn, *orig_insn = insn;
2115 
2116 	/*
2117 	 * Backward search using the @first_jump_src links, these help avoid
2118 	 * much of the 'in between' code. Which avoids us getting confused by
2119 	 * it.
2120 	 */
2121 	for (;
2122 	     insn && insn_func(insn) && insn_func(insn)->pfunc == func;
2123 	     insn = insn->first_jump_src ?: prev_insn_same_sym(file, insn)) {
2124 
2125 		if (insn != orig_insn && insn->type == INSN_JUMP_DYNAMIC)
2126 			break;
2127 
2128 		/* allow small jumps within the range */
2129 		if (insn->type == INSN_JUMP_UNCONDITIONAL &&
2130 		    insn->jump_dest &&
2131 		    (insn->jump_dest->offset <= insn->offset ||
2132 		     insn->jump_dest->offset > orig_insn->offset))
2133 		    break;
2134 
2135 		table_reloc = arch_find_switch_table(file, insn);
2136 		if (!table_reloc)
2137 			continue;
2138 		dest_insn = find_insn(file, table_reloc->sym->sec, table_reloc->addend);
2139 		if (!dest_insn || !insn_func(dest_insn) || insn_func(dest_insn)->pfunc != func)
2140 			continue;
2141 
2142 		return table_reloc;
2143 	}
2144 
2145 	return NULL;
2146 }
2147 
2148 /*
2149  * First pass: Mark the head of each jump table so that in the next pass,
2150  * we know when a given jump table ends and the next one starts.
2151  */
2152 static void mark_func_jump_tables(struct objtool_file *file,
2153 				    struct symbol *func)
2154 {
2155 	struct instruction *insn, *last = NULL;
2156 	struct reloc *reloc;
2157 
2158 	func_for_each_insn(file, func, insn) {
2159 		if (!last)
2160 			last = insn;
2161 
2162 		/*
2163 		 * Store back-pointers for unconditional forward jumps such
2164 		 * that find_jump_table() can back-track using those and
2165 		 * avoid some potentially confusing code.
2166 		 */
2167 		if (insn->type == INSN_JUMP_UNCONDITIONAL && insn->jump_dest &&
2168 		    insn->offset > last->offset &&
2169 		    insn->jump_dest->offset > insn->offset &&
2170 		    !insn->jump_dest->first_jump_src) {
2171 
2172 			insn->jump_dest->first_jump_src = insn;
2173 			last = insn->jump_dest;
2174 		}
2175 
2176 		if (insn->type != INSN_JUMP_DYNAMIC)
2177 			continue;
2178 
2179 		reloc = find_jump_table(file, func, insn);
2180 		if (reloc) {
2181 			reloc->jump_table_start = true;
2182 			insn->_jump_table = reloc;
2183 		}
2184 	}
2185 }
2186 
2187 static int add_func_jump_tables(struct objtool_file *file,
2188 				  struct symbol *func)
2189 {
2190 	struct instruction *insn;
2191 	int ret;
2192 
2193 	func_for_each_insn(file, func, insn) {
2194 		if (!insn_jump_table(insn))
2195 			continue;
2196 
2197 		ret = add_jump_table(file, insn, insn_jump_table(insn));
2198 		if (ret)
2199 			return ret;
2200 	}
2201 
2202 	return 0;
2203 }
2204 
2205 /*
2206  * For some switch statements, gcc generates a jump table in the .rodata
2207  * section which contains a list of addresses within the function to jump to.
2208  * This finds these jump tables and adds them to the insn->alts lists.
2209  */
2210 static int add_jump_table_alts(struct objtool_file *file)
2211 {
2212 	struct symbol *func;
2213 	int ret;
2214 
2215 	if (!file->rodata)
2216 		return 0;
2217 
2218 	for_each_sym(file, func) {
2219 		if (func->type != STT_FUNC)
2220 			continue;
2221 
2222 		mark_func_jump_tables(file, func);
2223 		ret = add_func_jump_tables(file, func);
2224 		if (ret)
2225 			return ret;
2226 	}
2227 
2228 	return 0;
2229 }
2230 
2231 static void set_func_state(struct cfi_state *state)
2232 {
2233 	state->cfa = initial_func_cfi.cfa;
2234 	memcpy(&state->regs, &initial_func_cfi.regs,
2235 	       CFI_NUM_REGS * sizeof(struct cfi_reg));
2236 	state->stack_size = initial_func_cfi.cfa.offset;
2237 	state->type = UNWIND_HINT_TYPE_CALL;
2238 }
2239 
2240 static int read_unwind_hints(struct objtool_file *file)
2241 {
2242 	struct cfi_state cfi = init_cfi;
2243 	struct section *sec, *relocsec;
2244 	struct unwind_hint *hint;
2245 	struct instruction *insn;
2246 	struct reloc *reloc;
2247 	int i;
2248 
2249 	sec = find_section_by_name(file->elf, ".discard.unwind_hints");
2250 	if (!sec)
2251 		return 0;
2252 
2253 	relocsec = sec->reloc;
2254 	if (!relocsec) {
2255 		WARN("missing .rela.discard.unwind_hints section");
2256 		return -1;
2257 	}
2258 
2259 	if (sec->sh.sh_size % sizeof(struct unwind_hint)) {
2260 		WARN("struct unwind_hint size mismatch");
2261 		return -1;
2262 	}
2263 
2264 	file->hints = true;
2265 
2266 	for (i = 0; i < sec->sh.sh_size / sizeof(struct unwind_hint); i++) {
2267 		hint = (struct unwind_hint *)sec->data->d_buf + i;
2268 
2269 		reloc = find_reloc_by_dest(file->elf, sec, i * sizeof(*hint));
2270 		if (!reloc) {
2271 			WARN("can't find reloc for unwind_hints[%d]", i);
2272 			return -1;
2273 		}
2274 
2275 		insn = find_insn(file, reloc->sym->sec, reloc->addend);
2276 		if (!insn) {
2277 			WARN("can't find insn for unwind_hints[%d]", i);
2278 			return -1;
2279 		}
2280 
2281 		insn->hint = true;
2282 
2283 		if (hint->type == UNWIND_HINT_TYPE_SAVE) {
2284 			insn->hint = false;
2285 			insn->save = true;
2286 			continue;
2287 		}
2288 
2289 		if (hint->type == UNWIND_HINT_TYPE_RESTORE) {
2290 			insn->restore = true;
2291 			continue;
2292 		}
2293 
2294 		if (hint->type == UNWIND_HINT_TYPE_REGS_PARTIAL) {
2295 			struct symbol *sym = find_symbol_by_offset(insn->sec, insn->offset);
2296 
2297 			if (sym && sym->bind == STB_GLOBAL) {
2298 				if (opts.ibt && insn->type != INSN_ENDBR && !insn->noendbr) {
2299 					WARN_INSN(insn, "UNWIND_HINT_IRET_REGS without ENDBR");
2300 				}
2301 			}
2302 		}
2303 
2304 		if (hint->type == UNWIND_HINT_TYPE_FUNC) {
2305 			insn->cfi = &func_cfi;
2306 			continue;
2307 		}
2308 
2309 		if (insn->cfi)
2310 			cfi = *(insn->cfi);
2311 
2312 		if (arch_decode_hint_reg(hint->sp_reg, &cfi.cfa.base)) {
2313 			WARN_INSN(insn, "unsupported unwind_hint sp base reg %d", hint->sp_reg);
2314 			return -1;
2315 		}
2316 
2317 		cfi.cfa.offset = bswap_if_needed(file->elf, hint->sp_offset);
2318 		cfi.type = hint->type;
2319 		cfi.signal = hint->signal;
2320 
2321 		insn->cfi = cfi_hash_find_or_add(&cfi);
2322 	}
2323 
2324 	return 0;
2325 }
2326 
2327 static int read_noendbr_hints(struct objtool_file *file)
2328 {
2329 	struct section *sec;
2330 	struct instruction *insn;
2331 	struct reloc *reloc;
2332 
2333 	sec = find_section_by_name(file->elf, ".rela.discard.noendbr");
2334 	if (!sec)
2335 		return 0;
2336 
2337 	list_for_each_entry(reloc, &sec->reloc_list, list) {
2338 		insn = find_insn(file, reloc->sym->sec, reloc->sym->offset + reloc->addend);
2339 		if (!insn) {
2340 			WARN("bad .discard.noendbr entry");
2341 			return -1;
2342 		}
2343 
2344 		insn->noendbr = 1;
2345 	}
2346 
2347 	return 0;
2348 }
2349 
2350 static int read_retpoline_hints(struct objtool_file *file)
2351 {
2352 	struct section *sec;
2353 	struct instruction *insn;
2354 	struct reloc *reloc;
2355 
2356 	sec = find_section_by_name(file->elf, ".rela.discard.retpoline_safe");
2357 	if (!sec)
2358 		return 0;
2359 
2360 	list_for_each_entry(reloc, &sec->reloc_list, list) {
2361 		if (reloc->sym->type != STT_SECTION) {
2362 			WARN("unexpected relocation symbol type in %s", sec->name);
2363 			return -1;
2364 		}
2365 
2366 		insn = find_insn(file, reloc->sym->sec, reloc->addend);
2367 		if (!insn) {
2368 			WARN("bad .discard.retpoline_safe entry");
2369 			return -1;
2370 		}
2371 
2372 		if (insn->type != INSN_JUMP_DYNAMIC &&
2373 		    insn->type != INSN_CALL_DYNAMIC &&
2374 		    insn->type != INSN_RETURN &&
2375 		    insn->type != INSN_NOP) {
2376 			WARN_INSN(insn, "retpoline_safe hint not an indirect jump/call/ret/nop");
2377 			return -1;
2378 		}
2379 
2380 		insn->retpoline_safe = true;
2381 	}
2382 
2383 	return 0;
2384 }
2385 
2386 static int read_instr_hints(struct objtool_file *file)
2387 {
2388 	struct section *sec;
2389 	struct instruction *insn;
2390 	struct reloc *reloc;
2391 
2392 	sec = find_section_by_name(file->elf, ".rela.discard.instr_end");
2393 	if (!sec)
2394 		return 0;
2395 
2396 	list_for_each_entry(reloc, &sec->reloc_list, list) {
2397 		if (reloc->sym->type != STT_SECTION) {
2398 			WARN("unexpected relocation symbol type in %s", sec->name);
2399 			return -1;
2400 		}
2401 
2402 		insn = find_insn(file, reloc->sym->sec, reloc->addend);
2403 		if (!insn) {
2404 			WARN("bad .discard.instr_end entry");
2405 			return -1;
2406 		}
2407 
2408 		insn->instr--;
2409 	}
2410 
2411 	sec = find_section_by_name(file->elf, ".rela.discard.instr_begin");
2412 	if (!sec)
2413 		return 0;
2414 
2415 	list_for_each_entry(reloc, &sec->reloc_list, list) {
2416 		if (reloc->sym->type != STT_SECTION) {
2417 			WARN("unexpected relocation symbol type in %s", sec->name);
2418 			return -1;
2419 		}
2420 
2421 		insn = find_insn(file, reloc->sym->sec, reloc->addend);
2422 		if (!insn) {
2423 			WARN("bad .discard.instr_begin entry");
2424 			return -1;
2425 		}
2426 
2427 		insn->instr++;
2428 	}
2429 
2430 	return 0;
2431 }
2432 
2433 static int read_validate_unret_hints(struct objtool_file *file)
2434 {
2435 	struct section *sec;
2436 	struct instruction *insn;
2437 	struct reloc *reloc;
2438 
2439 	sec = find_section_by_name(file->elf, ".rela.discard.validate_unret");
2440 	if (!sec)
2441 		return 0;
2442 
2443 	list_for_each_entry(reloc, &sec->reloc_list, list) {
2444 		if (reloc->sym->type != STT_SECTION) {
2445 			WARN("unexpected relocation symbol type in %s", sec->name);
2446 			return -1;
2447 		}
2448 
2449 		insn = find_insn(file, reloc->sym->sec, reloc->addend);
2450 		if (!insn) {
2451 			WARN("bad .discard.instr_end entry");
2452 			return -1;
2453 		}
2454 		insn->unret = 1;
2455 	}
2456 
2457 	return 0;
2458 }
2459 
2460 
2461 static int read_intra_function_calls(struct objtool_file *file)
2462 {
2463 	struct instruction *insn;
2464 	struct section *sec;
2465 	struct reloc *reloc;
2466 
2467 	sec = find_section_by_name(file->elf, ".rela.discard.intra_function_calls");
2468 	if (!sec)
2469 		return 0;
2470 
2471 	list_for_each_entry(reloc, &sec->reloc_list, list) {
2472 		unsigned long dest_off;
2473 
2474 		if (reloc->sym->type != STT_SECTION) {
2475 			WARN("unexpected relocation symbol type in %s",
2476 			     sec->name);
2477 			return -1;
2478 		}
2479 
2480 		insn = find_insn(file, reloc->sym->sec, reloc->addend);
2481 		if (!insn) {
2482 			WARN("bad .discard.intra_function_call entry");
2483 			return -1;
2484 		}
2485 
2486 		if (insn->type != INSN_CALL) {
2487 			WARN_INSN(insn, "intra_function_call not a direct call");
2488 			return -1;
2489 		}
2490 
2491 		/*
2492 		 * Treat intra-function CALLs as JMPs, but with a stack_op.
2493 		 * See add_call_destinations(), which strips stack_ops from
2494 		 * normal CALLs.
2495 		 */
2496 		insn->type = INSN_JUMP_UNCONDITIONAL;
2497 
2498 		dest_off = arch_jump_destination(insn);
2499 		insn->jump_dest = find_insn(file, insn->sec, dest_off);
2500 		if (!insn->jump_dest) {
2501 			WARN_INSN(insn, "can't find call dest at %s+0x%lx",
2502 				  insn->sec->name, dest_off);
2503 			return -1;
2504 		}
2505 	}
2506 
2507 	return 0;
2508 }
2509 
2510 /*
2511  * Return true if name matches an instrumentation function, where calls to that
2512  * function from noinstr code can safely be removed, but compilers won't do so.
2513  */
2514 static bool is_profiling_func(const char *name)
2515 {
2516 	/*
2517 	 * Many compilers cannot disable KCOV with a function attribute.
2518 	 */
2519 	if (!strncmp(name, "__sanitizer_cov_", 16))
2520 		return true;
2521 
2522 	/*
2523 	 * Some compilers currently do not remove __tsan_func_entry/exit nor
2524 	 * __tsan_atomic_signal_fence (used for barrier instrumentation) with
2525 	 * the __no_sanitize_thread attribute, remove them. Once the kernel's
2526 	 * minimum Clang version is 14.0, this can be removed.
2527 	 */
2528 	if (!strncmp(name, "__tsan_func_", 12) ||
2529 	    !strcmp(name, "__tsan_atomic_signal_fence"))
2530 		return true;
2531 
2532 	return false;
2533 }
2534 
2535 static int classify_symbols(struct objtool_file *file)
2536 {
2537 	struct symbol *func;
2538 
2539 	for_each_sym(file, func) {
2540 		if (func->bind != STB_GLOBAL)
2541 			continue;
2542 
2543 		if (!strncmp(func->name, STATIC_CALL_TRAMP_PREFIX_STR,
2544 			     strlen(STATIC_CALL_TRAMP_PREFIX_STR)))
2545 			func->static_call_tramp = true;
2546 
2547 		if (arch_is_retpoline(func))
2548 			func->retpoline_thunk = true;
2549 
2550 		if (arch_is_rethunk(func))
2551 			func->return_thunk = true;
2552 
2553 		if (arch_ftrace_match(func->name))
2554 			func->fentry = true;
2555 
2556 		if (is_profiling_func(func->name))
2557 			func->profiling_func = true;
2558 	}
2559 
2560 	return 0;
2561 }
2562 
2563 static void mark_rodata(struct objtool_file *file)
2564 {
2565 	struct section *sec;
2566 	bool found = false;
2567 
2568 	/*
2569 	 * Search for the following rodata sections, each of which can
2570 	 * potentially contain jump tables:
2571 	 *
2572 	 * - .rodata: can contain GCC switch tables
2573 	 * - .rodata.<func>: same, if -fdata-sections is being used
2574 	 * - .rodata..c_jump_table: contains C annotated jump tables
2575 	 *
2576 	 * .rodata.str1.* sections are ignored; they don't contain jump tables.
2577 	 */
2578 	for_each_sec(file, sec) {
2579 		if (!strncmp(sec->name, ".rodata", 7) &&
2580 		    !strstr(sec->name, ".str1.")) {
2581 			sec->rodata = true;
2582 			found = true;
2583 		}
2584 	}
2585 
2586 	file->rodata = found;
2587 }
2588 
2589 static int decode_sections(struct objtool_file *file)
2590 {
2591 	int ret;
2592 
2593 	mark_rodata(file);
2594 
2595 	ret = init_pv_ops(file);
2596 	if (ret)
2597 		return ret;
2598 
2599 	/*
2600 	 * Must be before add_{jump_call}_destination.
2601 	 */
2602 	ret = classify_symbols(file);
2603 	if (ret)
2604 		return ret;
2605 
2606 	ret = decode_instructions(file);
2607 	if (ret)
2608 		return ret;
2609 
2610 	add_ignores(file);
2611 	add_uaccess_safe(file);
2612 
2613 	ret = add_ignore_alternatives(file);
2614 	if (ret)
2615 		return ret;
2616 
2617 	/*
2618 	 * Must be before read_unwind_hints() since that needs insn->noendbr.
2619 	 */
2620 	ret = read_noendbr_hints(file);
2621 	if (ret)
2622 		return ret;
2623 
2624 	/*
2625 	 * Must be before add_jump_destinations(), which depends on 'func'
2626 	 * being set for alternatives, to enable proper sibling call detection.
2627 	 */
2628 	if (opts.stackval || opts.orc || opts.uaccess || opts.noinstr) {
2629 		ret = add_special_section_alts(file);
2630 		if (ret)
2631 			return ret;
2632 	}
2633 
2634 	ret = add_jump_destinations(file);
2635 	if (ret)
2636 		return ret;
2637 
2638 	/*
2639 	 * Must be before add_call_destination(); it changes INSN_CALL to
2640 	 * INSN_JUMP.
2641 	 */
2642 	ret = read_intra_function_calls(file);
2643 	if (ret)
2644 		return ret;
2645 
2646 	ret = add_call_destinations(file);
2647 	if (ret)
2648 		return ret;
2649 
2650 	/*
2651 	 * Must be after add_call_destinations() such that it can override
2652 	 * dead_end_function() marks.
2653 	 */
2654 	ret = add_dead_ends(file);
2655 	if (ret)
2656 		return ret;
2657 
2658 	ret = add_jump_table_alts(file);
2659 	if (ret)
2660 		return ret;
2661 
2662 	ret = read_unwind_hints(file);
2663 	if (ret)
2664 		return ret;
2665 
2666 	ret = read_retpoline_hints(file);
2667 	if (ret)
2668 		return ret;
2669 
2670 	ret = read_instr_hints(file);
2671 	if (ret)
2672 		return ret;
2673 
2674 	ret = read_validate_unret_hints(file);
2675 	if (ret)
2676 		return ret;
2677 
2678 	return 0;
2679 }
2680 
2681 static bool is_fentry_call(struct instruction *insn)
2682 {
2683 	if (insn->type == INSN_CALL &&
2684 	    insn_call_dest(insn) &&
2685 	    insn_call_dest(insn)->fentry)
2686 		return true;
2687 
2688 	return false;
2689 }
2690 
2691 static bool has_modified_stack_frame(struct instruction *insn, struct insn_state *state)
2692 {
2693 	struct cfi_state *cfi = &state->cfi;
2694 	int i;
2695 
2696 	if (cfi->cfa.base != initial_func_cfi.cfa.base || cfi->drap)
2697 		return true;
2698 
2699 	if (cfi->cfa.offset != initial_func_cfi.cfa.offset)
2700 		return true;
2701 
2702 	if (cfi->stack_size != initial_func_cfi.cfa.offset)
2703 		return true;
2704 
2705 	for (i = 0; i < CFI_NUM_REGS; i++) {
2706 		if (cfi->regs[i].base != initial_func_cfi.regs[i].base ||
2707 		    cfi->regs[i].offset != initial_func_cfi.regs[i].offset)
2708 			return true;
2709 	}
2710 
2711 	return false;
2712 }
2713 
2714 static bool check_reg_frame_pos(const struct cfi_reg *reg,
2715 				int expected_offset)
2716 {
2717 	return reg->base == CFI_CFA &&
2718 	       reg->offset == expected_offset;
2719 }
2720 
2721 static bool has_valid_stack_frame(struct insn_state *state)
2722 {
2723 	struct cfi_state *cfi = &state->cfi;
2724 
2725 	if (cfi->cfa.base == CFI_BP &&
2726 	    check_reg_frame_pos(&cfi->regs[CFI_BP], -cfi->cfa.offset) &&
2727 	    check_reg_frame_pos(&cfi->regs[CFI_RA], -cfi->cfa.offset + 8))
2728 		return true;
2729 
2730 	if (cfi->drap && cfi->regs[CFI_BP].base == CFI_BP)
2731 		return true;
2732 
2733 	return false;
2734 }
2735 
2736 static int update_cfi_state_regs(struct instruction *insn,
2737 				  struct cfi_state *cfi,
2738 				  struct stack_op *op)
2739 {
2740 	struct cfi_reg *cfa = &cfi->cfa;
2741 
2742 	if (cfa->base != CFI_SP && cfa->base != CFI_SP_INDIRECT)
2743 		return 0;
2744 
2745 	/* push */
2746 	if (op->dest.type == OP_DEST_PUSH || op->dest.type == OP_DEST_PUSHF)
2747 		cfa->offset += 8;
2748 
2749 	/* pop */
2750 	if (op->src.type == OP_SRC_POP || op->src.type == OP_SRC_POPF)
2751 		cfa->offset -= 8;
2752 
2753 	/* add immediate to sp */
2754 	if (op->dest.type == OP_DEST_REG && op->src.type == OP_SRC_ADD &&
2755 	    op->dest.reg == CFI_SP && op->src.reg == CFI_SP)
2756 		cfa->offset -= op->src.offset;
2757 
2758 	return 0;
2759 }
2760 
2761 static void save_reg(struct cfi_state *cfi, unsigned char reg, int base, int offset)
2762 {
2763 	if (arch_callee_saved_reg(reg) &&
2764 	    cfi->regs[reg].base == CFI_UNDEFINED) {
2765 		cfi->regs[reg].base = base;
2766 		cfi->regs[reg].offset = offset;
2767 	}
2768 }
2769 
2770 static void restore_reg(struct cfi_state *cfi, unsigned char reg)
2771 {
2772 	cfi->regs[reg].base = initial_func_cfi.regs[reg].base;
2773 	cfi->regs[reg].offset = initial_func_cfi.regs[reg].offset;
2774 }
2775 
2776 /*
2777  * A note about DRAP stack alignment:
2778  *
2779  * GCC has the concept of a DRAP register, which is used to help keep track of
2780  * the stack pointer when aligning the stack.  r10 or r13 is used as the DRAP
2781  * register.  The typical DRAP pattern is:
2782  *
2783  *   4c 8d 54 24 08		lea    0x8(%rsp),%r10
2784  *   48 83 e4 c0		and    $0xffffffffffffffc0,%rsp
2785  *   41 ff 72 f8		pushq  -0x8(%r10)
2786  *   55				push   %rbp
2787  *   48 89 e5			mov    %rsp,%rbp
2788  *				(more pushes)
2789  *   41 52			push   %r10
2790  *				...
2791  *   41 5a			pop    %r10
2792  *				(more pops)
2793  *   5d				pop    %rbp
2794  *   49 8d 62 f8		lea    -0x8(%r10),%rsp
2795  *   c3				retq
2796  *
2797  * There are some variations in the epilogues, like:
2798  *
2799  *   5b				pop    %rbx
2800  *   41 5a			pop    %r10
2801  *   41 5c			pop    %r12
2802  *   41 5d			pop    %r13
2803  *   41 5e			pop    %r14
2804  *   c9				leaveq
2805  *   49 8d 62 f8		lea    -0x8(%r10),%rsp
2806  *   c3				retq
2807  *
2808  * and:
2809  *
2810  *   4c 8b 55 e8		mov    -0x18(%rbp),%r10
2811  *   48 8b 5d e0		mov    -0x20(%rbp),%rbx
2812  *   4c 8b 65 f0		mov    -0x10(%rbp),%r12
2813  *   4c 8b 6d f8		mov    -0x8(%rbp),%r13
2814  *   c9				leaveq
2815  *   49 8d 62 f8		lea    -0x8(%r10),%rsp
2816  *   c3				retq
2817  *
2818  * Sometimes r13 is used as the DRAP register, in which case it's saved and
2819  * restored beforehand:
2820  *
2821  *   41 55			push   %r13
2822  *   4c 8d 6c 24 10		lea    0x10(%rsp),%r13
2823  *   48 83 e4 f0		and    $0xfffffffffffffff0,%rsp
2824  *				...
2825  *   49 8d 65 f0		lea    -0x10(%r13),%rsp
2826  *   41 5d			pop    %r13
2827  *   c3				retq
2828  */
2829 static int update_cfi_state(struct instruction *insn,
2830 			    struct instruction *next_insn,
2831 			    struct cfi_state *cfi, struct stack_op *op)
2832 {
2833 	struct cfi_reg *cfa = &cfi->cfa;
2834 	struct cfi_reg *regs = cfi->regs;
2835 
2836 	/* stack operations don't make sense with an undefined CFA */
2837 	if (cfa->base == CFI_UNDEFINED) {
2838 		if (insn_func(insn)) {
2839 			WARN_INSN(insn, "undefined stack state");
2840 			return -1;
2841 		}
2842 		return 0;
2843 	}
2844 
2845 	if (cfi->type == UNWIND_HINT_TYPE_REGS ||
2846 	    cfi->type == UNWIND_HINT_TYPE_REGS_PARTIAL)
2847 		return update_cfi_state_regs(insn, cfi, op);
2848 
2849 	switch (op->dest.type) {
2850 
2851 	case OP_DEST_REG:
2852 		switch (op->src.type) {
2853 
2854 		case OP_SRC_REG:
2855 			if (op->src.reg == CFI_SP && op->dest.reg == CFI_BP &&
2856 			    cfa->base == CFI_SP &&
2857 			    check_reg_frame_pos(&regs[CFI_BP], -cfa->offset)) {
2858 
2859 				/* mov %rsp, %rbp */
2860 				cfa->base = op->dest.reg;
2861 				cfi->bp_scratch = false;
2862 			}
2863 
2864 			else if (op->src.reg == CFI_SP &&
2865 				 op->dest.reg == CFI_BP && cfi->drap) {
2866 
2867 				/* drap: mov %rsp, %rbp */
2868 				regs[CFI_BP].base = CFI_BP;
2869 				regs[CFI_BP].offset = -cfi->stack_size;
2870 				cfi->bp_scratch = false;
2871 			}
2872 
2873 			else if (op->src.reg == CFI_SP && cfa->base == CFI_SP) {
2874 
2875 				/*
2876 				 * mov %rsp, %reg
2877 				 *
2878 				 * This is needed for the rare case where GCC
2879 				 * does:
2880 				 *
2881 				 *   mov    %rsp, %rax
2882 				 *   ...
2883 				 *   mov    %rax, %rsp
2884 				 */
2885 				cfi->vals[op->dest.reg].base = CFI_CFA;
2886 				cfi->vals[op->dest.reg].offset = -cfi->stack_size;
2887 			}
2888 
2889 			else if (op->src.reg == CFI_BP && op->dest.reg == CFI_SP &&
2890 				 (cfa->base == CFI_BP || cfa->base == cfi->drap_reg)) {
2891 
2892 				/*
2893 				 * mov %rbp, %rsp
2894 				 *
2895 				 * Restore the original stack pointer (Clang).
2896 				 */
2897 				cfi->stack_size = -cfi->regs[CFI_BP].offset;
2898 			}
2899 
2900 			else if (op->dest.reg == cfa->base) {
2901 
2902 				/* mov %reg, %rsp */
2903 				if (cfa->base == CFI_SP &&
2904 				    cfi->vals[op->src.reg].base == CFI_CFA) {
2905 
2906 					/*
2907 					 * This is needed for the rare case
2908 					 * where GCC does something dumb like:
2909 					 *
2910 					 *   lea    0x8(%rsp), %rcx
2911 					 *   ...
2912 					 *   mov    %rcx, %rsp
2913 					 */
2914 					cfa->offset = -cfi->vals[op->src.reg].offset;
2915 					cfi->stack_size = cfa->offset;
2916 
2917 				} else if (cfa->base == CFI_SP &&
2918 					   cfi->vals[op->src.reg].base == CFI_SP_INDIRECT &&
2919 					   cfi->vals[op->src.reg].offset == cfa->offset) {
2920 
2921 					/*
2922 					 * Stack swizzle:
2923 					 *
2924 					 * 1: mov %rsp, (%[tos])
2925 					 * 2: mov %[tos], %rsp
2926 					 *    ...
2927 					 * 3: pop %rsp
2928 					 *
2929 					 * Where:
2930 					 *
2931 					 * 1 - places a pointer to the previous
2932 					 *     stack at the Top-of-Stack of the
2933 					 *     new stack.
2934 					 *
2935 					 * 2 - switches to the new stack.
2936 					 *
2937 					 * 3 - pops the Top-of-Stack to restore
2938 					 *     the original stack.
2939 					 *
2940 					 * Note: we set base to SP_INDIRECT
2941 					 * here and preserve offset. Therefore
2942 					 * when the unwinder reaches ToS it
2943 					 * will dereference SP and then add the
2944 					 * offset to find the next frame, IOW:
2945 					 * (%rsp) + offset.
2946 					 */
2947 					cfa->base = CFI_SP_INDIRECT;
2948 
2949 				} else {
2950 					cfa->base = CFI_UNDEFINED;
2951 					cfa->offset = 0;
2952 				}
2953 			}
2954 
2955 			else if (op->dest.reg == CFI_SP &&
2956 				 cfi->vals[op->src.reg].base == CFI_SP_INDIRECT &&
2957 				 cfi->vals[op->src.reg].offset == cfa->offset) {
2958 
2959 				/*
2960 				 * The same stack swizzle case 2) as above. But
2961 				 * because we can't change cfa->base, case 3)
2962 				 * will become a regular POP. Pretend we're a
2963 				 * PUSH so things don't go unbalanced.
2964 				 */
2965 				cfi->stack_size += 8;
2966 			}
2967 
2968 
2969 			break;
2970 
2971 		case OP_SRC_ADD:
2972 			if (op->dest.reg == CFI_SP && op->src.reg == CFI_SP) {
2973 
2974 				/* add imm, %rsp */
2975 				cfi->stack_size -= op->src.offset;
2976 				if (cfa->base == CFI_SP)
2977 					cfa->offset -= op->src.offset;
2978 				break;
2979 			}
2980 
2981 			if (op->dest.reg == CFI_SP && op->src.reg == CFI_BP) {
2982 
2983 				/* lea disp(%rbp), %rsp */
2984 				cfi->stack_size = -(op->src.offset + regs[CFI_BP].offset);
2985 				break;
2986 			}
2987 
2988 			if (op->src.reg == CFI_SP && cfa->base == CFI_SP) {
2989 
2990 				/* drap: lea disp(%rsp), %drap */
2991 				cfi->drap_reg = op->dest.reg;
2992 
2993 				/*
2994 				 * lea disp(%rsp), %reg
2995 				 *
2996 				 * This is needed for the rare case where GCC
2997 				 * does something dumb like:
2998 				 *
2999 				 *   lea    0x8(%rsp), %rcx
3000 				 *   ...
3001 				 *   mov    %rcx, %rsp
3002 				 */
3003 				cfi->vals[op->dest.reg].base = CFI_CFA;
3004 				cfi->vals[op->dest.reg].offset = \
3005 					-cfi->stack_size + op->src.offset;
3006 
3007 				break;
3008 			}
3009 
3010 			if (cfi->drap && op->dest.reg == CFI_SP &&
3011 			    op->src.reg == cfi->drap_reg) {
3012 
3013 				 /* drap: lea disp(%drap), %rsp */
3014 				cfa->base = CFI_SP;
3015 				cfa->offset = cfi->stack_size = -op->src.offset;
3016 				cfi->drap_reg = CFI_UNDEFINED;
3017 				cfi->drap = false;
3018 				break;
3019 			}
3020 
3021 			if (op->dest.reg == cfi->cfa.base && !(next_insn && next_insn->hint)) {
3022 				WARN_INSN(insn, "unsupported stack register modification");
3023 				return -1;
3024 			}
3025 
3026 			break;
3027 
3028 		case OP_SRC_AND:
3029 			if (op->dest.reg != CFI_SP ||
3030 			    (cfi->drap_reg != CFI_UNDEFINED && cfa->base != CFI_SP) ||
3031 			    (cfi->drap_reg == CFI_UNDEFINED && cfa->base != CFI_BP)) {
3032 				WARN_INSN(insn, "unsupported stack pointer realignment");
3033 				return -1;
3034 			}
3035 
3036 			if (cfi->drap_reg != CFI_UNDEFINED) {
3037 				/* drap: and imm, %rsp */
3038 				cfa->base = cfi->drap_reg;
3039 				cfa->offset = cfi->stack_size = 0;
3040 				cfi->drap = true;
3041 			}
3042 
3043 			/*
3044 			 * Older versions of GCC (4.8ish) realign the stack
3045 			 * without DRAP, with a frame pointer.
3046 			 */
3047 
3048 			break;
3049 
3050 		case OP_SRC_POP:
3051 		case OP_SRC_POPF:
3052 			if (op->dest.reg == CFI_SP && cfa->base == CFI_SP_INDIRECT) {
3053 
3054 				/* pop %rsp; # restore from a stack swizzle */
3055 				cfa->base = CFI_SP;
3056 				break;
3057 			}
3058 
3059 			if (!cfi->drap && op->dest.reg == cfa->base) {
3060 
3061 				/* pop %rbp */
3062 				cfa->base = CFI_SP;
3063 			}
3064 
3065 			if (cfi->drap && cfa->base == CFI_BP_INDIRECT &&
3066 			    op->dest.reg == cfi->drap_reg &&
3067 			    cfi->drap_offset == -cfi->stack_size) {
3068 
3069 				/* drap: pop %drap */
3070 				cfa->base = cfi->drap_reg;
3071 				cfa->offset = 0;
3072 				cfi->drap_offset = -1;
3073 
3074 			} else if (cfi->stack_size == -regs[op->dest.reg].offset) {
3075 
3076 				/* pop %reg */
3077 				restore_reg(cfi, op->dest.reg);
3078 			}
3079 
3080 			cfi->stack_size -= 8;
3081 			if (cfa->base == CFI_SP)
3082 				cfa->offset -= 8;
3083 
3084 			break;
3085 
3086 		case OP_SRC_REG_INDIRECT:
3087 			if (!cfi->drap && op->dest.reg == cfa->base &&
3088 			    op->dest.reg == CFI_BP) {
3089 
3090 				/* mov disp(%rsp), %rbp */
3091 				cfa->base = CFI_SP;
3092 				cfa->offset = cfi->stack_size;
3093 			}
3094 
3095 			if (cfi->drap && op->src.reg == CFI_BP &&
3096 			    op->src.offset == cfi->drap_offset) {
3097 
3098 				/* drap: mov disp(%rbp), %drap */
3099 				cfa->base = cfi->drap_reg;
3100 				cfa->offset = 0;
3101 				cfi->drap_offset = -1;
3102 			}
3103 
3104 			if (cfi->drap && op->src.reg == CFI_BP &&
3105 			    op->src.offset == regs[op->dest.reg].offset) {
3106 
3107 				/* drap: mov disp(%rbp), %reg */
3108 				restore_reg(cfi, op->dest.reg);
3109 
3110 			} else if (op->src.reg == cfa->base &&
3111 			    op->src.offset == regs[op->dest.reg].offset + cfa->offset) {
3112 
3113 				/* mov disp(%rbp), %reg */
3114 				/* mov disp(%rsp), %reg */
3115 				restore_reg(cfi, op->dest.reg);
3116 
3117 			} else if (op->src.reg == CFI_SP &&
3118 				   op->src.offset == regs[op->dest.reg].offset + cfi->stack_size) {
3119 
3120 				/* mov disp(%rsp), %reg */
3121 				restore_reg(cfi, op->dest.reg);
3122 			}
3123 
3124 			break;
3125 
3126 		default:
3127 			WARN_INSN(insn, "unknown stack-related instruction");
3128 			return -1;
3129 		}
3130 
3131 		break;
3132 
3133 	case OP_DEST_PUSH:
3134 	case OP_DEST_PUSHF:
3135 		cfi->stack_size += 8;
3136 		if (cfa->base == CFI_SP)
3137 			cfa->offset += 8;
3138 
3139 		if (op->src.type != OP_SRC_REG)
3140 			break;
3141 
3142 		if (cfi->drap) {
3143 			if (op->src.reg == cfa->base && op->src.reg == cfi->drap_reg) {
3144 
3145 				/* drap: push %drap */
3146 				cfa->base = CFI_BP_INDIRECT;
3147 				cfa->offset = -cfi->stack_size;
3148 
3149 				/* save drap so we know when to restore it */
3150 				cfi->drap_offset = -cfi->stack_size;
3151 
3152 			} else if (op->src.reg == CFI_BP && cfa->base == cfi->drap_reg) {
3153 
3154 				/* drap: push %rbp */
3155 				cfi->stack_size = 0;
3156 
3157 			} else {
3158 
3159 				/* drap: push %reg */
3160 				save_reg(cfi, op->src.reg, CFI_BP, -cfi->stack_size);
3161 			}
3162 
3163 		} else {
3164 
3165 			/* push %reg */
3166 			save_reg(cfi, op->src.reg, CFI_CFA, -cfi->stack_size);
3167 		}
3168 
3169 		/* detect when asm code uses rbp as a scratch register */
3170 		if (opts.stackval && insn_func(insn) && op->src.reg == CFI_BP &&
3171 		    cfa->base != CFI_BP)
3172 			cfi->bp_scratch = true;
3173 		break;
3174 
3175 	case OP_DEST_REG_INDIRECT:
3176 
3177 		if (cfi->drap) {
3178 			if (op->src.reg == cfa->base && op->src.reg == cfi->drap_reg) {
3179 
3180 				/* drap: mov %drap, disp(%rbp) */
3181 				cfa->base = CFI_BP_INDIRECT;
3182 				cfa->offset = op->dest.offset;
3183 
3184 				/* save drap offset so we know when to restore it */
3185 				cfi->drap_offset = op->dest.offset;
3186 			} else {
3187 
3188 				/* drap: mov reg, disp(%rbp) */
3189 				save_reg(cfi, op->src.reg, CFI_BP, op->dest.offset);
3190 			}
3191 
3192 		} else if (op->dest.reg == cfa->base) {
3193 
3194 			/* mov reg, disp(%rbp) */
3195 			/* mov reg, disp(%rsp) */
3196 			save_reg(cfi, op->src.reg, CFI_CFA,
3197 				 op->dest.offset - cfi->cfa.offset);
3198 
3199 		} else if (op->dest.reg == CFI_SP) {
3200 
3201 			/* mov reg, disp(%rsp) */
3202 			save_reg(cfi, op->src.reg, CFI_CFA,
3203 				 op->dest.offset - cfi->stack_size);
3204 
3205 		} else if (op->src.reg == CFI_SP && op->dest.offset == 0) {
3206 
3207 			/* mov %rsp, (%reg); # setup a stack swizzle. */
3208 			cfi->vals[op->dest.reg].base = CFI_SP_INDIRECT;
3209 			cfi->vals[op->dest.reg].offset = cfa->offset;
3210 		}
3211 
3212 		break;
3213 
3214 	case OP_DEST_MEM:
3215 		if (op->src.type != OP_SRC_POP && op->src.type != OP_SRC_POPF) {
3216 			WARN_INSN(insn, "unknown stack-related memory operation");
3217 			return -1;
3218 		}
3219 
3220 		/* pop mem */
3221 		cfi->stack_size -= 8;
3222 		if (cfa->base == CFI_SP)
3223 			cfa->offset -= 8;
3224 
3225 		break;
3226 
3227 	default:
3228 		WARN_INSN(insn, "unknown stack-related instruction");
3229 		return -1;
3230 	}
3231 
3232 	return 0;
3233 }
3234 
3235 /*
3236  * The stack layouts of alternatives instructions can sometimes diverge when
3237  * they have stack modifications.  That's fine as long as the potential stack
3238  * layouts don't conflict at any given potential instruction boundary.
3239  *
3240  * Flatten the CFIs of the different alternative code streams (both original
3241  * and replacement) into a single shared CFI array which can be used to detect
3242  * conflicts and nicely feed a linear array of ORC entries to the unwinder.
3243  */
3244 static int propagate_alt_cfi(struct objtool_file *file, struct instruction *insn)
3245 {
3246 	struct cfi_state **alt_cfi;
3247 	int group_off;
3248 
3249 	if (!insn->alt_group)
3250 		return 0;
3251 
3252 	if (!insn->cfi) {
3253 		WARN("CFI missing");
3254 		return -1;
3255 	}
3256 
3257 	alt_cfi = insn->alt_group->cfi;
3258 	group_off = insn->offset - insn->alt_group->first_insn->offset;
3259 
3260 	if (!alt_cfi[group_off]) {
3261 		alt_cfi[group_off] = insn->cfi;
3262 	} else {
3263 		if (cficmp(alt_cfi[group_off], insn->cfi)) {
3264 			struct alt_group *orig_group = insn->alt_group->orig_group ?: insn->alt_group;
3265 			struct instruction *orig = orig_group->first_insn;
3266 			char *where = offstr(insn->sec, insn->offset);
3267 			WARN_INSN(orig, "stack layout conflict in alternatives: %s", where);
3268 			free(where);
3269 			return -1;
3270 		}
3271 	}
3272 
3273 	return 0;
3274 }
3275 
3276 static int handle_insn_ops(struct instruction *insn,
3277 			   struct instruction *next_insn,
3278 			   struct insn_state *state)
3279 {
3280 	struct stack_op *op;
3281 
3282 	for (op = insn->stack_ops; op; op = op->next) {
3283 
3284 		if (update_cfi_state(insn, next_insn, &state->cfi, op))
3285 			return 1;
3286 
3287 		if (!insn->alt_group)
3288 			continue;
3289 
3290 		if (op->dest.type == OP_DEST_PUSHF) {
3291 			if (!state->uaccess_stack) {
3292 				state->uaccess_stack = 1;
3293 			} else if (state->uaccess_stack >> 31) {
3294 				WARN_INSN(insn, "PUSHF stack exhausted");
3295 				return 1;
3296 			}
3297 			state->uaccess_stack <<= 1;
3298 			state->uaccess_stack  |= state->uaccess;
3299 		}
3300 
3301 		if (op->src.type == OP_SRC_POPF) {
3302 			if (state->uaccess_stack) {
3303 				state->uaccess = state->uaccess_stack & 1;
3304 				state->uaccess_stack >>= 1;
3305 				if (state->uaccess_stack == 1)
3306 					state->uaccess_stack = 0;
3307 			}
3308 		}
3309 	}
3310 
3311 	return 0;
3312 }
3313 
3314 static bool insn_cfi_match(struct instruction *insn, struct cfi_state *cfi2)
3315 {
3316 	struct cfi_state *cfi1 = insn->cfi;
3317 	int i;
3318 
3319 	if (!cfi1) {
3320 		WARN("CFI missing");
3321 		return false;
3322 	}
3323 
3324 	if (memcmp(&cfi1->cfa, &cfi2->cfa, sizeof(cfi1->cfa))) {
3325 
3326 		WARN_INSN(insn, "stack state mismatch: cfa1=%d%+d cfa2=%d%+d",
3327 			  cfi1->cfa.base, cfi1->cfa.offset,
3328 			  cfi2->cfa.base, cfi2->cfa.offset);
3329 
3330 	} else if (memcmp(&cfi1->regs, &cfi2->regs, sizeof(cfi1->regs))) {
3331 		for (i = 0; i < CFI_NUM_REGS; i++) {
3332 			if (!memcmp(&cfi1->regs[i], &cfi2->regs[i],
3333 				    sizeof(struct cfi_reg)))
3334 				continue;
3335 
3336 			WARN_INSN(insn, "stack state mismatch: reg1[%d]=%d%+d reg2[%d]=%d%+d",
3337 				  i, cfi1->regs[i].base, cfi1->regs[i].offset,
3338 				  i, cfi2->regs[i].base, cfi2->regs[i].offset);
3339 			break;
3340 		}
3341 
3342 	} else if (cfi1->type != cfi2->type) {
3343 
3344 		WARN_INSN(insn, "stack state mismatch: type1=%d type2=%d",
3345 			  cfi1->type, cfi2->type);
3346 
3347 	} else if (cfi1->drap != cfi2->drap ||
3348 		   (cfi1->drap && cfi1->drap_reg != cfi2->drap_reg) ||
3349 		   (cfi1->drap && cfi1->drap_offset != cfi2->drap_offset)) {
3350 
3351 		WARN_INSN(insn, "stack state mismatch: drap1=%d(%d,%d) drap2=%d(%d,%d)",
3352 			  cfi1->drap, cfi1->drap_reg, cfi1->drap_offset,
3353 			  cfi2->drap, cfi2->drap_reg, cfi2->drap_offset);
3354 
3355 	} else
3356 		return true;
3357 
3358 	return false;
3359 }
3360 
3361 static inline bool func_uaccess_safe(struct symbol *func)
3362 {
3363 	if (func)
3364 		return func->uaccess_safe;
3365 
3366 	return false;
3367 }
3368 
3369 static inline const char *call_dest_name(struct instruction *insn)
3370 {
3371 	static char pvname[19];
3372 	struct reloc *rel;
3373 	int idx;
3374 
3375 	if (insn_call_dest(insn))
3376 		return insn_call_dest(insn)->name;
3377 
3378 	rel = insn_reloc(NULL, insn);
3379 	if (rel && !strcmp(rel->sym->name, "pv_ops")) {
3380 		idx = (rel->addend / sizeof(void *));
3381 		snprintf(pvname, sizeof(pvname), "pv_ops[%d]", idx);
3382 		return pvname;
3383 	}
3384 
3385 	return "{dynamic}";
3386 }
3387 
3388 static bool pv_call_dest(struct objtool_file *file, struct instruction *insn)
3389 {
3390 	struct symbol *target;
3391 	struct reloc *rel;
3392 	int idx;
3393 
3394 	rel = insn_reloc(file, insn);
3395 	if (!rel || strcmp(rel->sym->name, "pv_ops"))
3396 		return false;
3397 
3398 	idx = (arch_dest_reloc_offset(rel->addend) / sizeof(void *));
3399 
3400 	if (file->pv_ops[idx].clean)
3401 		return true;
3402 
3403 	file->pv_ops[idx].clean = true;
3404 
3405 	list_for_each_entry(target, &file->pv_ops[idx].targets, pv_target) {
3406 		if (!target->sec->noinstr) {
3407 			WARN("pv_ops[%d]: %s", idx, target->name);
3408 			file->pv_ops[idx].clean = false;
3409 		}
3410 	}
3411 
3412 	return file->pv_ops[idx].clean;
3413 }
3414 
3415 static inline bool noinstr_call_dest(struct objtool_file *file,
3416 				     struct instruction *insn,
3417 				     struct symbol *func)
3418 {
3419 	/*
3420 	 * We can't deal with indirect function calls at present;
3421 	 * assume they're instrumented.
3422 	 */
3423 	if (!func) {
3424 		if (file->pv_ops)
3425 			return pv_call_dest(file, insn);
3426 
3427 		return false;
3428 	}
3429 
3430 	/*
3431 	 * If the symbol is from a noinstr section; we good.
3432 	 */
3433 	if (func->sec->noinstr)
3434 		return true;
3435 
3436 	/*
3437 	 * If the symbol is a static_call trampoline, we can't tell.
3438 	 */
3439 	if (func->static_call_tramp)
3440 		return true;
3441 
3442 	/*
3443 	 * The __ubsan_handle_*() calls are like WARN(), they only happen when
3444 	 * something 'BAD' happened. At the risk of taking the machine down,
3445 	 * let them proceed to get the message out.
3446 	 */
3447 	if (!strncmp(func->name, "__ubsan_handle_", 15))
3448 		return true;
3449 
3450 	return false;
3451 }
3452 
3453 static int validate_call(struct objtool_file *file,
3454 			 struct instruction *insn,
3455 			 struct insn_state *state)
3456 {
3457 	if (state->noinstr && state->instr <= 0 &&
3458 	    !noinstr_call_dest(file, insn, insn_call_dest(insn))) {
3459 		WARN_INSN(insn, "call to %s() leaves .noinstr.text section", call_dest_name(insn));
3460 		return 1;
3461 	}
3462 
3463 	if (state->uaccess && !func_uaccess_safe(insn_call_dest(insn))) {
3464 		WARN_INSN(insn, "call to %s() with UACCESS enabled", call_dest_name(insn));
3465 		return 1;
3466 	}
3467 
3468 	if (state->df) {
3469 		WARN_INSN(insn, "call to %s() with DF set", call_dest_name(insn));
3470 		return 1;
3471 	}
3472 
3473 	return 0;
3474 }
3475 
3476 static int validate_sibling_call(struct objtool_file *file,
3477 				 struct instruction *insn,
3478 				 struct insn_state *state)
3479 {
3480 	if (insn_func(insn) && has_modified_stack_frame(insn, state)) {
3481 		WARN_INSN(insn, "sibling call from callable instruction with modified stack frame");
3482 		return 1;
3483 	}
3484 
3485 	return validate_call(file, insn, state);
3486 }
3487 
3488 static int validate_return(struct symbol *func, struct instruction *insn, struct insn_state *state)
3489 {
3490 	if (state->noinstr && state->instr > 0) {
3491 		WARN_INSN(insn, "return with instrumentation enabled");
3492 		return 1;
3493 	}
3494 
3495 	if (state->uaccess && !func_uaccess_safe(func)) {
3496 		WARN_INSN(insn, "return with UACCESS enabled");
3497 		return 1;
3498 	}
3499 
3500 	if (!state->uaccess && func_uaccess_safe(func)) {
3501 		WARN_INSN(insn, "return with UACCESS disabled from a UACCESS-safe function");
3502 		return 1;
3503 	}
3504 
3505 	if (state->df) {
3506 		WARN_INSN(insn, "return with DF set");
3507 		return 1;
3508 	}
3509 
3510 	if (func && has_modified_stack_frame(insn, state)) {
3511 		WARN_INSN(insn, "return with modified stack frame");
3512 		return 1;
3513 	}
3514 
3515 	if (state->cfi.bp_scratch) {
3516 		WARN_INSN(insn, "BP used as a scratch register");
3517 		return 1;
3518 	}
3519 
3520 	return 0;
3521 }
3522 
3523 static struct instruction *next_insn_to_validate(struct objtool_file *file,
3524 						 struct instruction *insn)
3525 {
3526 	struct alt_group *alt_group = insn->alt_group;
3527 
3528 	/*
3529 	 * Simulate the fact that alternatives are patched in-place.  When the
3530 	 * end of a replacement alt_group is reached, redirect objtool flow to
3531 	 * the end of the original alt_group.
3532 	 *
3533 	 * insn->alts->insn -> alt_group->first_insn
3534 	 *		       ...
3535 	 *		       alt_group->last_insn
3536 	 *		       [alt_group->nop]      -> next(orig_group->last_insn)
3537 	 */
3538 	if (alt_group) {
3539 		if (alt_group->nop) {
3540 			/* ->nop implies ->orig_group */
3541 			if (insn == alt_group->last_insn)
3542 				return alt_group->nop;
3543 			if (insn == alt_group->nop)
3544 				goto next_orig;
3545 		}
3546 		if (insn == alt_group->last_insn && alt_group->orig_group)
3547 			goto next_orig;
3548 	}
3549 
3550 	return next_insn_same_sec(file, insn);
3551 
3552 next_orig:
3553 	return next_insn_same_sec(file, alt_group->orig_group->last_insn);
3554 }
3555 
3556 /*
3557  * Follow the branch starting at the given instruction, and recursively follow
3558  * any other branches (jumps).  Meanwhile, track the frame pointer state at
3559  * each instruction and validate all the rules described in
3560  * tools/objtool/Documentation/objtool.txt.
3561  */
3562 static int validate_branch(struct objtool_file *file, struct symbol *func,
3563 			   struct instruction *insn, struct insn_state state)
3564 {
3565 	struct alternative *alt;
3566 	struct instruction *next_insn, *prev_insn = NULL;
3567 	struct section *sec;
3568 	u8 visited;
3569 	int ret;
3570 
3571 	sec = insn->sec;
3572 
3573 	while (1) {
3574 		next_insn = next_insn_to_validate(file, insn);
3575 
3576 		if (func && insn_func(insn) && func != insn_func(insn)->pfunc) {
3577 			/* Ignore KCFI type preambles, which always fall through */
3578 			if (!strncmp(func->name, "__cfi_", 6) ||
3579 			    !strncmp(func->name, "__pfx_", 6))
3580 				return 0;
3581 
3582 			WARN("%s() falls through to next function %s()",
3583 			     func->name, insn_func(insn)->name);
3584 			return 1;
3585 		}
3586 
3587 		if (func && insn->ignore) {
3588 			WARN_INSN(insn, "BUG: why am I validating an ignored function?");
3589 			return 1;
3590 		}
3591 
3592 		visited = VISITED_BRANCH << state.uaccess;
3593 		if (insn->visited & VISITED_BRANCH_MASK) {
3594 			if (!insn->hint && !insn_cfi_match(insn, &state.cfi))
3595 				return 1;
3596 
3597 			if (insn->visited & visited)
3598 				return 0;
3599 		} else {
3600 			nr_insns_visited++;
3601 		}
3602 
3603 		if (state.noinstr)
3604 			state.instr += insn->instr;
3605 
3606 		if (insn->hint) {
3607 			if (insn->restore) {
3608 				struct instruction *save_insn, *i;
3609 
3610 				i = insn;
3611 				save_insn = NULL;
3612 
3613 				sym_for_each_insn_continue_reverse(file, func, i) {
3614 					if (i->save) {
3615 						save_insn = i;
3616 						break;
3617 					}
3618 				}
3619 
3620 				if (!save_insn) {
3621 					WARN_INSN(insn, "no corresponding CFI save for CFI restore");
3622 					return 1;
3623 				}
3624 
3625 				if (!save_insn->visited) {
3626 					WARN_INSN(insn, "objtool isn't smart enough to handle this CFI save/restore combo");
3627 					return 1;
3628 				}
3629 
3630 				insn->cfi = save_insn->cfi;
3631 				nr_cfi_reused++;
3632 			}
3633 
3634 			state.cfi = *insn->cfi;
3635 		} else {
3636 			/* XXX track if we actually changed state.cfi */
3637 
3638 			if (prev_insn && !cficmp(prev_insn->cfi, &state.cfi)) {
3639 				insn->cfi = prev_insn->cfi;
3640 				nr_cfi_reused++;
3641 			} else {
3642 				insn->cfi = cfi_hash_find_or_add(&state.cfi);
3643 			}
3644 		}
3645 
3646 		insn->visited |= visited;
3647 
3648 		if (propagate_alt_cfi(file, insn))
3649 			return 1;
3650 
3651 		if (!insn->ignore_alts && insn->alts) {
3652 			bool skip_orig = false;
3653 
3654 			for (alt = insn->alts; alt; alt = alt->next) {
3655 				if (alt->skip_orig)
3656 					skip_orig = true;
3657 
3658 				ret = validate_branch(file, func, alt->insn, state);
3659 				if (ret) {
3660 					if (opts.backtrace)
3661 						BT_FUNC("(alt)", insn);
3662 					return ret;
3663 				}
3664 			}
3665 
3666 			if (skip_orig)
3667 				return 0;
3668 		}
3669 
3670 		if (handle_insn_ops(insn, next_insn, &state))
3671 			return 1;
3672 
3673 		switch (insn->type) {
3674 
3675 		case INSN_RETURN:
3676 			return validate_return(func, insn, &state);
3677 
3678 		case INSN_CALL:
3679 		case INSN_CALL_DYNAMIC:
3680 			ret = validate_call(file, insn, &state);
3681 			if (ret)
3682 				return ret;
3683 
3684 			if (opts.stackval && func && !is_fentry_call(insn) &&
3685 			    !has_valid_stack_frame(&state)) {
3686 				WARN_INSN(insn, "call without frame pointer save/setup");
3687 				return 1;
3688 			}
3689 
3690 			if (insn->dead_end)
3691 				return 0;
3692 
3693 			break;
3694 
3695 		case INSN_JUMP_CONDITIONAL:
3696 		case INSN_JUMP_UNCONDITIONAL:
3697 			if (is_sibling_call(insn)) {
3698 				ret = validate_sibling_call(file, insn, &state);
3699 				if (ret)
3700 					return ret;
3701 
3702 			} else if (insn->jump_dest) {
3703 				ret = validate_branch(file, func,
3704 						      insn->jump_dest, state);
3705 				if (ret) {
3706 					if (opts.backtrace)
3707 						BT_FUNC("(branch)", insn);
3708 					return ret;
3709 				}
3710 			}
3711 
3712 			if (insn->type == INSN_JUMP_UNCONDITIONAL)
3713 				return 0;
3714 
3715 			break;
3716 
3717 		case INSN_JUMP_DYNAMIC:
3718 		case INSN_JUMP_DYNAMIC_CONDITIONAL:
3719 			if (is_sibling_call(insn)) {
3720 				ret = validate_sibling_call(file, insn, &state);
3721 				if (ret)
3722 					return ret;
3723 			}
3724 
3725 			if (insn->type == INSN_JUMP_DYNAMIC)
3726 				return 0;
3727 
3728 			break;
3729 
3730 		case INSN_CONTEXT_SWITCH:
3731 			if (func && (!next_insn || !next_insn->hint)) {
3732 				WARN_INSN(insn, "unsupported instruction in callable function");
3733 				return 1;
3734 			}
3735 			return 0;
3736 
3737 		case INSN_STAC:
3738 			if (state.uaccess) {
3739 				WARN_INSN(insn, "recursive UACCESS enable");
3740 				return 1;
3741 			}
3742 
3743 			state.uaccess = true;
3744 			break;
3745 
3746 		case INSN_CLAC:
3747 			if (!state.uaccess && func) {
3748 				WARN_INSN(insn, "redundant UACCESS disable");
3749 				return 1;
3750 			}
3751 
3752 			if (func_uaccess_safe(func) && !state.uaccess_stack) {
3753 				WARN_INSN(insn, "UACCESS-safe disables UACCESS");
3754 				return 1;
3755 			}
3756 
3757 			state.uaccess = false;
3758 			break;
3759 
3760 		case INSN_STD:
3761 			if (state.df) {
3762 				WARN_INSN(insn, "recursive STD");
3763 				return 1;
3764 			}
3765 
3766 			state.df = true;
3767 			break;
3768 
3769 		case INSN_CLD:
3770 			if (!state.df && func) {
3771 				WARN_INSN(insn, "redundant CLD");
3772 				return 1;
3773 			}
3774 
3775 			state.df = false;
3776 			break;
3777 
3778 		default:
3779 			break;
3780 		}
3781 
3782 		if (insn->dead_end)
3783 			return 0;
3784 
3785 		if (!next_insn) {
3786 			if (state.cfi.cfa.base == CFI_UNDEFINED)
3787 				return 0;
3788 			WARN("%s: unexpected end of section", sec->name);
3789 			return 1;
3790 		}
3791 
3792 		prev_insn = insn;
3793 		insn = next_insn;
3794 	}
3795 
3796 	return 0;
3797 }
3798 
3799 static int validate_unwind_hint(struct objtool_file *file,
3800 				  struct instruction *insn,
3801 				  struct insn_state *state)
3802 {
3803 	if (insn->hint && !insn->visited && !insn->ignore) {
3804 		int ret = validate_branch(file, insn_func(insn), insn, *state);
3805 		if (ret && opts.backtrace)
3806 			BT_FUNC("<=== (hint)", insn);
3807 		return ret;
3808 	}
3809 
3810 	return 0;
3811 }
3812 
3813 static int validate_unwind_hints(struct objtool_file *file, struct section *sec)
3814 {
3815 	struct instruction *insn;
3816 	struct insn_state state;
3817 	int warnings = 0;
3818 
3819 	if (!file->hints)
3820 		return 0;
3821 
3822 	init_insn_state(file, &state, sec);
3823 
3824 	if (sec) {
3825 		sec_for_each_insn(file, sec, insn)
3826 			warnings += validate_unwind_hint(file, insn, &state);
3827 	} else {
3828 		for_each_insn(file, insn)
3829 			warnings += validate_unwind_hint(file, insn, &state);
3830 	}
3831 
3832 	return warnings;
3833 }
3834 
3835 /*
3836  * Validate rethunk entry constraint: must untrain RET before the first RET.
3837  *
3838  * Follow every branch (intra-function) and ensure VALIDATE_UNRET_END comes
3839  * before an actual RET instruction.
3840  */
3841 static int validate_unret(struct objtool_file *file, struct instruction *insn)
3842 {
3843 	struct instruction *next, *dest;
3844 	int ret, warnings = 0;
3845 
3846 	for (;;) {
3847 		next = next_insn_to_validate(file, insn);
3848 
3849 		if (insn->visited & VISITED_UNRET)
3850 			return 0;
3851 
3852 		insn->visited |= VISITED_UNRET;
3853 
3854 		if (!insn->ignore_alts && insn->alts) {
3855 			struct alternative *alt;
3856 			bool skip_orig = false;
3857 
3858 			for (alt = insn->alts; alt; alt = alt->next) {
3859 				if (alt->skip_orig)
3860 					skip_orig = true;
3861 
3862 				ret = validate_unret(file, alt->insn);
3863 				if (ret) {
3864 				        if (opts.backtrace)
3865 						BT_FUNC("(alt)", insn);
3866 					return ret;
3867 				}
3868 			}
3869 
3870 			if (skip_orig)
3871 				return 0;
3872 		}
3873 
3874 		switch (insn->type) {
3875 
3876 		case INSN_CALL_DYNAMIC:
3877 		case INSN_JUMP_DYNAMIC:
3878 		case INSN_JUMP_DYNAMIC_CONDITIONAL:
3879 			WARN_INSN(insn, "early indirect call");
3880 			return 1;
3881 
3882 		case INSN_JUMP_UNCONDITIONAL:
3883 		case INSN_JUMP_CONDITIONAL:
3884 			if (!is_sibling_call(insn)) {
3885 				if (!insn->jump_dest) {
3886 					WARN_INSN(insn, "unresolved jump target after linking?!?");
3887 					return -1;
3888 				}
3889 				ret = validate_unret(file, insn->jump_dest);
3890 				if (ret) {
3891 					if (opts.backtrace) {
3892 						BT_FUNC("(branch%s)", insn,
3893 							insn->type == INSN_JUMP_CONDITIONAL ? "-cond" : "");
3894 					}
3895 					return ret;
3896 				}
3897 
3898 				if (insn->type == INSN_JUMP_UNCONDITIONAL)
3899 					return 0;
3900 
3901 				break;
3902 			}
3903 
3904 			/* fallthrough */
3905 		case INSN_CALL:
3906 			dest = find_insn(file, insn_call_dest(insn)->sec,
3907 					 insn_call_dest(insn)->offset);
3908 			if (!dest) {
3909 				WARN("Unresolved function after linking!?: %s",
3910 				     insn_call_dest(insn)->name);
3911 				return -1;
3912 			}
3913 
3914 			ret = validate_unret(file, dest);
3915 			if (ret) {
3916 				if (opts.backtrace)
3917 					BT_FUNC("(call)", insn);
3918 				return ret;
3919 			}
3920 			/*
3921 			 * If a call returns without error, it must have seen UNTRAIN_RET.
3922 			 * Therefore any non-error return is a success.
3923 			 */
3924 			return 0;
3925 
3926 		case INSN_RETURN:
3927 			WARN_INSN(insn, "RET before UNTRAIN");
3928 			return 1;
3929 
3930 		case INSN_NOP:
3931 			if (insn->retpoline_safe)
3932 				return 0;
3933 			break;
3934 
3935 		default:
3936 			break;
3937 		}
3938 
3939 		if (!next) {
3940 			WARN_INSN(insn, "teh end!");
3941 			return -1;
3942 		}
3943 		insn = next;
3944 	}
3945 
3946 	return warnings;
3947 }
3948 
3949 /*
3950  * Validate that all branches starting at VALIDATE_UNRET_BEGIN encounter
3951  * VALIDATE_UNRET_END before RET.
3952  */
3953 static int validate_unrets(struct objtool_file *file)
3954 {
3955 	struct instruction *insn;
3956 	int ret, warnings = 0;
3957 
3958 	for_each_insn(file, insn) {
3959 		if (!insn->unret)
3960 			continue;
3961 
3962 		ret = validate_unret(file, insn);
3963 		if (ret < 0) {
3964 			WARN_INSN(insn, "Failed UNRET validation");
3965 			return ret;
3966 		}
3967 		warnings += ret;
3968 	}
3969 
3970 	return warnings;
3971 }
3972 
3973 static int validate_retpoline(struct objtool_file *file)
3974 {
3975 	struct instruction *insn;
3976 	int warnings = 0;
3977 
3978 	for_each_insn(file, insn) {
3979 		if (insn->type != INSN_JUMP_DYNAMIC &&
3980 		    insn->type != INSN_CALL_DYNAMIC &&
3981 		    insn->type != INSN_RETURN)
3982 			continue;
3983 
3984 		if (insn->retpoline_safe)
3985 			continue;
3986 
3987 		if (insn->sec->init)
3988 			continue;
3989 
3990 		if (insn->type == INSN_RETURN) {
3991 			if (opts.rethunk) {
3992 				WARN_INSN(insn, "'naked' return found in RETHUNK build");
3993 			} else
3994 				continue;
3995 		} else {
3996 			WARN_INSN(insn, "indirect %s found in RETPOLINE build",
3997 				  insn->type == INSN_JUMP_DYNAMIC ? "jump" : "call");
3998 		}
3999 
4000 		warnings++;
4001 	}
4002 
4003 	return warnings;
4004 }
4005 
4006 static bool is_kasan_insn(struct instruction *insn)
4007 {
4008 	return (insn->type == INSN_CALL &&
4009 		!strcmp(insn_call_dest(insn)->name, "__asan_handle_no_return"));
4010 }
4011 
4012 static bool is_ubsan_insn(struct instruction *insn)
4013 {
4014 	return (insn->type == INSN_CALL &&
4015 		!strcmp(insn_call_dest(insn)->name,
4016 			"__ubsan_handle_builtin_unreachable"));
4017 }
4018 
4019 static bool ignore_unreachable_insn(struct objtool_file *file, struct instruction *insn)
4020 {
4021 	int i;
4022 	struct instruction *prev_insn;
4023 
4024 	if (insn->ignore || insn->type == INSN_NOP || insn->type == INSN_TRAP)
4025 		return true;
4026 
4027 	/*
4028 	 * Ignore alternative replacement instructions.  This can happen
4029 	 * when a whitelisted function uses one of the ALTERNATIVE macros.
4030 	 */
4031 	if (!strcmp(insn->sec->name, ".altinstr_replacement") ||
4032 	    !strcmp(insn->sec->name, ".altinstr_aux"))
4033 		return true;
4034 
4035 	/*
4036 	 * Whole archive runs might encounter dead code from weak symbols.
4037 	 * This is where the linker will have dropped the weak symbol in
4038 	 * favour of a regular symbol, but leaves the code in place.
4039 	 *
4040 	 * In this case we'll find a piece of code (whole function) that is not
4041 	 * covered by a !section symbol. Ignore them.
4042 	 */
4043 	if (opts.link && !insn_func(insn)) {
4044 		int size = find_symbol_hole_containing(insn->sec, insn->offset);
4045 		unsigned long end = insn->offset + size;
4046 
4047 		if (!size) /* not a hole */
4048 			return false;
4049 
4050 		if (size < 0) /* hole until the end */
4051 			return true;
4052 
4053 		sec_for_each_insn_continue(file, insn) {
4054 			/*
4055 			 * If we reach a visited instruction at or before the
4056 			 * end of the hole, ignore the unreachable.
4057 			 */
4058 			if (insn->visited)
4059 				return true;
4060 
4061 			if (insn->offset >= end)
4062 				break;
4063 
4064 			/*
4065 			 * If this hole jumps to a .cold function, mark it ignore too.
4066 			 */
4067 			if (insn->jump_dest && insn_func(insn->jump_dest) &&
4068 			    strstr(insn_func(insn->jump_dest)->name, ".cold")) {
4069 				struct instruction *dest = insn->jump_dest;
4070 				func_for_each_insn(file, insn_func(dest), dest)
4071 					dest->ignore = true;
4072 			}
4073 		}
4074 
4075 		return false;
4076 	}
4077 
4078 	if (!insn_func(insn))
4079 		return false;
4080 
4081 	if (insn_func(insn)->static_call_tramp)
4082 		return true;
4083 
4084 	/*
4085 	 * CONFIG_UBSAN_TRAP inserts a UD2 when it sees
4086 	 * __builtin_unreachable().  The BUG() macro has an unreachable() after
4087 	 * the UD2, which causes GCC's undefined trap logic to emit another UD2
4088 	 * (or occasionally a JMP to UD2).
4089 	 *
4090 	 * It may also insert a UD2 after calling a __noreturn function.
4091 	 */
4092 	prev_insn = prev_insn_same_sec(file, insn);
4093 	if (prev_insn->dead_end &&
4094 	    (insn->type == INSN_BUG ||
4095 	     (insn->type == INSN_JUMP_UNCONDITIONAL &&
4096 	      insn->jump_dest && insn->jump_dest->type == INSN_BUG)))
4097 		return true;
4098 
4099 	/*
4100 	 * Check if this (or a subsequent) instruction is related to
4101 	 * CONFIG_UBSAN or CONFIG_KASAN.
4102 	 *
4103 	 * End the search at 5 instructions to avoid going into the weeds.
4104 	 */
4105 	for (i = 0; i < 5; i++) {
4106 
4107 		if (is_kasan_insn(insn) || is_ubsan_insn(insn))
4108 			return true;
4109 
4110 		if (insn->type == INSN_JUMP_UNCONDITIONAL) {
4111 			if (insn->jump_dest &&
4112 			    insn_func(insn->jump_dest) == insn_func(insn)) {
4113 				insn = insn->jump_dest;
4114 				continue;
4115 			}
4116 
4117 			break;
4118 		}
4119 
4120 		if (insn->offset + insn->len >= insn_func(insn)->offset + insn_func(insn)->len)
4121 			break;
4122 
4123 		insn = next_insn_same_sec(file, insn);
4124 	}
4125 
4126 	return false;
4127 }
4128 
4129 static int add_prefix_symbol(struct objtool_file *file, struct symbol *func)
4130 {
4131 	struct instruction *insn, *prev;
4132 	struct cfi_state *cfi;
4133 
4134 	insn = find_insn(file, func->sec, func->offset);
4135 	if (!insn)
4136 		return -1;
4137 
4138 	for (prev = prev_insn_same_sec(file, insn);
4139 	     prev;
4140 	     prev = prev_insn_same_sec(file, prev)) {
4141 		u64 offset;
4142 
4143 		if (prev->type != INSN_NOP)
4144 			return -1;
4145 
4146 		offset = func->offset - prev->offset;
4147 
4148 		if (offset > opts.prefix)
4149 			return -1;
4150 
4151 		if (offset < opts.prefix)
4152 			continue;
4153 
4154 		elf_create_prefix_symbol(file->elf, func, opts.prefix);
4155 		break;
4156 	}
4157 
4158 	if (!prev)
4159 		return -1;
4160 
4161 	if (!insn->cfi) {
4162 		/*
4163 		 * This can happen if stack validation isn't enabled or the
4164 		 * function is annotated with STACK_FRAME_NON_STANDARD.
4165 		 */
4166 		return 0;
4167 	}
4168 
4169 	/* Propagate insn->cfi to the prefix code */
4170 	cfi = cfi_hash_find_or_add(insn->cfi);
4171 	for (; prev != insn; prev = next_insn_same_sec(file, prev))
4172 		prev->cfi = cfi;
4173 
4174 	return 0;
4175 }
4176 
4177 static int add_prefix_symbols(struct objtool_file *file)
4178 {
4179 	struct section *sec;
4180 	struct symbol *func;
4181 	int warnings = 0;
4182 
4183 	for_each_sec(file, sec) {
4184 		if (!(sec->sh.sh_flags & SHF_EXECINSTR))
4185 			continue;
4186 
4187 		sec_for_each_sym(sec, func) {
4188 			if (func->type != STT_FUNC)
4189 				continue;
4190 
4191 			add_prefix_symbol(file, func);
4192 		}
4193 	}
4194 
4195 	return warnings;
4196 }
4197 
4198 static int validate_symbol(struct objtool_file *file, struct section *sec,
4199 			   struct symbol *sym, struct insn_state *state)
4200 {
4201 	struct instruction *insn;
4202 	int ret;
4203 
4204 	if (!sym->len) {
4205 		WARN("%s() is missing an ELF size annotation", sym->name);
4206 		return 1;
4207 	}
4208 
4209 	if (sym->pfunc != sym || sym->alias != sym)
4210 		return 0;
4211 
4212 	insn = find_insn(file, sec, sym->offset);
4213 	if (!insn || insn->ignore || insn->visited)
4214 		return 0;
4215 
4216 	state->uaccess = sym->uaccess_safe;
4217 
4218 	ret = validate_branch(file, insn_func(insn), insn, *state);
4219 	if (ret && opts.backtrace)
4220 		BT_FUNC("<=== (sym)", insn);
4221 	return ret;
4222 }
4223 
4224 static int validate_section(struct objtool_file *file, struct section *sec)
4225 {
4226 	struct insn_state state;
4227 	struct symbol *func;
4228 	int warnings = 0;
4229 
4230 	sec_for_each_sym(sec, func) {
4231 		if (func->type != STT_FUNC)
4232 			continue;
4233 
4234 		init_insn_state(file, &state, sec);
4235 		set_func_state(&state.cfi);
4236 
4237 		warnings += validate_symbol(file, sec, func, &state);
4238 	}
4239 
4240 	return warnings;
4241 }
4242 
4243 static int validate_noinstr_sections(struct objtool_file *file)
4244 {
4245 	struct section *sec;
4246 	int warnings = 0;
4247 
4248 	sec = find_section_by_name(file->elf, ".noinstr.text");
4249 	if (sec) {
4250 		warnings += validate_section(file, sec);
4251 		warnings += validate_unwind_hints(file, sec);
4252 	}
4253 
4254 	sec = find_section_by_name(file->elf, ".entry.text");
4255 	if (sec) {
4256 		warnings += validate_section(file, sec);
4257 		warnings += validate_unwind_hints(file, sec);
4258 	}
4259 
4260 	sec = find_section_by_name(file->elf, ".cpuidle.text");
4261 	if (sec) {
4262 		warnings += validate_section(file, sec);
4263 		warnings += validate_unwind_hints(file, sec);
4264 	}
4265 
4266 	return warnings;
4267 }
4268 
4269 static int validate_functions(struct objtool_file *file)
4270 {
4271 	struct section *sec;
4272 	int warnings = 0;
4273 
4274 	for_each_sec(file, sec) {
4275 		if (!(sec->sh.sh_flags & SHF_EXECINSTR))
4276 			continue;
4277 
4278 		warnings += validate_section(file, sec);
4279 	}
4280 
4281 	return warnings;
4282 }
4283 
4284 static void mark_endbr_used(struct instruction *insn)
4285 {
4286 	if (!list_empty(&insn->call_node))
4287 		list_del_init(&insn->call_node);
4288 }
4289 
4290 static bool noendbr_range(struct objtool_file *file, struct instruction *insn)
4291 {
4292 	struct symbol *sym = find_symbol_containing(insn->sec, insn->offset-1);
4293 	struct instruction *first;
4294 
4295 	if (!sym)
4296 		return false;
4297 
4298 	first = find_insn(file, sym->sec, sym->offset);
4299 	if (!first)
4300 		return false;
4301 
4302 	if (first->type != INSN_ENDBR && !first->noendbr)
4303 		return false;
4304 
4305 	return insn->offset == sym->offset + sym->len;
4306 }
4307 
4308 static int validate_ibt_insn(struct objtool_file *file, struct instruction *insn)
4309 {
4310 	struct instruction *dest;
4311 	struct reloc *reloc;
4312 	unsigned long off;
4313 	int warnings = 0;
4314 
4315 	/*
4316 	 * Looking for function pointer load relocations.  Ignore
4317 	 * direct/indirect branches:
4318 	 */
4319 	switch (insn->type) {
4320 	case INSN_CALL:
4321 	case INSN_CALL_DYNAMIC:
4322 	case INSN_JUMP_CONDITIONAL:
4323 	case INSN_JUMP_UNCONDITIONAL:
4324 	case INSN_JUMP_DYNAMIC:
4325 	case INSN_JUMP_DYNAMIC_CONDITIONAL:
4326 	case INSN_RETURN:
4327 	case INSN_NOP:
4328 		return 0;
4329 	default:
4330 		break;
4331 	}
4332 
4333 	for (reloc = insn_reloc(file, insn);
4334 	     reloc;
4335 	     reloc = find_reloc_by_dest_range(file->elf, insn->sec,
4336 					      reloc->offset + 1,
4337 					      (insn->offset + insn->len) - (reloc->offset + 1))) {
4338 
4339 		/*
4340 		 * static_call_update() references the trampoline, which
4341 		 * doesn't have (or need) ENDBR.  Skip warning in that case.
4342 		 */
4343 		if (reloc->sym->static_call_tramp)
4344 			continue;
4345 
4346 		off = reloc->sym->offset;
4347 		if (reloc->type == R_X86_64_PC32 || reloc->type == R_X86_64_PLT32)
4348 			off += arch_dest_reloc_offset(reloc->addend);
4349 		else
4350 			off += reloc->addend;
4351 
4352 		dest = find_insn(file, reloc->sym->sec, off);
4353 		if (!dest)
4354 			continue;
4355 
4356 		if (dest->type == INSN_ENDBR) {
4357 			mark_endbr_used(dest);
4358 			continue;
4359 		}
4360 
4361 		if (insn_func(dest) && insn_func(dest) == insn_func(insn)) {
4362 			/*
4363 			 * Anything from->to self is either _THIS_IP_ or
4364 			 * IRET-to-self.
4365 			 *
4366 			 * There is no sane way to annotate _THIS_IP_ since the
4367 			 * compiler treats the relocation as a constant and is
4368 			 * happy to fold in offsets, skewing any annotation we
4369 			 * do, leading to vast amounts of false-positives.
4370 			 *
4371 			 * There's also compiler generated _THIS_IP_ through
4372 			 * KCOV and such which we have no hope of annotating.
4373 			 *
4374 			 * As such, blanket accept self-references without
4375 			 * issue.
4376 			 */
4377 			continue;
4378 		}
4379 
4380 		/*
4381 		 * Accept anything ANNOTATE_NOENDBR.
4382 		 */
4383 		if (dest->noendbr)
4384 			continue;
4385 
4386 		/*
4387 		 * Accept if this is the instruction after a symbol
4388 		 * that is (no)endbr -- typical code-range usage.
4389 		 */
4390 		if (noendbr_range(file, dest))
4391 			continue;
4392 
4393 		WARN_INSN(insn, "relocation to !ENDBR: %s", offstr(dest->sec, dest->offset));
4394 
4395 		warnings++;
4396 	}
4397 
4398 	return warnings;
4399 }
4400 
4401 static int validate_ibt_data_reloc(struct objtool_file *file,
4402 				   struct reloc *reloc)
4403 {
4404 	struct instruction *dest;
4405 
4406 	dest = find_insn(file, reloc->sym->sec,
4407 			 reloc->sym->offset + reloc->addend);
4408 	if (!dest)
4409 		return 0;
4410 
4411 	if (dest->type == INSN_ENDBR) {
4412 		mark_endbr_used(dest);
4413 		return 0;
4414 	}
4415 
4416 	if (dest->noendbr)
4417 		return 0;
4418 
4419 	WARN_FUNC("data relocation to !ENDBR: %s",
4420 		  reloc->sec->base, reloc->offset,
4421 		  offstr(dest->sec, dest->offset));
4422 
4423 	return 1;
4424 }
4425 
4426 /*
4427  * Validate IBT rules and remove used ENDBR instructions from the seal list.
4428  * Unused ENDBR instructions will be annotated for sealing (i.e., replaced with
4429  * NOPs) later, in create_ibt_endbr_seal_sections().
4430  */
4431 static int validate_ibt(struct objtool_file *file)
4432 {
4433 	struct section *sec;
4434 	struct reloc *reloc;
4435 	struct instruction *insn;
4436 	int warnings = 0;
4437 
4438 	for_each_insn(file, insn)
4439 		warnings += validate_ibt_insn(file, insn);
4440 
4441 	for_each_sec(file, sec) {
4442 
4443 		/* Already done by validate_ibt_insn() */
4444 		if (sec->sh.sh_flags & SHF_EXECINSTR)
4445 			continue;
4446 
4447 		if (!sec->reloc)
4448 			continue;
4449 
4450 		/*
4451 		 * These sections can reference text addresses, but not with
4452 		 * the intent to indirect branch to them.
4453 		 */
4454 		if ((!strncmp(sec->name, ".discard", 8) &&
4455 		     strcmp(sec->name, ".discard.ibt_endbr_noseal"))	||
4456 		    !strncmp(sec->name, ".debug", 6)			||
4457 		    !strcmp(sec->name, ".altinstructions")		||
4458 		    !strcmp(sec->name, ".ibt_endbr_seal")		||
4459 		    !strcmp(sec->name, ".orc_unwind_ip")		||
4460 		    !strcmp(sec->name, ".parainstructions")		||
4461 		    !strcmp(sec->name, ".retpoline_sites")		||
4462 		    !strcmp(sec->name, ".smp_locks")			||
4463 		    !strcmp(sec->name, ".static_call_sites")		||
4464 		    !strcmp(sec->name, "_error_injection_whitelist")	||
4465 		    !strcmp(sec->name, "_kprobe_blacklist")		||
4466 		    !strcmp(sec->name, "__bug_table")			||
4467 		    !strcmp(sec->name, "__ex_table")			||
4468 		    !strcmp(sec->name, "__jump_table")			||
4469 		    !strcmp(sec->name, "__mcount_loc")			||
4470 		    !strcmp(sec->name, ".kcfi_traps")			||
4471 		    strstr(sec->name, "__patchable_function_entries"))
4472 			continue;
4473 
4474 		list_for_each_entry(reloc, &sec->reloc->reloc_list, list)
4475 			warnings += validate_ibt_data_reloc(file, reloc);
4476 	}
4477 
4478 	return warnings;
4479 }
4480 
4481 static int validate_sls(struct objtool_file *file)
4482 {
4483 	struct instruction *insn, *next_insn;
4484 	int warnings = 0;
4485 
4486 	for_each_insn(file, insn) {
4487 		next_insn = next_insn_same_sec(file, insn);
4488 
4489 		if (insn->retpoline_safe)
4490 			continue;
4491 
4492 		switch (insn->type) {
4493 		case INSN_RETURN:
4494 			if (!next_insn || next_insn->type != INSN_TRAP) {
4495 				WARN_INSN(insn, "missing int3 after ret");
4496 				warnings++;
4497 			}
4498 
4499 			break;
4500 		case INSN_JUMP_DYNAMIC:
4501 			if (!next_insn || next_insn->type != INSN_TRAP) {
4502 				WARN_INSN(insn, "missing int3 after indirect jump");
4503 				warnings++;
4504 			}
4505 			break;
4506 		default:
4507 			break;
4508 		}
4509 	}
4510 
4511 	return warnings;
4512 }
4513 
4514 static int validate_reachable_instructions(struct objtool_file *file)
4515 {
4516 	struct instruction *insn;
4517 
4518 	if (file->ignore_unreachables)
4519 		return 0;
4520 
4521 	for_each_insn(file, insn) {
4522 		if (insn->visited || ignore_unreachable_insn(file, insn))
4523 			continue;
4524 
4525 		WARN_INSN(insn, "unreachable instruction");
4526 		return 1;
4527 	}
4528 
4529 	return 0;
4530 }
4531 
4532 int check(struct objtool_file *file)
4533 {
4534 	int ret, warnings = 0;
4535 
4536 	arch_initial_func_cfi_state(&initial_func_cfi);
4537 	init_cfi_state(&init_cfi);
4538 	init_cfi_state(&func_cfi);
4539 	set_func_state(&func_cfi);
4540 
4541 	if (!cfi_hash_alloc(1UL << (file->elf->symbol_bits - 3)))
4542 		goto out;
4543 
4544 	cfi_hash_add(&init_cfi);
4545 	cfi_hash_add(&func_cfi);
4546 
4547 	ret = decode_sections(file);
4548 	if (ret < 0)
4549 		goto out;
4550 
4551 	warnings += ret;
4552 
4553 	if (!nr_insns)
4554 		goto out;
4555 
4556 	if (opts.retpoline) {
4557 		ret = validate_retpoline(file);
4558 		if (ret < 0)
4559 			return ret;
4560 		warnings += ret;
4561 	}
4562 
4563 	if (opts.stackval || opts.orc || opts.uaccess) {
4564 		ret = validate_functions(file);
4565 		if (ret < 0)
4566 			goto out;
4567 		warnings += ret;
4568 
4569 		ret = validate_unwind_hints(file, NULL);
4570 		if (ret < 0)
4571 			goto out;
4572 		warnings += ret;
4573 
4574 		if (!warnings) {
4575 			ret = validate_reachable_instructions(file);
4576 			if (ret < 0)
4577 				goto out;
4578 			warnings += ret;
4579 		}
4580 
4581 	} else if (opts.noinstr) {
4582 		ret = validate_noinstr_sections(file);
4583 		if (ret < 0)
4584 			goto out;
4585 		warnings += ret;
4586 	}
4587 
4588 	if (opts.unret) {
4589 		/*
4590 		 * Must be after validate_branch() and friends, it plays
4591 		 * further games with insn->visited.
4592 		 */
4593 		ret = validate_unrets(file);
4594 		if (ret < 0)
4595 			return ret;
4596 		warnings += ret;
4597 	}
4598 
4599 	if (opts.ibt) {
4600 		ret = validate_ibt(file);
4601 		if (ret < 0)
4602 			goto out;
4603 		warnings += ret;
4604 	}
4605 
4606 	if (opts.sls) {
4607 		ret = validate_sls(file);
4608 		if (ret < 0)
4609 			goto out;
4610 		warnings += ret;
4611 	}
4612 
4613 	if (opts.static_call) {
4614 		ret = create_static_call_sections(file);
4615 		if (ret < 0)
4616 			goto out;
4617 		warnings += ret;
4618 	}
4619 
4620 	if (opts.retpoline) {
4621 		ret = create_retpoline_sites_sections(file);
4622 		if (ret < 0)
4623 			goto out;
4624 		warnings += ret;
4625 	}
4626 
4627 	if (opts.cfi) {
4628 		ret = create_cfi_sections(file);
4629 		if (ret < 0)
4630 			goto out;
4631 		warnings += ret;
4632 	}
4633 
4634 	if (opts.rethunk) {
4635 		ret = create_return_sites_sections(file);
4636 		if (ret < 0)
4637 			goto out;
4638 		warnings += ret;
4639 
4640 		if (opts.hack_skylake) {
4641 			ret = create_direct_call_sections(file);
4642 			if (ret < 0)
4643 				goto out;
4644 			warnings += ret;
4645 		}
4646 	}
4647 
4648 	if (opts.mcount) {
4649 		ret = create_mcount_loc_sections(file);
4650 		if (ret < 0)
4651 			goto out;
4652 		warnings += ret;
4653 	}
4654 
4655 	if (opts.prefix) {
4656 		ret = add_prefix_symbols(file);
4657 		if (ret < 0)
4658 			return ret;
4659 		warnings += ret;
4660 	}
4661 
4662 	if (opts.ibt) {
4663 		ret = create_ibt_endbr_seal_sections(file);
4664 		if (ret < 0)
4665 			goto out;
4666 		warnings += ret;
4667 	}
4668 
4669 	if (opts.orc && nr_insns) {
4670 		ret = orc_create(file);
4671 		if (ret < 0)
4672 			goto out;
4673 		warnings += ret;
4674 	}
4675 
4676 
4677 	if (opts.stats) {
4678 		printf("nr_insns_visited: %ld\n", nr_insns_visited);
4679 		printf("nr_cfi: %ld\n", nr_cfi);
4680 		printf("nr_cfi_reused: %ld\n", nr_cfi_reused);
4681 		printf("nr_cfi_cache: %ld\n", nr_cfi_cache);
4682 	}
4683 
4684 out:
4685 	/*
4686 	 *  For now, don't fail the kernel build on fatal warnings.  These
4687 	 *  errors are still fairly common due to the growing matrix of
4688 	 *  supported toolchains and their recent pace of change.
4689 	 */
4690 	return 0;
4691 }
4692