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