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