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