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