xref: /linux/tools/objtool/check.c (revision a5b6612332622d809e5c0a4f5637eef92dc06c06)
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 struct reloc *insn_reloc(struct objtool_file *file, struct instruction *insn)
1350 {
1351 	struct reloc *reloc;
1352 
1353 	if (!file || insn->no_reloc || insn->fake)
1354 		return NULL;
1355 
1356 	reloc = find_reloc_by_dest_range(file->elf, insn->sec,
1357 					 insn->offset, insn->len);
1358 	if (!reloc) {
1359 		insn->no_reloc = 1;
1360 		return NULL;
1361 	}
1362 
1363 	return reloc;
1364 }
1365 
1366 static void remove_insn_ops(struct instruction *insn)
1367 {
1368 	struct stack_op *op, *next;
1369 
1370 	for (op = insn->stack_ops; op; op = next) {
1371 		next = op->next;
1372 		free(op);
1373 	}
1374 	insn->stack_ops = NULL;
1375 }
1376 
1377 static int annotate_call_site(struct objtool_file *file,
1378 			       struct instruction *insn, bool sibling)
1379 {
1380 	struct reloc *reloc = insn_reloc(file, insn);
1381 	struct symbol *sym = insn_call_dest(insn);
1382 
1383 	if (!sym)
1384 		sym = reloc->sym;
1385 
1386 	if (sym->static_call_tramp) {
1387 		list_add_tail(&insn->call_node, &file->static_call_list);
1388 		return 0;
1389 	}
1390 
1391 	if (sym->retpoline_thunk) {
1392 		list_add_tail(&insn->call_node, &file->retpoline_call_list);
1393 		return 0;
1394 	}
1395 
1396 	/*
1397 	 * Many compilers cannot disable KCOV or sanitizer calls with a function
1398 	 * attribute so they need a little help, NOP out any such calls from
1399 	 * noinstr text.
1400 	 */
1401 	if (opts.hack_noinstr && insn->sec->noinstr && sym->profiling_func) {
1402 		if (reloc)
1403 			set_reloc_type(file->elf, reloc, R_NONE);
1404 
1405 		if (elf_write_insn(file->elf, insn->sec,
1406 				   insn->offset, insn->len,
1407 				   sibling ? arch_ret_insn(insn->len)
1408 					   : arch_nop_insn(insn->len))) {
1409 			return -1;
1410 		}
1411 
1412 		insn->type = sibling ? INSN_RETURN : INSN_NOP;
1413 
1414 		if (sibling) {
1415 			/*
1416 			 * We've replaced the tail-call JMP insn by two new
1417 			 * insn: RET; INT3, except we only have a single struct
1418 			 * insn here. Mark it retpoline_safe to avoid the SLS
1419 			 * warning, instead of adding another insn.
1420 			 */
1421 			insn->retpoline_safe = true;
1422 		}
1423 
1424 		return 0;
1425 	}
1426 
1427 	if (opts.mcount && sym->fentry) {
1428 		if (sibling)
1429 			WARN_INSN(insn, "tail call to __fentry__ !?!?");
1430 		if (opts.mnop) {
1431 			if (reloc)
1432 				set_reloc_type(file->elf, reloc, R_NONE);
1433 
1434 			if (elf_write_insn(file->elf, insn->sec,
1435 					   insn->offset, insn->len,
1436 					   arch_nop_insn(insn->len))) {
1437 				return -1;
1438 			}
1439 
1440 			insn->type = INSN_NOP;
1441 		}
1442 
1443 		list_add_tail(&insn->call_node, &file->mcount_loc_list);
1444 		return 0;
1445 	}
1446 
1447 	if (insn->type == INSN_CALL && !insn->sec->init &&
1448 	    !insn->_call_dest->embedded_insn)
1449 		list_add_tail(&insn->call_node, &file->call_list);
1450 
1451 	if (!sibling && dead_end_function(file, sym))
1452 		insn->dead_end = true;
1453 
1454 	return 0;
1455 }
1456 
1457 static int add_call_dest(struct objtool_file *file, struct instruction *insn,
1458 			  struct symbol *dest, bool sibling)
1459 {
1460 	insn->_call_dest = dest;
1461 	if (!dest)
1462 		return 0;
1463 
1464 	/*
1465 	 * Whatever stack impact regular CALLs have, should be undone
1466 	 * by the RETURN of the called function.
1467 	 *
1468 	 * Annotated intra-function calls retain the stack_ops but
1469 	 * are converted to JUMP, see read_intra_function_calls().
1470 	 */
1471 	remove_insn_ops(insn);
1472 
1473 	return annotate_call_site(file, insn, sibling);
1474 }
1475 
1476 static int add_retpoline_call(struct objtool_file *file, struct instruction *insn)
1477 {
1478 	/*
1479 	 * Retpoline calls/jumps are really dynamic calls/jumps in disguise,
1480 	 * so convert them accordingly.
1481 	 */
1482 	switch (insn->type) {
1483 	case INSN_CALL:
1484 		insn->type = INSN_CALL_DYNAMIC;
1485 		break;
1486 	case INSN_JUMP_UNCONDITIONAL:
1487 		insn->type = INSN_JUMP_DYNAMIC;
1488 		break;
1489 	case INSN_JUMP_CONDITIONAL:
1490 		insn->type = INSN_JUMP_DYNAMIC_CONDITIONAL;
1491 		break;
1492 	default:
1493 		return 0;
1494 	}
1495 
1496 	insn->retpoline_safe = true;
1497 
1498 	/*
1499 	 * Whatever stack impact regular CALLs have, should be undone
1500 	 * by the RETURN of the called function.
1501 	 *
1502 	 * Annotated intra-function calls retain the stack_ops but
1503 	 * are converted to JUMP, see read_intra_function_calls().
1504 	 */
1505 	remove_insn_ops(insn);
1506 
1507 	return annotate_call_site(file, insn, false);
1508 }
1509 
1510 static void add_return_call(struct objtool_file *file, struct instruction *insn, bool add)
1511 {
1512 	/*
1513 	 * Return thunk tail calls are really just returns in disguise,
1514 	 * so convert them accordingly.
1515 	 */
1516 	insn->type = INSN_RETURN;
1517 	insn->retpoline_safe = true;
1518 
1519 	if (add)
1520 		list_add_tail(&insn->call_node, &file->return_thunk_list);
1521 }
1522 
1523 static bool is_first_func_insn(struct objtool_file *file,
1524 			       struct instruction *insn)
1525 {
1526 	struct symbol *func = insn_func(insn);
1527 
1528 	if (!func)
1529 		return false;
1530 
1531 	if (insn->offset == func->offset)
1532 		return true;
1533 
1534 	/* Allow direct CALL/JMP past ENDBR */
1535 	if (opts.ibt) {
1536 		struct instruction *prev = prev_insn_same_sym(file, insn);
1537 
1538 		if (prev && prev->type == INSN_ENDBR &&
1539 		    insn->offset == func->offset + prev->len)
1540 			return true;
1541 	}
1542 
1543 	return false;
1544 }
1545 
1546 /*
1547  * Find the destination instructions for all jumps.
1548  */
1549 static int add_jump_destinations(struct objtool_file *file)
1550 {
1551 	struct instruction *insn;
1552 	struct reloc *reloc;
1553 
1554 	for_each_insn(file, insn) {
1555 		struct symbol *func = insn_func(insn);
1556 		struct instruction *dest_insn;
1557 		struct section *dest_sec;
1558 		struct symbol *dest_sym;
1559 		unsigned long dest_off;
1560 
1561 		if (!is_static_jump(insn))
1562 			continue;
1563 
1564 		if (insn->jump_dest) {
1565 			/*
1566 			 * handle_group_alt() may have previously set
1567 			 * 'jump_dest' for some alternatives.
1568 			 */
1569 			continue;
1570 		}
1571 
1572 		reloc = insn_reloc(file, insn);
1573 		if (!reloc) {
1574 			dest_sec = insn->sec;
1575 			dest_off = arch_jump_destination(insn);
1576 			dest_sym = dest_sec->sym;
1577 		} else {
1578 			dest_sym = reloc->sym;
1579 			if (is_undef_sym(dest_sym)) {
1580 				if (dest_sym->retpoline_thunk) {
1581 					if (add_retpoline_call(file, insn))
1582 						return -1;
1583 					continue;
1584 				}
1585 
1586 				if (dest_sym->return_thunk) {
1587 					add_return_call(file, insn, true);
1588 					continue;
1589 				}
1590 
1591 				/* External symbol */
1592 				if (func) {
1593 					/* External sibling call */
1594 					if (add_call_dest(file, insn, dest_sym, true))
1595 						return -1;
1596 					continue;
1597 				}
1598 
1599 				/* Non-func asm code jumping to external symbol */
1600 				continue;
1601 			}
1602 
1603 			dest_sec = dest_sym->sec;
1604 			dest_off = dest_sym->offset + arch_insn_adjusted_addend(insn, reloc);
1605 		}
1606 
1607 		dest_insn = find_insn(file, dest_sec, dest_off);
1608 		if (!dest_insn) {
1609 			struct symbol *sym = find_symbol_by_offset(dest_sec, dest_off);
1610 
1611 			/*
1612 			 * retbleed_untrain_ret() jumps to
1613 			 * __x86_return_thunk(), but objtool can't find
1614 			 * the thunk's starting RET instruction,
1615 			 * because the RET is also in the middle of
1616 			 * another instruction.  Objtool only knows
1617 			 * about the outer instruction.
1618 			 */
1619 			if (sym && sym->embedded_insn) {
1620 				add_return_call(file, insn, false);
1621 				continue;
1622 			}
1623 
1624 			/*
1625 			 * GCOV/KCOV dead code can jump to the end of
1626 			 * the function/section.
1627 			 */
1628 			if (file->ignore_unreachables && func &&
1629 			    dest_sec == insn->sec &&
1630 			    dest_off == func->offset + func->len)
1631 				continue;
1632 
1633 			ERROR_INSN(insn, "can't find jump dest instruction at %s",
1634 				   offstr(dest_sec, dest_off));
1635 			return -1;
1636 		}
1637 
1638 		if (!dest_sym || is_sec_sym(dest_sym)) {
1639 			dest_sym = dest_insn->sym;
1640 			if (!dest_sym)
1641 				goto set_jump_dest;
1642 		}
1643 
1644 		if (dest_sym->retpoline_thunk && dest_insn->offset == dest_sym->offset) {
1645 			if (add_retpoline_call(file, insn))
1646 				return -1;
1647 			continue;
1648 		}
1649 
1650 		if (dest_sym->return_thunk && dest_insn->offset == dest_sym->offset) {
1651 			add_return_call(file, insn, true);
1652 			continue;
1653 		}
1654 
1655 		if (!insn->sym || insn->sym->pfunc == dest_sym->pfunc)
1656 			goto set_jump_dest;
1657 
1658 		/*
1659 		 * Internal cross-function jump.
1660 		 */
1661 
1662 		if (is_first_func_insn(file, dest_insn)) {
1663 			/* Internal sibling call */
1664 			if (add_call_dest(file, insn, dest_sym, true))
1665 				return -1;
1666 			continue;
1667 		}
1668 
1669 set_jump_dest:
1670 		insn->jump_dest = dest_insn;
1671 	}
1672 
1673 	return 0;
1674 }
1675 
1676 static struct symbol *find_call_destination(struct section *sec, unsigned long offset)
1677 {
1678 	struct symbol *call_dest;
1679 
1680 	call_dest = find_func_by_offset(sec, offset);
1681 	if (!call_dest)
1682 		call_dest = find_symbol_by_offset(sec, offset);
1683 
1684 	return call_dest;
1685 }
1686 
1687 /*
1688  * Find the destination instructions for all calls.
1689  */
1690 static int add_call_destinations(struct objtool_file *file)
1691 {
1692 	struct instruction *insn;
1693 	unsigned long dest_off;
1694 	struct symbol *dest;
1695 	struct reloc *reloc;
1696 
1697 	for_each_insn(file, insn) {
1698 		struct symbol *func = insn_func(insn);
1699 		if (insn->type != INSN_CALL)
1700 			continue;
1701 
1702 		reloc = insn_reloc(file, insn);
1703 		if (!reloc) {
1704 			dest_off = arch_jump_destination(insn);
1705 			dest = find_call_destination(insn->sec, dest_off);
1706 
1707 			if (add_call_dest(file, insn, dest, false))
1708 				return -1;
1709 
1710 			if (func && func->ignore)
1711 				continue;
1712 
1713 			if (!insn_call_dest(insn)) {
1714 				ERROR_INSN(insn, "unannotated intra-function call");
1715 				return -1;
1716 			}
1717 
1718 			if (func && !is_func_sym(insn_call_dest(insn))) {
1719 				ERROR_INSN(insn, "unsupported call to non-function");
1720 				return -1;
1721 			}
1722 
1723 		} else if (is_sec_sym(reloc->sym)) {
1724 			dest_off = arch_insn_adjusted_addend(insn, reloc);
1725 			dest = find_call_destination(reloc->sym->sec, dest_off);
1726 			if (!dest) {
1727 				ERROR_INSN(insn, "can't find call dest symbol at %s+0x%lx",
1728 					   reloc->sym->sec->name, dest_off);
1729 				return -1;
1730 			}
1731 
1732 			if (add_call_dest(file, insn, dest, false))
1733 				return -1;
1734 
1735 		} else if (reloc->sym->retpoline_thunk) {
1736 			if (add_retpoline_call(file, insn))
1737 				return -1;
1738 
1739 		} else {
1740 			if (add_call_dest(file, insn, reloc->sym, false))
1741 				return -1;
1742 		}
1743 	}
1744 
1745 	return 0;
1746 }
1747 
1748 /*
1749  * The .alternatives section requires some extra special care over and above
1750  * other special sections because alternatives are patched in place.
1751  */
1752 static int handle_group_alt(struct objtool_file *file,
1753 			    struct special_alt *special_alt,
1754 			    struct instruction *orig_insn,
1755 			    struct instruction **new_insn)
1756 {
1757 	struct instruction *last_new_insn = NULL, *insn, *nop = NULL;
1758 	struct alt_group *orig_alt_group, *new_alt_group;
1759 	unsigned long dest_off;
1760 
1761 	orig_alt_group = orig_insn->alt_group;
1762 	if (!orig_alt_group) {
1763 		struct instruction *last_orig_insn = NULL;
1764 
1765 		orig_alt_group = calloc(1, sizeof(*orig_alt_group));
1766 		if (!orig_alt_group) {
1767 			ERROR_GLIBC("calloc");
1768 			return -1;
1769 		}
1770 		orig_alt_group->cfi = calloc(special_alt->orig_len,
1771 					     sizeof(struct cfi_state *));
1772 		if (!orig_alt_group->cfi) {
1773 			ERROR_GLIBC("calloc");
1774 			return -1;
1775 		}
1776 
1777 		insn = orig_insn;
1778 		sec_for_each_insn_from(file, insn) {
1779 			if (insn->offset >= special_alt->orig_off + special_alt->orig_len)
1780 				break;
1781 
1782 			insn->alt_group = orig_alt_group;
1783 			last_orig_insn = insn;
1784 		}
1785 		orig_alt_group->orig_group = NULL;
1786 		orig_alt_group->first_insn = orig_insn;
1787 		orig_alt_group->last_insn = last_orig_insn;
1788 		orig_alt_group->nop = NULL;
1789 		orig_alt_group->ignore = orig_insn->ignore_alts;
1790 		orig_alt_group->feature = 0;
1791 	} else {
1792 		if (orig_alt_group->last_insn->offset + orig_alt_group->last_insn->len -
1793 		    orig_alt_group->first_insn->offset != special_alt->orig_len) {
1794 			ERROR_INSN(orig_insn, "weirdly overlapping alternative! %ld != %d",
1795 				   orig_alt_group->last_insn->offset +
1796 				   orig_alt_group->last_insn->len -
1797 				   orig_alt_group->first_insn->offset,
1798 				   special_alt->orig_len);
1799 			return -1;
1800 		}
1801 	}
1802 
1803 	new_alt_group = calloc(1, sizeof(*new_alt_group));
1804 	if (!new_alt_group) {
1805 		ERROR_GLIBC("calloc");
1806 		return -1;
1807 	}
1808 
1809 	if (special_alt->new_len < special_alt->orig_len) {
1810 		/*
1811 		 * Insert a fake nop at the end to make the replacement
1812 		 * alt_group the same size as the original.  This is needed to
1813 		 * allow propagate_alt_cfi() to do its magic.  When the last
1814 		 * instruction affects the stack, the instruction after it (the
1815 		 * nop) will propagate the new state to the shared CFI array.
1816 		 */
1817 		nop = calloc(1, sizeof(*nop));
1818 		if (!nop) {
1819 			ERROR_GLIBC("calloc");
1820 			return -1;
1821 		}
1822 		memset(nop, 0, sizeof(*nop));
1823 
1824 		nop->sec = special_alt->new_sec;
1825 		nop->offset = special_alt->new_off + special_alt->new_len;
1826 		nop->len = special_alt->orig_len - special_alt->new_len;
1827 		nop->type = INSN_NOP;
1828 		nop->sym = orig_insn->sym;
1829 		nop->alt_group = new_alt_group;
1830 		nop->fake = 1;
1831 	}
1832 
1833 	if (!special_alt->new_len) {
1834 		*new_insn = nop;
1835 		goto end;
1836 	}
1837 
1838 	insn = *new_insn;
1839 	sec_for_each_insn_from(file, insn) {
1840 		struct reloc *alt_reloc;
1841 
1842 		if (insn->offset >= special_alt->new_off + special_alt->new_len)
1843 			break;
1844 
1845 		last_new_insn = insn;
1846 
1847 		insn->sym = orig_insn->sym;
1848 		insn->alt_group = new_alt_group;
1849 
1850 		/*
1851 		 * Since alternative replacement code is copy/pasted by the
1852 		 * kernel after applying relocations, generally such code can't
1853 		 * have relative-address relocation references to outside the
1854 		 * .altinstr_replacement section, unless the arch's
1855 		 * alternatives code can adjust the relative offsets
1856 		 * accordingly.
1857 		 */
1858 		alt_reloc = insn_reloc(file, insn);
1859 		if (alt_reloc && arch_pc_relative_reloc(alt_reloc) &&
1860 		    !arch_support_alt_relocation(special_alt, insn, alt_reloc)) {
1861 
1862 			ERROR_INSN(insn, "unsupported relocation in alternatives section");
1863 			return -1;
1864 		}
1865 
1866 		if (!is_static_jump(insn))
1867 			continue;
1868 
1869 		if (!insn->immediate)
1870 			continue;
1871 
1872 		dest_off = arch_jump_destination(insn);
1873 		if (dest_off == special_alt->new_off + special_alt->new_len) {
1874 			insn->jump_dest = next_insn_same_sec(file, orig_alt_group->last_insn);
1875 			if (!insn->jump_dest) {
1876 				ERROR_INSN(insn, "can't find alternative jump destination");
1877 				return -1;
1878 			}
1879 		}
1880 	}
1881 
1882 	if (!last_new_insn) {
1883 		ERROR_FUNC(special_alt->new_sec, special_alt->new_off,
1884 			   "can't find last new alternative instruction");
1885 		return -1;
1886 	}
1887 
1888 end:
1889 	new_alt_group->orig_group = orig_alt_group;
1890 	new_alt_group->first_insn = *new_insn;
1891 	new_alt_group->last_insn = last_new_insn;
1892 	new_alt_group->nop = nop;
1893 	new_alt_group->ignore = (*new_insn)->ignore_alts;
1894 	new_alt_group->cfi = orig_alt_group->cfi;
1895 	new_alt_group->feature = special_alt->feature;
1896 	return 0;
1897 }
1898 
1899 /*
1900  * A jump table entry can either convert a nop to a jump or a jump to a nop.
1901  * If the original instruction is a jump, make the alt entry an effective nop
1902  * by just skipping the original instruction.
1903  */
1904 static int handle_jump_alt(struct objtool_file *file,
1905 			   struct special_alt *special_alt,
1906 			   struct instruction *orig_insn,
1907 			   struct instruction **new_insn)
1908 {
1909 	if (orig_insn->type != INSN_JUMP_UNCONDITIONAL &&
1910 	    orig_insn->type != INSN_NOP) {
1911 
1912 		ERROR_INSN(orig_insn, "unsupported instruction at jump label");
1913 		return -1;
1914 	}
1915 
1916 	if (opts.hack_jump_label && special_alt->key_addend & 2) {
1917 		struct reloc *reloc = insn_reloc(file, orig_insn);
1918 
1919 		if (reloc)
1920 			set_reloc_type(file->elf, reloc, R_NONE);
1921 
1922 		if (elf_write_insn(file->elf, orig_insn->sec,
1923 				   orig_insn->offset, orig_insn->len,
1924 				   arch_nop_insn(orig_insn->len))) {
1925 			return -1;
1926 		}
1927 
1928 		orig_insn->type = INSN_NOP;
1929 	}
1930 
1931 	if (orig_insn->type == INSN_NOP) {
1932 		if (orig_insn->len == 2)
1933 			file->jl_nop_short++;
1934 		else
1935 			file->jl_nop_long++;
1936 
1937 		return 0;
1938 	}
1939 
1940 	if (orig_insn->len == 2)
1941 		file->jl_short++;
1942 	else
1943 		file->jl_long++;
1944 
1945 	*new_insn = next_insn_same_sec(file, orig_insn);
1946 	return 0;
1947 }
1948 
1949 /*
1950  * Read all the special sections which have alternate instructions which can be
1951  * patched in or redirected to at runtime.  Each instruction having alternate
1952  * instruction(s) has them added to its insn->alts list, which will be
1953  * traversed in validate_branch().
1954  */
1955 static int add_special_section_alts(struct objtool_file *file)
1956 {
1957 	struct list_head special_alts;
1958 	struct instruction *orig_insn, *new_insn;
1959 	struct special_alt *special_alt, *tmp;
1960 	enum alternative_type alt_type;
1961 	struct alternative *alt;
1962 	struct alternative *a;
1963 
1964 	if (special_get_alts(file->elf, &special_alts))
1965 		return -1;
1966 
1967 	list_for_each_entry_safe(special_alt, tmp, &special_alts, list) {
1968 
1969 		orig_insn = find_insn(file, special_alt->orig_sec,
1970 				      special_alt->orig_off);
1971 		if (!orig_insn) {
1972 			ERROR_FUNC(special_alt->orig_sec, special_alt->orig_off,
1973 				   "special: can't find orig instruction");
1974 			return -1;
1975 		}
1976 
1977 		new_insn = NULL;
1978 		if (!special_alt->group || special_alt->new_len) {
1979 			new_insn = find_insn(file, special_alt->new_sec,
1980 					     special_alt->new_off);
1981 			if (!new_insn) {
1982 				ERROR_FUNC(special_alt->new_sec, special_alt->new_off,
1983 					   "special: can't find new instruction");
1984 				return -1;
1985 			}
1986 		}
1987 
1988 		if (special_alt->group) {
1989 			if (!special_alt->orig_len) {
1990 				ERROR_INSN(orig_insn, "empty alternative entry");
1991 				continue;
1992 			}
1993 
1994 			if (handle_group_alt(file, special_alt, orig_insn, &new_insn))
1995 				return -1;
1996 
1997 			alt_type = ALT_TYPE_INSTRUCTIONS;
1998 
1999 		} else if (special_alt->jump_or_nop) {
2000 			if (handle_jump_alt(file, special_alt, orig_insn, &new_insn))
2001 				return -1;
2002 
2003 			alt_type = ALT_TYPE_JUMP_TABLE;
2004 		} else {
2005 			alt_type = ALT_TYPE_EX_TABLE;
2006 		}
2007 
2008 		alt = calloc(1, sizeof(*alt));
2009 		if (!alt) {
2010 			ERROR_GLIBC("calloc");
2011 			return -1;
2012 		}
2013 
2014 		alt->insn = new_insn;
2015 		alt->type = alt_type;
2016 		alt->next = NULL;
2017 
2018 		/*
2019 		 * Store alternatives in the same order they have been
2020 		 * defined.
2021 		 */
2022 		if (!orig_insn->alts) {
2023 			orig_insn->alts = alt;
2024 		} else {
2025 			for (a = orig_insn->alts; a->next; a = a->next)
2026 				;
2027 			a->next = alt;
2028 		}
2029 
2030 		list_del(&special_alt->list);
2031 		free(special_alt);
2032 	}
2033 
2034 	if (opts.stats) {
2035 		printf("jl\\\tNOP\tJMP\n");
2036 		printf("short:\t%ld\t%ld\n", file->jl_nop_short, file->jl_short);
2037 		printf("long:\t%ld\t%ld\n", file->jl_nop_long, file->jl_long);
2038 	}
2039 
2040 	return 0;
2041 }
2042 
2043 __weak unsigned long arch_jump_table_sym_offset(struct reloc *reloc, struct reloc *table)
2044 {
2045 	return reloc->sym->offset + reloc_addend(reloc);
2046 }
2047 
2048 static int add_jump_table(struct objtool_file *file, struct instruction *insn)
2049 {
2050 	unsigned long table_size = insn_jump_table_size(insn);
2051 	struct symbol *pfunc = insn_func(insn)->pfunc;
2052 	struct reloc *table = insn_jump_table(insn);
2053 	struct instruction *dest_insn;
2054 	unsigned int prev_offset = 0;
2055 	struct reloc *reloc = table;
2056 	struct alternative *alt;
2057 	unsigned long sym_offset;
2058 
2059 	/*
2060 	 * Each @reloc is a switch table relocation which points to the target
2061 	 * instruction.
2062 	 */
2063 	for_each_reloc_from(table->sec, reloc) {
2064 
2065 		/* Check for the end of the table: */
2066 		if (table_size && reloc_offset(reloc) - reloc_offset(table) >= table_size)
2067 			break;
2068 		if (reloc != table && is_jump_table(reloc))
2069 			break;
2070 
2071 		/* Make sure the table entries are consecutive: */
2072 		if (prev_offset && reloc_offset(reloc) != prev_offset + arch_reloc_size(reloc))
2073 			break;
2074 
2075 		sym_offset = arch_jump_table_sym_offset(reloc, table);
2076 
2077 		/* Detect function pointers from contiguous objects: */
2078 		if (reloc->sym->sec == pfunc->sec && sym_offset == pfunc->offset)
2079 			break;
2080 
2081 		/*
2082 		 * Clang sometimes leaves dangling unused jump table entries
2083 		 * which point to the end of the function.  Ignore them.
2084 		 */
2085 		if (reloc->sym->sec == pfunc->sec &&
2086 		    sym_offset == pfunc->offset + pfunc->len)
2087 			goto next;
2088 
2089 		dest_insn = find_insn(file, reloc->sym->sec, sym_offset);
2090 		if (!dest_insn)
2091 			break;
2092 
2093 		/* Make sure the destination is in the same function: */
2094 		if (!insn_func(dest_insn) || insn_func(dest_insn)->pfunc != pfunc)
2095 			break;
2096 
2097 		alt = calloc(1, sizeof(*alt));
2098 		if (!alt) {
2099 			ERROR_GLIBC("calloc");
2100 			return -1;
2101 		}
2102 
2103 		alt->insn = dest_insn;
2104 		alt->next = insn->alts;
2105 		insn->alts = alt;
2106 next:
2107 		prev_offset = reloc_offset(reloc);
2108 	}
2109 
2110 	if (!prev_offset) {
2111 		ERROR_INSN(insn, "can't find switch jump table");
2112 		return -1;
2113 	}
2114 
2115 	return 0;
2116 }
2117 
2118 /*
2119  * find_jump_table() - Given a dynamic jump, find the switch jump table
2120  * associated with it.
2121  */
2122 static void find_jump_table(struct objtool_file *file, struct symbol *func,
2123 			    struct instruction *insn)
2124 {
2125 	struct reloc *table_reloc;
2126 	struct instruction *dest_insn, *orig_insn = insn;
2127 	unsigned long table_size;
2128 	unsigned long sym_offset;
2129 
2130 	/*
2131 	 * Backward search using the @first_jump_src links, these help avoid
2132 	 * much of the 'in between' code. Which avoids us getting confused by
2133 	 * it.
2134 	 */
2135 	for (;
2136 	     insn && insn_func(insn) && insn_func(insn)->pfunc == func;
2137 	     insn = insn->first_jump_src ?: prev_insn_same_sym(file, insn)) {
2138 
2139 		if (insn != orig_insn && insn->type == INSN_JUMP_DYNAMIC)
2140 			break;
2141 
2142 		/* allow small jumps within the range */
2143 		if (insn->type == INSN_JUMP_UNCONDITIONAL &&
2144 		    insn->jump_dest &&
2145 		    (insn->jump_dest->offset <= insn->offset ||
2146 		     insn->jump_dest->offset > orig_insn->offset))
2147 			break;
2148 
2149 		table_reloc = arch_find_switch_table(file, insn, &table_size);
2150 		if (!table_reloc)
2151 			continue;
2152 
2153 		sym_offset = table_reloc->sym->offset + reloc_addend(table_reloc);
2154 
2155 		dest_insn = find_insn(file, table_reloc->sym->sec, sym_offset);
2156 		if (!dest_insn || !insn_func(dest_insn) || insn_func(dest_insn)->pfunc != func)
2157 			continue;
2158 
2159 		set_jump_table(table_reloc);
2160 		orig_insn->_jump_table = table_reloc;
2161 		orig_insn->_jump_table_size = table_size;
2162 
2163 		break;
2164 	}
2165 }
2166 
2167 /*
2168  * First pass: Mark the head of each jump table so that in the next pass,
2169  * we know when a given jump table ends and the next one starts.
2170  */
2171 static void mark_func_jump_tables(struct objtool_file *file,
2172 				    struct symbol *func)
2173 {
2174 	struct instruction *insn, *last = NULL;
2175 
2176 	func_for_each_insn(file, func, insn) {
2177 		if (!last)
2178 			last = insn;
2179 
2180 		/*
2181 		 * Store back-pointers for forward jumps such
2182 		 * that find_jump_table() can back-track using those and
2183 		 * avoid some potentially confusing code.
2184 		 */
2185 		if (insn->jump_dest &&
2186 		    insn->jump_dest->offset > insn->offset &&
2187 		    !insn->jump_dest->first_jump_src) {
2188 
2189 			insn->jump_dest->first_jump_src = insn;
2190 			last = insn->jump_dest;
2191 		}
2192 
2193 		if (insn->type != INSN_JUMP_DYNAMIC)
2194 			continue;
2195 
2196 		find_jump_table(file, func, insn);
2197 	}
2198 }
2199 
2200 static int add_func_jump_tables(struct objtool_file *file,
2201 				  struct symbol *func)
2202 {
2203 	struct instruction *insn;
2204 
2205 	func_for_each_insn(file, func, insn) {
2206 		if (!insn_jump_table(insn))
2207 			continue;
2208 
2209 		if (add_jump_table(file, insn))
2210 			return -1;
2211 	}
2212 
2213 	return 0;
2214 }
2215 
2216 /*
2217  * For some switch statements, gcc generates a jump table in the .rodata
2218  * section which contains a list of addresses within the function to jump to.
2219  * This finds these jump tables and adds them to the insn->alts lists.
2220  */
2221 static int add_jump_table_alts(struct objtool_file *file)
2222 {
2223 	struct symbol *func;
2224 
2225 	if (!file->rodata)
2226 		return 0;
2227 
2228 	for_each_sym(file->elf, func) {
2229 		if (!is_func_sym(func) || is_alias_sym(func))
2230 			continue;
2231 
2232 		mark_func_jump_tables(file, func);
2233 		if (add_func_jump_tables(file, func))
2234 			return -1;
2235 	}
2236 
2237 	return 0;
2238 }
2239 
2240 static void set_func_state(struct cfi_state *state)
2241 {
2242 	state->cfa = initial_func_cfi.cfa;
2243 	memcpy(&state->regs, &initial_func_cfi.regs,
2244 	       CFI_NUM_REGS * sizeof(struct cfi_reg));
2245 	state->stack_size = initial_func_cfi.cfa.offset;
2246 	state->type = UNWIND_HINT_TYPE_CALL;
2247 }
2248 
2249 static int read_unwind_hints(struct objtool_file *file)
2250 {
2251 	struct cfi_state cfi = init_cfi;
2252 	struct section *sec;
2253 	struct unwind_hint *hint;
2254 	struct instruction *insn;
2255 	struct reloc *reloc;
2256 	unsigned long offset;
2257 	int i;
2258 
2259 	sec = find_section_by_name(file->elf, ".discard.unwind_hints");
2260 	if (!sec)
2261 		return 0;
2262 
2263 	if (!sec->rsec) {
2264 		ERROR("missing .rela.discard.unwind_hints section");
2265 		return -1;
2266 	}
2267 
2268 	if (sec_size(sec) % sizeof(struct unwind_hint)) {
2269 		ERROR("struct unwind_hint size mismatch");
2270 		return -1;
2271 	}
2272 
2273 	file->hints = true;
2274 
2275 	for (i = 0; i < sec_size(sec) / sizeof(struct unwind_hint); i++) {
2276 		hint = (struct unwind_hint *)sec->data->d_buf + i;
2277 
2278 		reloc = find_reloc_by_dest(file->elf, sec, i * sizeof(*hint));
2279 		if (!reloc) {
2280 			ERROR("can't find reloc for unwind_hints[%d]", i);
2281 			return -1;
2282 		}
2283 
2284 		offset = reloc->sym->offset + reloc_addend(reloc);
2285 
2286 		insn = find_insn(file, reloc->sym->sec, offset);
2287 		if (!insn) {
2288 			ERROR("can't find insn for unwind_hints[%d]", i);
2289 			return -1;
2290 		}
2291 
2292 		insn->hint = true;
2293 
2294 		if (hint->type == UNWIND_HINT_TYPE_UNDEFINED) {
2295 			insn->cfi = &force_undefined_cfi;
2296 			continue;
2297 		}
2298 
2299 		if (hint->type == UNWIND_HINT_TYPE_SAVE) {
2300 			insn->hint = false;
2301 			insn->save = true;
2302 			continue;
2303 		}
2304 
2305 		if (hint->type == UNWIND_HINT_TYPE_RESTORE) {
2306 			insn->restore = true;
2307 			continue;
2308 		}
2309 
2310 		if (hint->type == UNWIND_HINT_TYPE_REGS_PARTIAL) {
2311 			struct symbol *sym = find_symbol_by_offset(insn->sec, insn->offset);
2312 
2313 			if (sym && is_global_sym(sym)) {
2314 				if (opts.ibt && insn->type != INSN_ENDBR && !insn->noendbr) {
2315 					ERROR_INSN(insn, "UNWIND_HINT_IRET_REGS without ENDBR");
2316 					return -1;
2317 				}
2318 			}
2319 		}
2320 
2321 		if (hint->type == UNWIND_HINT_TYPE_FUNC) {
2322 			insn->cfi = &func_cfi;
2323 			continue;
2324 		}
2325 
2326 		if (insn->cfi)
2327 			cfi = *(insn->cfi);
2328 
2329 		if (arch_decode_hint_reg(hint->sp_reg, &cfi.cfa.base)) {
2330 			ERROR_INSN(insn, "unsupported unwind_hint sp base reg %d", hint->sp_reg);
2331 			return -1;
2332 		}
2333 
2334 		cfi.cfa.offset = bswap_if_needed(file->elf, hint->sp_offset);
2335 		cfi.type = hint->type;
2336 		cfi.signal = hint->signal;
2337 
2338 		insn->cfi = cfi_hash_find_or_add(&cfi);
2339 	}
2340 
2341 	return 0;
2342 }
2343 
2344 static int read_annotate(struct objtool_file *file,
2345 			 int (*func)(struct objtool_file *file, int type, struct instruction *insn))
2346 {
2347 	struct section *sec;
2348 	struct instruction *insn;
2349 	struct reloc *reloc;
2350 	uint64_t offset;
2351 	int type;
2352 
2353 	sec = find_section_by_name(file->elf, ".discard.annotate_insn");
2354 	if (!sec)
2355 		return 0;
2356 
2357 	if (!sec->rsec)
2358 		return 0;
2359 
2360 	if (sec->sh.sh_entsize != 8) {
2361 		static bool warned = false;
2362 		if (!warned && opts.verbose) {
2363 			WARN("%s: dodgy linker, sh_entsize != 8", sec->name);
2364 			warned = true;
2365 		}
2366 		sec->sh.sh_entsize = 8;
2367 	}
2368 
2369 	if (sec_num_entries(sec) != sec_num_entries(sec->rsec)) {
2370 		ERROR("bad .discard.annotate_insn section: missing relocs");
2371 		return -1;
2372 	}
2373 
2374 	for_each_reloc(sec->rsec, reloc) {
2375 		type = annotype(file->elf, sec, reloc);
2376 		offset = reloc->sym->offset + reloc_addend(reloc);
2377 		insn = find_insn(file, reloc->sym->sec, offset);
2378 
2379 		if (!insn) {
2380 			ERROR("bad .discard.annotate_insn entry: %d of type %d", reloc_idx(reloc), type);
2381 			return -1;
2382 		}
2383 
2384 		if (func(file, type, insn))
2385 			return -1;
2386 	}
2387 
2388 	return 0;
2389 }
2390 
2391 static int __annotate_early(struct objtool_file *file, int type, struct instruction *insn)
2392 {
2393 	switch (type) {
2394 
2395 	/* Must be before add_special_section_alts() */
2396 	case ANNOTYPE_IGNORE_ALTS:
2397 		insn->ignore_alts = true;
2398 		break;
2399 
2400 	/*
2401 	 * Must be before read_unwind_hints() since that needs insn->noendbr.
2402 	 */
2403 	case ANNOTYPE_NOENDBR:
2404 		insn->noendbr = 1;
2405 		break;
2406 
2407 	default:
2408 		break;
2409 	}
2410 
2411 	return 0;
2412 }
2413 
2414 static int __annotate_ifc(struct objtool_file *file, int type, struct instruction *insn)
2415 {
2416 	unsigned long dest_off;
2417 
2418 	if (type != ANNOTYPE_INTRA_FUNCTION_CALL)
2419 		return 0;
2420 
2421 	if (insn->type != INSN_CALL) {
2422 		ERROR_INSN(insn, "intra_function_call not a direct call");
2423 		return -1;
2424 	}
2425 
2426 	/*
2427 	 * Treat intra-function CALLs as JMPs, but with a stack_op.
2428 	 * See add_call_destinations(), which strips stack_ops from
2429 	 * normal CALLs.
2430 	 */
2431 	insn->type = INSN_JUMP_UNCONDITIONAL;
2432 
2433 	dest_off = arch_jump_destination(insn);
2434 	insn->jump_dest = find_insn(file, insn->sec, dest_off);
2435 	if (!insn->jump_dest) {
2436 		ERROR_INSN(insn, "can't find call dest at %s+0x%lx",
2437 			   insn->sec->name, dest_off);
2438 		return -1;
2439 	}
2440 
2441 	return 0;
2442 }
2443 
2444 static int __annotate_late(struct objtool_file *file, int type, struct instruction *insn)
2445 {
2446 	struct symbol *sym;
2447 
2448 	switch (type) {
2449 	case ANNOTYPE_NOENDBR:
2450 		/* early */
2451 		break;
2452 
2453 	case ANNOTYPE_RETPOLINE_SAFE:
2454 		if (insn->type != INSN_JUMP_DYNAMIC &&
2455 		    insn->type != INSN_CALL_DYNAMIC &&
2456 		    insn->type != INSN_RETURN &&
2457 		    insn->type != INSN_NOP) {
2458 			ERROR_INSN(insn, "retpoline_safe hint not an indirect jump/call/ret/nop");
2459 			return -1;
2460 		}
2461 
2462 		insn->retpoline_safe = true;
2463 		break;
2464 
2465 	case ANNOTYPE_INSTR_BEGIN:
2466 		insn->instr++;
2467 		break;
2468 
2469 	case ANNOTYPE_INSTR_END:
2470 		insn->instr--;
2471 		break;
2472 
2473 	case ANNOTYPE_UNRET_BEGIN:
2474 		insn->unret = 1;
2475 		break;
2476 
2477 	case ANNOTYPE_IGNORE_ALTS:
2478 		/* early */
2479 		break;
2480 
2481 	case ANNOTYPE_INTRA_FUNCTION_CALL:
2482 		/* ifc */
2483 		break;
2484 
2485 	case ANNOTYPE_REACHABLE:
2486 		insn->dead_end = false;
2487 		break;
2488 
2489 	case ANNOTYPE_NOCFI:
2490 		sym = insn->sym;
2491 		if (!sym) {
2492 			ERROR_INSN(insn, "dodgy NOCFI annotation");
2493 			return -1;
2494 		}
2495 		insn->sym->nocfi = 1;
2496 		break;
2497 
2498 	default:
2499 		ERROR_INSN(insn, "Unknown annotation type: %d", type);
2500 		return -1;
2501 	}
2502 
2503 	return 0;
2504 }
2505 
2506 /*
2507  * Return true if name matches an instrumentation function, where calls to that
2508  * function from noinstr code can safely be removed, but compilers won't do so.
2509  */
2510 static bool is_profiling_func(const char *name)
2511 {
2512 	/*
2513 	 * Many compilers cannot disable KCOV with a function attribute.
2514 	 */
2515 	if (!strncmp(name, "__sanitizer_cov_", 16))
2516 		return true;
2517 
2518 	return false;
2519 }
2520 
2521 static int classify_symbols(struct objtool_file *file)
2522 {
2523 	struct symbol *func;
2524 	size_t len;
2525 
2526 	for_each_sym(file->elf, func) {
2527 		if (is_notype_sym(func) && strstarts(func->name, ".L"))
2528 			func->local_label = true;
2529 
2530 		if (!is_global_sym(func))
2531 			continue;
2532 
2533 		if (!strncmp(func->name, STATIC_CALL_TRAMP_PREFIX_STR,
2534 			     strlen(STATIC_CALL_TRAMP_PREFIX_STR)))
2535 			func->static_call_tramp = true;
2536 
2537 		if (arch_is_retpoline(func))
2538 			func->retpoline_thunk = true;
2539 
2540 		if (arch_is_rethunk(func))
2541 			func->return_thunk = true;
2542 
2543 		if (arch_is_embedded_insn(func))
2544 			func->embedded_insn = true;
2545 
2546 		if (arch_ftrace_match(func->name))
2547 			func->fentry = true;
2548 
2549 		if (is_profiling_func(func->name))
2550 			func->profiling_func = true;
2551 
2552 		len = strlen(func->name);
2553 		if (len > sym_name_max_len)
2554 			sym_name_max_len = len;
2555 	}
2556 
2557 	return 0;
2558 }
2559 
2560 static void mark_rodata(struct objtool_file *file)
2561 {
2562 	struct section *sec;
2563 
2564 	/*
2565 	 * Search for the following rodata sections, each of which can
2566 	 * potentially contain jump tables:
2567 	 *
2568 	 * - .rodata: can contain GCC switch tables
2569 	 * - .rodata.<func>: same, if -fdata-sections is being used
2570 	 * - .data.rel.ro.c_jump_table: contains C annotated jump tables
2571 	 *
2572 	 * .rodata.str1.* sections are ignored; they don't contain jump tables.
2573 	 */
2574 	for_each_sec(file->elf, sec) {
2575 		if (is_rodata_sec(sec)) {
2576 			file->rodata = true;
2577 			return;
2578 		}
2579 	}
2580 }
2581 
2582 static void mark_holes(struct objtool_file *file)
2583 {
2584 	struct instruction *insn;
2585 	bool in_hole = false;
2586 
2587 	if (!opts.link)
2588 		return;
2589 
2590 	/*
2591 	 * Whole archive runs might encounter dead code from weak symbols.
2592 	 * This is where the linker will have dropped the weak symbol in
2593 	 * favour of a regular symbol, but leaves the code in place.
2594 	 */
2595 	for_each_insn(file, insn) {
2596 		if (insn->sym || !find_symbol_hole_containing(insn->sec, insn->offset)) {
2597 			in_hole = false;
2598 			continue;
2599 		}
2600 
2601 		/* Skip function padding and pfx code */
2602 		if (!in_hole && insn->type == INSN_NOP)
2603 			continue;
2604 
2605 		in_hole = true;
2606 		insn->hole = 1;
2607 
2608 		/*
2609 		 * If this hole jumps to a .cold function, mark it ignore.
2610 		 */
2611 		if (insn->jump_dest) {
2612 			struct symbol *dest_func = insn_func(insn->jump_dest);
2613 
2614 			if (dest_func && is_cold_func(dest_func))
2615 				dest_func->ignore = true;
2616 		}
2617 	}
2618 }
2619 
2620 static bool validate_branch_enabled(void)
2621 {
2622 	return opts.stackval	||
2623 	       opts.orc		||
2624 	       opts.uaccess;
2625 }
2626 
2627 static bool alts_needed(void)
2628 {
2629 	return validate_branch_enabled()	||
2630 	       opts.noinstr			||
2631 	       opts.hack_jump_label		||
2632 	       opts.disas			||
2633 	       opts.checksum;
2634 }
2635 
2636 int decode_file(struct objtool_file *file)
2637 {
2638 	arch_initial_func_cfi_state(&initial_func_cfi);
2639 	init_cfi_state(&init_cfi);
2640 	init_cfi_state(&func_cfi);
2641 	set_func_state(&func_cfi);
2642 	init_cfi_state(&force_undefined_cfi);
2643 	force_undefined_cfi.force_undefined = true;
2644 
2645 	if (!cfi_hash_alloc(1UL << (file->elf->symbol_bits - 3)))
2646 		return -1;
2647 
2648 	cfi_hash_add(&init_cfi);
2649 	cfi_hash_add(&func_cfi);
2650 
2651 	file->klp = is_livepatch_module(file);
2652 
2653 	mark_rodata(file);
2654 
2655 	if (init_pv_ops(file))
2656 		return -1;
2657 
2658 	/*
2659 	 * Must be before add_{jump_call}_destination.
2660 	 */
2661 	if (classify_symbols(file))
2662 		return -1;
2663 
2664 	if (decode_instructions(file))
2665 		return -1;
2666 
2667 	if (add_ignores(file))
2668 		return -1;
2669 
2670 	add_uaccess_safe(file);
2671 
2672 	if (read_annotate(file, __annotate_early))
2673 		return -1;
2674 
2675 	/*
2676 	 * Must be before add_jump_destinations(), which depends on 'func'
2677 	 * being set for alternatives, to enable proper sibling call detection.
2678 	 */
2679 	if (alts_needed()) {
2680 		if (add_special_section_alts(file))
2681 			return -1;
2682 	}
2683 
2684 	if (add_jump_destinations(file))
2685 		return -1;
2686 
2687 	/*
2688 	 * Must be before add_call_destination(); it changes INSN_CALL to
2689 	 * INSN_JUMP.
2690 	 */
2691 	if (read_annotate(file, __annotate_ifc))
2692 		return -1;
2693 
2694 	if (add_call_destinations(file))
2695 		return -1;
2696 
2697 	if (add_jump_table_alts(file))
2698 		return -1;
2699 
2700 	if (read_unwind_hints(file))
2701 		return -1;
2702 
2703 	/* Must be after add_jump_destinations() */
2704 	mark_holes(file);
2705 
2706 	/*
2707 	 * Must be after add_call_destinations() such that it can override
2708 	 * dead_end_function() marks.
2709 	 */
2710 	if (read_annotate(file, __annotate_late))
2711 		return -1;
2712 
2713 	return 0;
2714 }
2715 
2716 static bool is_special_call(struct instruction *insn)
2717 {
2718 	if (insn->type == INSN_CALL) {
2719 		struct symbol *dest = insn_call_dest(insn);
2720 
2721 		if (!dest)
2722 			return false;
2723 
2724 		if (dest->fentry || dest->embedded_insn)
2725 			return true;
2726 	}
2727 
2728 	return false;
2729 }
2730 
2731 static bool has_modified_stack_frame(struct instruction *insn, struct insn_state *state)
2732 {
2733 	struct cfi_state *cfi = &state->cfi;
2734 	int i;
2735 
2736 	if (cfi->cfa.base != initial_func_cfi.cfa.base || cfi->drap)
2737 		return true;
2738 
2739 	if (cfi->cfa.offset != initial_func_cfi.cfa.offset)
2740 		return true;
2741 
2742 	if (cfi->stack_size != initial_func_cfi.cfa.offset)
2743 		return true;
2744 
2745 	for (i = 0; i < CFI_NUM_REGS; i++) {
2746 		if (cfi->regs[i].base != initial_func_cfi.regs[i].base ||
2747 		    cfi->regs[i].offset != initial_func_cfi.regs[i].offset)
2748 			return true;
2749 	}
2750 
2751 	return false;
2752 }
2753 
2754 static bool check_reg_frame_pos(const struct cfi_reg *reg,
2755 				int expected_offset)
2756 {
2757 	return reg->base == CFI_CFA &&
2758 	       reg->offset == expected_offset;
2759 }
2760 
2761 static bool has_valid_stack_frame(struct insn_state *state)
2762 {
2763 	struct cfi_state *cfi = &state->cfi;
2764 
2765 	if (cfi->cfa.base == CFI_BP &&
2766 	    check_reg_frame_pos(&cfi->regs[CFI_BP], -cfi->cfa.offset) &&
2767 	    check_reg_frame_pos(&cfi->regs[CFI_RA], -cfi->cfa.offset + 8))
2768 		return true;
2769 
2770 	if (cfi->drap && cfi->regs[CFI_BP].base == CFI_BP)
2771 		return true;
2772 
2773 	return false;
2774 }
2775 
2776 static int update_cfi_state_regs(struct instruction *insn,
2777 				  struct cfi_state *cfi,
2778 				  struct stack_op *op)
2779 {
2780 	struct cfi_reg *cfa = &cfi->cfa;
2781 
2782 	if (cfa->base != CFI_SP && cfa->base != CFI_SP_INDIRECT)
2783 		return 0;
2784 
2785 	/* push */
2786 	if (op->dest.type == OP_DEST_PUSH || op->dest.type == OP_DEST_PUSHF)
2787 		cfa->offset += 8;
2788 
2789 	/* pop */
2790 	if (op->src.type == OP_SRC_POP || op->src.type == OP_SRC_POPF)
2791 		cfa->offset -= 8;
2792 
2793 	/* add immediate to sp */
2794 	if (op->dest.type == OP_DEST_REG && op->src.type == OP_SRC_ADD &&
2795 	    op->dest.reg == CFI_SP && op->src.reg == CFI_SP)
2796 		cfa->offset -= op->src.offset;
2797 
2798 	return 0;
2799 }
2800 
2801 static void save_reg(struct cfi_state *cfi, unsigned char reg, int base, int offset)
2802 {
2803 	if (arch_callee_saved_reg(reg) &&
2804 	    cfi->regs[reg].base == CFI_UNDEFINED) {
2805 		cfi->regs[reg].base = base;
2806 		cfi->regs[reg].offset = offset;
2807 	}
2808 }
2809 
2810 static void restore_reg(struct cfi_state *cfi, unsigned char reg)
2811 {
2812 	cfi->regs[reg].base = initial_func_cfi.regs[reg].base;
2813 	cfi->regs[reg].offset = initial_func_cfi.regs[reg].offset;
2814 }
2815 
2816 /*
2817  * A note about DRAP stack alignment:
2818  *
2819  * GCC has the concept of a DRAP register, which is used to help keep track of
2820  * the stack pointer when aligning the stack.  r10 or r13 is used as the DRAP
2821  * register.  The typical DRAP pattern is:
2822  *
2823  *   4c 8d 54 24 08		lea    0x8(%rsp),%r10
2824  *   48 83 e4 c0		and    $0xffffffffffffffc0,%rsp
2825  *   41 ff 72 f8		pushq  -0x8(%r10)
2826  *   55				push   %rbp
2827  *   48 89 e5			mov    %rsp,%rbp
2828  *				(more pushes)
2829  *   41 52			push   %r10
2830  *				...
2831  *   41 5a			pop    %r10
2832  *				(more pops)
2833  *   5d				pop    %rbp
2834  *   49 8d 62 f8		lea    -0x8(%r10),%rsp
2835  *   c3				retq
2836  *
2837  * There are some variations in the epilogues, like:
2838  *
2839  *   5b				pop    %rbx
2840  *   41 5a			pop    %r10
2841  *   41 5c			pop    %r12
2842  *   41 5d			pop    %r13
2843  *   41 5e			pop    %r14
2844  *   c9				leaveq
2845  *   49 8d 62 f8		lea    -0x8(%r10),%rsp
2846  *   c3				retq
2847  *
2848  * and:
2849  *
2850  *   4c 8b 55 e8		mov    -0x18(%rbp),%r10
2851  *   48 8b 5d e0		mov    -0x20(%rbp),%rbx
2852  *   4c 8b 65 f0		mov    -0x10(%rbp),%r12
2853  *   4c 8b 6d f8		mov    -0x8(%rbp),%r13
2854  *   c9				leaveq
2855  *   49 8d 62 f8		lea    -0x8(%r10),%rsp
2856  *   c3				retq
2857  *
2858  * Sometimes r13 is used as the DRAP register, in which case it's saved and
2859  * restored beforehand:
2860  *
2861  *   41 55			push   %r13
2862  *   4c 8d 6c 24 10		lea    0x10(%rsp),%r13
2863  *   48 83 e4 f0		and    $0xfffffffffffffff0,%rsp
2864  *				...
2865  *   49 8d 65 f0		lea    -0x10(%r13),%rsp
2866  *   41 5d			pop    %r13
2867  *   c3				retq
2868  */
2869 static int update_cfi_state(struct instruction *insn,
2870 			    struct instruction *next_insn,
2871 			    struct cfi_state *cfi, struct stack_op *op)
2872 {
2873 	struct cfi_reg *cfa = &cfi->cfa;
2874 	struct cfi_reg *regs = cfi->regs;
2875 
2876 	/* ignore UNWIND_HINT_UNDEFINED regions */
2877 	if (cfi->force_undefined)
2878 		return 0;
2879 
2880 	/* stack operations don't make sense with an undefined CFA */
2881 	if (cfa->base == CFI_UNDEFINED) {
2882 		if (insn_func(insn)) {
2883 			WARN_INSN(insn, "undefined stack state");
2884 			return 1;
2885 		}
2886 		return 0;
2887 	}
2888 
2889 	if (cfi->type == UNWIND_HINT_TYPE_REGS ||
2890 	    cfi->type == UNWIND_HINT_TYPE_REGS_PARTIAL)
2891 		return update_cfi_state_regs(insn, cfi, op);
2892 
2893 	switch (op->dest.type) {
2894 
2895 	case OP_DEST_REG:
2896 		switch (op->src.type) {
2897 
2898 		case OP_SRC_REG:
2899 			if (op->src.reg == CFI_SP && op->dest.reg == CFI_BP &&
2900 			    cfa->base == CFI_SP &&
2901 			    check_reg_frame_pos(&regs[CFI_BP], -cfa->offset)) {
2902 
2903 				/* mov %rsp, %rbp */
2904 				cfa->base = op->dest.reg;
2905 				cfi->bp_scratch = false;
2906 			}
2907 
2908 			else if (op->src.reg == CFI_SP &&
2909 				 op->dest.reg == CFI_BP && cfi->drap) {
2910 
2911 				/* drap: mov %rsp, %rbp */
2912 				regs[CFI_BP].base = CFI_BP;
2913 				regs[CFI_BP].offset = -cfi->stack_size;
2914 				cfi->bp_scratch = false;
2915 			}
2916 
2917 			else if (op->src.reg == CFI_SP && cfa->base == CFI_SP) {
2918 
2919 				/*
2920 				 * mov %rsp, %reg
2921 				 *
2922 				 * This is needed for the rare case where GCC
2923 				 * does:
2924 				 *
2925 				 *   mov    %rsp, %rax
2926 				 *   ...
2927 				 *   mov    %rax, %rsp
2928 				 */
2929 				cfi->vals[op->dest.reg].base = CFI_CFA;
2930 				cfi->vals[op->dest.reg].offset = -cfi->stack_size;
2931 			}
2932 
2933 			else if (op->src.reg == CFI_BP && op->dest.reg == CFI_SP &&
2934 				 (cfa->base == CFI_BP || cfa->base == cfi->drap_reg)) {
2935 
2936 				/*
2937 				 * mov %rbp, %rsp
2938 				 *
2939 				 * Restore the original stack pointer (Clang).
2940 				 */
2941 				cfi->stack_size = -cfi->regs[CFI_BP].offset;
2942 			}
2943 
2944 			else if (op->dest.reg == cfa->base) {
2945 
2946 				/* mov %reg, %rsp */
2947 				if (cfa->base == CFI_SP &&
2948 				    cfi->vals[op->src.reg].base == CFI_CFA) {
2949 
2950 					/*
2951 					 * This is needed for the rare case
2952 					 * where GCC does something dumb like:
2953 					 *
2954 					 *   lea    0x8(%rsp), %rcx
2955 					 *   ...
2956 					 *   mov    %rcx, %rsp
2957 					 */
2958 					cfa->offset = -cfi->vals[op->src.reg].offset;
2959 					cfi->stack_size = cfa->offset;
2960 
2961 				} else if (cfa->base == CFI_SP &&
2962 					   cfi->vals[op->src.reg].base == CFI_SP_INDIRECT &&
2963 					   cfi->vals[op->src.reg].offset == cfa->offset) {
2964 
2965 					/*
2966 					 * Stack swizzle:
2967 					 *
2968 					 * 1: mov %rsp, (%[tos])
2969 					 * 2: mov %[tos], %rsp
2970 					 *    ...
2971 					 * 3: pop %rsp
2972 					 *
2973 					 * Where:
2974 					 *
2975 					 * 1 - places a pointer to the previous
2976 					 *     stack at the Top-of-Stack of the
2977 					 *     new stack.
2978 					 *
2979 					 * 2 - switches to the new stack.
2980 					 *
2981 					 * 3 - pops the Top-of-Stack to restore
2982 					 *     the original stack.
2983 					 *
2984 					 * Note: we set base to SP_INDIRECT
2985 					 * here and preserve offset. Therefore
2986 					 * when the unwinder reaches ToS it
2987 					 * will dereference SP and then add the
2988 					 * offset to find the next frame, IOW:
2989 					 * (%rsp) + offset.
2990 					 */
2991 					cfa->base = CFI_SP_INDIRECT;
2992 
2993 				} else {
2994 					cfa->base = CFI_UNDEFINED;
2995 					cfa->offset = 0;
2996 				}
2997 			}
2998 
2999 			else if (op->dest.reg == CFI_SP &&
3000 				 cfi->vals[op->src.reg].base == CFI_SP_INDIRECT &&
3001 				 cfi->vals[op->src.reg].offset == cfa->offset) {
3002 
3003 				/*
3004 				 * The same stack swizzle case 2) as above. But
3005 				 * because we can't change cfa->base, case 3)
3006 				 * will become a regular POP. Pretend we're a
3007 				 * PUSH so things don't go unbalanced.
3008 				 */
3009 				cfi->stack_size += 8;
3010 			}
3011 
3012 			else if (cfi->vals[op->src.reg].base == CFI_CFA) {
3013 				/*
3014 				 * Clang RSP musical chairs:
3015 				 *
3016 				 *   mov %rsp, %rdx [handled above]
3017 				 *   ...
3018 				 *   mov %rdx, %rbx [handled here]
3019 				 *   ...
3020 				 *   mov %rbx, %rsp [handled above]
3021 				 */
3022 				cfi->vals[op->dest.reg].base = CFI_CFA;
3023 				cfi->vals[op->dest.reg].offset = cfi->vals[op->src.reg].offset;
3024 			}
3025 
3026 
3027 			break;
3028 
3029 		case OP_SRC_ADD:
3030 			if (op->dest.reg == CFI_SP && op->src.reg == CFI_SP) {
3031 
3032 				/* add imm, %rsp */
3033 				cfi->stack_size -= op->src.offset;
3034 				if (cfa->base == CFI_SP)
3035 					cfa->offset -= op->src.offset;
3036 				break;
3037 			}
3038 
3039 			if (op->dest.reg == CFI_BP && op->src.reg == CFI_SP &&
3040 			    insn->sym->frame_pointer) {
3041 				/* addi.d fp,sp,imm on LoongArch */
3042 				if (cfa->base == CFI_SP && cfa->offset == op->src.offset) {
3043 					cfa->base = CFI_BP;
3044 					cfa->offset = 0;
3045 				}
3046 				break;
3047 			}
3048 
3049 			if (op->dest.reg == CFI_SP && op->src.reg == CFI_BP) {
3050 				/* addi.d sp,fp,imm on LoongArch */
3051 				if (cfa->base == CFI_BP && cfa->offset == 0) {
3052 					if (insn->sym->frame_pointer) {
3053 						cfa->base = CFI_SP;
3054 						cfa->offset = -op->src.offset;
3055 					}
3056 				} else {
3057 					/* lea disp(%rbp), %rsp */
3058 					cfi->stack_size = -(op->src.offset + regs[CFI_BP].offset);
3059 				}
3060 				break;
3061 			}
3062 
3063 			if (op->src.reg == CFI_SP && cfa->base == CFI_SP) {
3064 
3065 				/* drap: lea disp(%rsp), %drap */
3066 				cfi->drap_reg = op->dest.reg;
3067 
3068 				/*
3069 				 * lea disp(%rsp), %reg
3070 				 *
3071 				 * This is needed for the rare case where GCC
3072 				 * does something dumb like:
3073 				 *
3074 				 *   lea    0x8(%rsp), %rcx
3075 				 *   ...
3076 				 *   mov    %rcx, %rsp
3077 				 */
3078 				cfi->vals[op->dest.reg].base = CFI_CFA;
3079 				cfi->vals[op->dest.reg].offset = \
3080 					-cfi->stack_size + op->src.offset;
3081 
3082 				break;
3083 			}
3084 
3085 			if (cfi->drap && op->dest.reg == CFI_SP &&
3086 			    op->src.reg == cfi->drap_reg) {
3087 
3088 				 /* drap: lea disp(%drap), %rsp */
3089 				cfa->base = CFI_SP;
3090 				cfa->offset = cfi->stack_size = -op->src.offset;
3091 				cfi->drap_reg = CFI_UNDEFINED;
3092 				cfi->drap = false;
3093 				break;
3094 			}
3095 
3096 			if (op->dest.reg == cfi->cfa.base && !(next_insn && next_insn->hint)) {
3097 				WARN_INSN(insn, "unsupported stack register modification");
3098 				return -1;
3099 			}
3100 
3101 			break;
3102 
3103 		case OP_SRC_AND:
3104 			if (op->dest.reg != CFI_SP ||
3105 			    (cfi->drap_reg != CFI_UNDEFINED && cfa->base != CFI_SP) ||
3106 			    (cfi->drap_reg == CFI_UNDEFINED && cfa->base != CFI_BP)) {
3107 				WARN_INSN(insn, "unsupported stack pointer realignment");
3108 				return -1;
3109 			}
3110 
3111 			if (cfi->drap_reg != CFI_UNDEFINED) {
3112 				/* drap: and imm, %rsp */
3113 				cfa->base = cfi->drap_reg;
3114 				cfa->offset = cfi->stack_size = 0;
3115 				cfi->drap = true;
3116 			}
3117 
3118 			/*
3119 			 * Older versions of GCC (4.8ish) realign the stack
3120 			 * without DRAP, with a frame pointer.
3121 			 */
3122 
3123 			break;
3124 
3125 		case OP_SRC_POP:
3126 		case OP_SRC_POPF:
3127 			if (op->dest.reg == CFI_SP && cfa->base == CFI_SP_INDIRECT) {
3128 
3129 				/* pop %rsp; # restore from a stack swizzle */
3130 				cfa->base = CFI_SP;
3131 				break;
3132 			}
3133 
3134 			if (!cfi->drap && op->dest.reg == cfa->base) {
3135 
3136 				/* pop %rbp */
3137 				cfa->base = CFI_SP;
3138 			}
3139 
3140 			if (cfi->drap && cfa->base == CFI_BP_INDIRECT &&
3141 			    op->dest.reg == cfi->drap_reg &&
3142 			    cfi->drap_offset == -cfi->stack_size) {
3143 
3144 				/* drap: pop %drap */
3145 				cfa->base = cfi->drap_reg;
3146 				cfa->offset = 0;
3147 				cfi->drap_offset = -1;
3148 
3149 			} else if (cfi->stack_size == -regs[op->dest.reg].offset) {
3150 
3151 				/* pop %reg */
3152 				restore_reg(cfi, op->dest.reg);
3153 			}
3154 
3155 			cfi->stack_size -= 8;
3156 			if (cfa->base == CFI_SP)
3157 				cfa->offset -= 8;
3158 
3159 			break;
3160 
3161 		case OP_SRC_REG_INDIRECT:
3162 			if (!cfi->drap && op->dest.reg == cfa->base &&
3163 			    op->dest.reg == CFI_BP) {
3164 
3165 				/* mov disp(%rsp), %rbp */
3166 				cfa->base = CFI_SP;
3167 				cfa->offset = cfi->stack_size;
3168 			}
3169 
3170 			if (cfi->drap && op->src.reg == CFI_BP &&
3171 			    op->src.offset == cfi->drap_offset) {
3172 
3173 				/* drap: mov disp(%rbp), %drap */
3174 				cfa->base = cfi->drap_reg;
3175 				cfa->offset = 0;
3176 				cfi->drap_offset = -1;
3177 			}
3178 
3179 			if (cfi->drap && op->src.reg == CFI_BP &&
3180 			    op->src.offset == regs[op->dest.reg].offset) {
3181 
3182 				/* drap: mov disp(%rbp), %reg */
3183 				restore_reg(cfi, op->dest.reg);
3184 
3185 			} else if (op->src.reg == cfa->base &&
3186 			    op->src.offset == regs[op->dest.reg].offset + cfa->offset) {
3187 
3188 				/* mov disp(%rbp), %reg */
3189 				/* mov disp(%rsp), %reg */
3190 				restore_reg(cfi, op->dest.reg);
3191 
3192 			} else if (op->src.reg == CFI_SP &&
3193 				   op->src.offset == regs[op->dest.reg].offset + cfi->stack_size) {
3194 
3195 				/* mov disp(%rsp), %reg */
3196 				restore_reg(cfi, op->dest.reg);
3197 			}
3198 
3199 			break;
3200 
3201 		default:
3202 			WARN_INSN(insn, "unknown stack-related instruction");
3203 			return -1;
3204 		}
3205 
3206 		break;
3207 
3208 	case OP_DEST_PUSH:
3209 	case OP_DEST_PUSHF:
3210 		cfi->stack_size += 8;
3211 		if (cfa->base == CFI_SP)
3212 			cfa->offset += 8;
3213 
3214 		if (op->src.type != OP_SRC_REG)
3215 			break;
3216 
3217 		if (cfi->drap) {
3218 			if (op->src.reg == cfa->base && op->src.reg == cfi->drap_reg) {
3219 
3220 				/* drap: push %drap */
3221 				cfa->base = CFI_BP_INDIRECT;
3222 				cfa->offset = -cfi->stack_size;
3223 
3224 				/* save drap so we know when to restore it */
3225 				cfi->drap_offset = -cfi->stack_size;
3226 
3227 			} else if (op->src.reg == CFI_BP && cfa->base == cfi->drap_reg) {
3228 
3229 				/* drap: push %rbp */
3230 				cfi->stack_size = 0;
3231 
3232 			} else {
3233 
3234 				/* drap: push %reg */
3235 				save_reg(cfi, op->src.reg, CFI_BP, -cfi->stack_size);
3236 			}
3237 
3238 		} else {
3239 
3240 			/* push %reg */
3241 			save_reg(cfi, op->src.reg, CFI_CFA, -cfi->stack_size);
3242 		}
3243 
3244 		/* detect when asm code uses rbp as a scratch register */
3245 		if (opts.stackval && insn_func(insn) && op->src.reg == CFI_BP &&
3246 		    cfa->base != CFI_BP)
3247 			cfi->bp_scratch = true;
3248 		break;
3249 
3250 	case OP_DEST_REG_INDIRECT:
3251 
3252 		if (cfi->drap) {
3253 			if (op->src.reg == cfa->base && op->src.reg == cfi->drap_reg) {
3254 
3255 				/* drap: mov %drap, disp(%rbp) */
3256 				cfa->base = CFI_BP_INDIRECT;
3257 				cfa->offset = op->dest.offset;
3258 
3259 				/* save drap offset so we know when to restore it */
3260 				cfi->drap_offset = op->dest.offset;
3261 			} else {
3262 
3263 				/* drap: mov reg, disp(%rbp) */
3264 				save_reg(cfi, op->src.reg, CFI_BP, op->dest.offset);
3265 			}
3266 
3267 		} else if (op->dest.reg == cfa->base) {
3268 
3269 			/* mov reg, disp(%rbp) */
3270 			/* mov reg, disp(%rsp) */
3271 			save_reg(cfi, op->src.reg, CFI_CFA,
3272 				 op->dest.offset - cfi->cfa.offset);
3273 
3274 		} else if (op->dest.reg == CFI_SP) {
3275 
3276 			/* mov reg, disp(%rsp) */
3277 			save_reg(cfi, op->src.reg, CFI_CFA,
3278 				 op->dest.offset - cfi->stack_size);
3279 
3280 		} else if (op->src.reg == CFI_SP && op->dest.offset == 0) {
3281 
3282 			/* mov %rsp, (%reg); # setup a stack swizzle. */
3283 			cfi->vals[op->dest.reg].base = CFI_SP_INDIRECT;
3284 			cfi->vals[op->dest.reg].offset = cfa->offset;
3285 		}
3286 
3287 		break;
3288 
3289 	case OP_DEST_MEM:
3290 		if (op->src.type != OP_SRC_POP && op->src.type != OP_SRC_POPF) {
3291 			WARN_INSN(insn, "unknown stack-related memory operation");
3292 			return -1;
3293 		}
3294 
3295 		/* pop mem */
3296 		cfi->stack_size -= 8;
3297 		if (cfa->base == CFI_SP)
3298 			cfa->offset -= 8;
3299 
3300 		break;
3301 
3302 	default:
3303 		WARN_INSN(insn, "unknown stack-related instruction");
3304 		return -1;
3305 	}
3306 
3307 	return 0;
3308 }
3309 
3310 /*
3311  * The stack layouts of alternatives instructions can sometimes diverge when
3312  * they have stack modifications.  That's fine as long as the potential stack
3313  * layouts don't conflict at any given potential instruction boundary.
3314  *
3315  * Flatten the CFIs of the different alternative code streams (both original
3316  * and replacement) into a single shared CFI array which can be used to detect
3317  * conflicts and nicely feed a linear array of ORC entries to the unwinder.
3318  */
3319 static int propagate_alt_cfi(struct objtool_file *file, struct instruction *insn)
3320 {
3321 	struct cfi_state **alt_cfi;
3322 	int group_off;
3323 
3324 	if (!insn->alt_group)
3325 		return 0;
3326 
3327 	if (!insn->cfi) {
3328 		WARN("CFI missing");
3329 		return -1;
3330 	}
3331 
3332 	alt_cfi = insn->alt_group->cfi;
3333 	group_off = insn->offset - insn->alt_group->first_insn->offset;
3334 
3335 	if (!alt_cfi[group_off]) {
3336 		alt_cfi[group_off] = insn->cfi;
3337 	} else {
3338 		if (cficmp(alt_cfi[group_off], insn->cfi)) {
3339 			struct alt_group *orig_group = insn->alt_group->orig_group ?: insn->alt_group;
3340 			struct instruction *orig = orig_group->first_insn;
3341 			WARN_INSN(orig, "stack layout conflict in alternatives: %s",
3342 				  offstr(insn->sec, insn->offset));
3343 			return -1;
3344 		}
3345 	}
3346 
3347 	return 0;
3348 }
3349 
3350 static int noinline handle_insn_ops(struct instruction *insn,
3351 				    struct instruction *next_insn,
3352 				    struct insn_state *state)
3353 {
3354 	struct insn_state prev_state __maybe_unused = *state;
3355 	struct stack_op *op;
3356 	int ret = 0;
3357 
3358 	for (op = insn->stack_ops; op; op = op->next) {
3359 
3360 		ret = update_cfi_state(insn, next_insn, &state->cfi, op);
3361 		if (ret)
3362 			goto done;
3363 
3364 		if (!opts.uaccess || !insn->alt_group)
3365 			continue;
3366 
3367 		if (op->dest.type == OP_DEST_PUSHF) {
3368 			if (!state->uaccess_stack) {
3369 				state->uaccess_stack = 1;
3370 			} else if (state->uaccess_stack >> 31) {
3371 				WARN_INSN(insn, "PUSHF stack exhausted");
3372 				ret = 1;
3373 				goto done;
3374 			}
3375 			state->uaccess_stack <<= 1;
3376 			state->uaccess_stack  |= state->uaccess;
3377 		}
3378 
3379 		if (op->src.type == OP_SRC_POPF) {
3380 			if (state->uaccess_stack) {
3381 				state->uaccess = state->uaccess_stack & 1;
3382 				state->uaccess_stack >>= 1;
3383 				if (state->uaccess_stack == 1)
3384 					state->uaccess_stack = 0;
3385 			}
3386 		}
3387 	}
3388 
3389 done:
3390 	TRACE_INSN_STATE(insn, &prev_state, state);
3391 
3392 	return ret;
3393 }
3394 
3395 static bool insn_cfi_match(struct instruction *insn, struct cfi_state *cfi2)
3396 {
3397 	struct cfi_state *cfi1 = insn->cfi;
3398 	int i;
3399 
3400 	if (!cfi1) {
3401 		WARN("CFI missing");
3402 		return false;
3403 	}
3404 
3405 	if (memcmp(&cfi1->cfa, &cfi2->cfa, sizeof(cfi1->cfa))) {
3406 
3407 		WARN_INSN(insn, "stack state mismatch: cfa1=%d%+d cfa2=%d%+d",
3408 			  cfi1->cfa.base, cfi1->cfa.offset,
3409 			  cfi2->cfa.base, cfi2->cfa.offset);
3410 		return false;
3411 
3412 	}
3413 
3414 	if (memcmp(&cfi1->regs, &cfi2->regs, sizeof(cfi1->regs))) {
3415 		for (i = 0; i < CFI_NUM_REGS; i++) {
3416 
3417 			if (!memcmp(&cfi1->regs[i], &cfi2->regs[i], sizeof(struct cfi_reg)))
3418 				continue;
3419 
3420 			WARN_INSN(insn, "stack state mismatch: reg1[%d]=%d%+d reg2[%d]=%d%+d",
3421 				  i, cfi1->regs[i].base, cfi1->regs[i].offset,
3422 				  i, cfi2->regs[i].base, cfi2->regs[i].offset);
3423 		}
3424 		return false;
3425 	}
3426 
3427 	if (cfi1->type != cfi2->type) {
3428 
3429 		WARN_INSN(insn, "stack state mismatch: type1=%d type2=%d",
3430 			  cfi1->type, cfi2->type);
3431 		return false;
3432 	}
3433 
3434 	if (cfi1->drap != cfi2->drap ||
3435 		   (cfi1->drap && cfi1->drap_reg != cfi2->drap_reg) ||
3436 		   (cfi1->drap && cfi1->drap_offset != cfi2->drap_offset)) {
3437 
3438 		WARN_INSN(insn, "stack state mismatch: drap1=%d(%d,%d) drap2=%d(%d,%d)",
3439 			  cfi1->drap, cfi1->drap_reg, cfi1->drap_offset,
3440 			  cfi2->drap, cfi2->drap_reg, cfi2->drap_offset);
3441 		return false;
3442 	}
3443 
3444 	return true;
3445 }
3446 
3447 static inline bool func_uaccess_safe(struct symbol *func)
3448 {
3449 	if (func)
3450 		return func->uaccess_safe;
3451 
3452 	return false;
3453 }
3454 
3455 static inline const char *call_dest_name(struct instruction *insn)
3456 {
3457 	static char pvname[19];
3458 	struct reloc *reloc;
3459 	int idx;
3460 
3461 	if (insn_call_dest(insn))
3462 		return insn_call_dest(insn)->name;
3463 
3464 	reloc = insn_reloc(NULL, insn);
3465 	if (reloc && !strcmp(reloc->sym->name, "pv_ops")) {
3466 		idx = (reloc_addend(reloc) / sizeof(void *));
3467 		snprintf(pvname, sizeof(pvname), "pv_ops[%d]", idx);
3468 		return pvname;
3469 	}
3470 
3471 	return "{dynamic}";
3472 }
3473 
3474 static bool pv_call_dest(struct objtool_file *file, struct instruction *insn)
3475 {
3476 	struct symbol *target;
3477 	struct reloc *reloc;
3478 	int idx;
3479 
3480 	reloc = insn_reloc(file, insn);
3481 	if (!reloc || strcmp(reloc->sym->name, "pv_ops"))
3482 		return false;
3483 
3484 	idx = arch_insn_adjusted_addend(insn, reloc) / sizeof(void *);
3485 
3486 	if (file->pv_ops[idx].clean)
3487 		return true;
3488 
3489 	file->pv_ops[idx].clean = true;
3490 
3491 	list_for_each_entry(target, &file->pv_ops[idx].targets, pv_target) {
3492 		if (!target->sec->noinstr) {
3493 			WARN("pv_ops[%d]: %s", idx, target->name);
3494 			file->pv_ops[idx].clean = false;
3495 		}
3496 	}
3497 
3498 	return file->pv_ops[idx].clean;
3499 }
3500 
3501 static inline bool noinstr_call_dest(struct objtool_file *file,
3502 				     struct instruction *insn,
3503 				     struct symbol *func)
3504 {
3505 	/*
3506 	 * We can't deal with indirect function calls at present;
3507 	 * assume they're instrumented.
3508 	 */
3509 	if (!func) {
3510 		if (file->pv_ops)
3511 			return pv_call_dest(file, insn);
3512 
3513 		return false;
3514 	}
3515 
3516 	/*
3517 	 * If the symbol is from a noinstr section; we good.
3518 	 */
3519 	if (func->sec->noinstr)
3520 		return true;
3521 
3522 	/*
3523 	 * If the symbol is a static_call trampoline, we can't tell.
3524 	 */
3525 	if (func->static_call_tramp)
3526 		return true;
3527 
3528 	/*
3529 	 * The __ubsan_handle_*() calls are like WARN(), they only happen when
3530 	 * something 'BAD' happened. At the risk of taking the machine down,
3531 	 * let them proceed to get the message out.
3532 	 */
3533 	if (!strncmp(func->name, "__ubsan_handle_", 15))
3534 		return true;
3535 
3536 	return false;
3537 }
3538 
3539 static int validate_call(struct objtool_file *file,
3540 			 struct instruction *insn,
3541 			 struct insn_state *state)
3542 {
3543 	if (state->noinstr && state->instr <= 0 &&
3544 	    !noinstr_call_dest(file, insn, insn_call_dest(insn))) {
3545 		WARN_INSN(insn, "call to %s() leaves .noinstr.text section", call_dest_name(insn));
3546 		return 1;
3547 	}
3548 
3549 	if (state->uaccess && !func_uaccess_safe(insn_call_dest(insn))) {
3550 		WARN_INSN(insn, "call to %s() with UACCESS enabled", call_dest_name(insn));
3551 		return 1;
3552 	}
3553 
3554 	if (state->df) {
3555 		WARN_INSN(insn, "call to %s() with DF set", call_dest_name(insn));
3556 		return 1;
3557 	}
3558 
3559 	return 0;
3560 }
3561 
3562 static int validate_sibling_call(struct objtool_file *file,
3563 				 struct instruction *insn,
3564 				 struct insn_state *state)
3565 {
3566 	if (insn_func(insn) && has_modified_stack_frame(insn, state)) {
3567 		WARN_INSN(insn, "sibling call from callable instruction with modified stack frame");
3568 		return 1;
3569 	}
3570 
3571 	return validate_call(file, insn, state);
3572 }
3573 
3574 static int validate_return(struct symbol *func, struct instruction *insn, struct insn_state *state)
3575 {
3576 	if (state->noinstr && state->instr > 0) {
3577 		WARN_INSN(insn, "return with instrumentation enabled");
3578 		return 1;
3579 	}
3580 
3581 	if (state->uaccess && !func_uaccess_safe(func)) {
3582 		WARN_INSN(insn, "return with UACCESS enabled");
3583 		return 1;
3584 	}
3585 
3586 	if (!state->uaccess && func_uaccess_safe(func)) {
3587 		WARN_INSN(insn, "return with UACCESS disabled from a UACCESS-safe function");
3588 		return 1;
3589 	}
3590 
3591 	if (state->df) {
3592 		WARN_INSN(insn, "return with DF set");
3593 		return 1;
3594 	}
3595 
3596 	if (func && has_modified_stack_frame(insn, state)) {
3597 		WARN_INSN(insn, "return with modified stack frame");
3598 		return 1;
3599 	}
3600 
3601 	if (state->cfi.bp_scratch) {
3602 		WARN_INSN(insn, "BP used as a scratch register");
3603 		return 1;
3604 	}
3605 
3606 	return 0;
3607 }
3608 
3609 static struct instruction *next_insn_to_validate(struct objtool_file *file,
3610 						 struct instruction *insn)
3611 {
3612 	struct alt_group *alt_group = insn->alt_group;
3613 
3614 	/*
3615 	 * Simulate the fact that alternatives are patched in-place.  When the
3616 	 * end of a replacement alt_group is reached, redirect objtool flow to
3617 	 * the end of the original alt_group.
3618 	 *
3619 	 * insn->alts->insn -> alt_group->first_insn
3620 	 *		       ...
3621 	 *		       alt_group->last_insn
3622 	 *		       [alt_group->nop]      -> next(orig_group->last_insn)
3623 	 */
3624 	if (alt_group) {
3625 		if (alt_group->nop) {
3626 			/* ->nop implies ->orig_group */
3627 			if (insn == alt_group->last_insn)
3628 				return alt_group->nop;
3629 			if (insn == alt_group->nop)
3630 				goto next_orig;
3631 		}
3632 		if (insn == alt_group->last_insn && alt_group->orig_group)
3633 			goto next_orig;
3634 	}
3635 
3636 	return next_insn_same_sec(file, insn);
3637 
3638 next_orig:
3639 	return next_insn_same_sec(file, alt_group->orig_group->last_insn);
3640 }
3641 
3642 static bool skip_alt_group(struct instruction *insn)
3643 {
3644 	struct instruction *alt_insn = insn->alts ? insn->alts->insn : NULL;
3645 
3646 	if (!insn->alt_group)
3647 		return false;
3648 
3649 	/* ANNOTATE_IGNORE_ALTERNATIVE */
3650 	if (insn->alt_group->ignore) {
3651 		TRACE_ALT(insn, "alt group ignored");
3652 		return true;
3653 	}
3654 
3655 	/*
3656 	 * For NOP patched with CLAC/STAC, only follow the latter to avoid
3657 	 * impossible code paths combining patched CLAC with unpatched STAC
3658 	 * or vice versa.
3659 	 *
3660 	 * ANNOTATE_IGNORE_ALTERNATIVE could have been used here, but Linus
3661 	 * requested not to do that to avoid hurting .s file readability
3662 	 * around CLAC/STAC alternative sites.
3663 	 */
3664 
3665 	if (!alt_insn)
3666 		return false;
3667 
3668 	/* Don't override ASM_{CLAC,STAC}_UNSAFE */
3669 	if (alt_insn->alt_group && alt_insn->alt_group->ignore)
3670 		return false;
3671 
3672 	return alt_insn->type == INSN_CLAC || alt_insn->type == INSN_STAC;
3673 }
3674 
3675 #ifdef BUILD_KLP
3676 static int checksum_debug_init(struct objtool_file *file)
3677 {
3678 	char *dup, *s;
3679 
3680 	if (!opts.debug_checksum)
3681 		return 0;
3682 
3683 	dup = strdup(opts.debug_checksum);
3684 	if (!dup) {
3685 		ERROR_GLIBC("strdup");
3686 		return -1;
3687 	}
3688 
3689 	s = dup;
3690 	while (*s) {
3691 		bool found = false;
3692 		struct symbol *sym;
3693 		char *comma;
3694 
3695 		comma = strchr(s, ',');
3696 		if (comma)
3697 			*comma = '\0';
3698 
3699 		for_each_sym_by_name(file->elf, s, sym) {
3700 			if (!is_func_sym(sym))
3701 				continue;
3702 			sym->debug_checksum = 1;
3703 			found = true;
3704 		}
3705 
3706 		if (!found)
3707 			WARN("--debug-checksum: can't find '%s'", s);
3708 
3709 		if (!comma)
3710 			break;
3711 
3712 		s = comma + 1;
3713 	}
3714 
3715 	free(dup);
3716 	return 0;
3717 }
3718 
3719 static void checksum_update_insn(struct objtool_file *file, struct symbol *func,
3720 				 struct instruction *insn)
3721 {
3722 	struct reloc *reloc = insn_reloc(file, insn);
3723 	struct alternative *alt;
3724 	unsigned long offset;
3725 	struct symbol *sym;
3726 	static bool in_alt;
3727 
3728 	if (insn->fake)
3729 		return;
3730 
3731 	checksum_update(func, insn, insn->sec->data->d_buf + insn->offset, insn->len);
3732 
3733 	if (!reloc) {
3734 		struct symbol *call_dest = insn_call_dest(insn);
3735 
3736 		if (call_dest)
3737 			checksum_update(func, insn, call_dest->demangled_name,
3738 					strlen(call_dest->demangled_name));
3739 		goto alts;
3740 	}
3741 
3742 	sym = reloc->sym;
3743 	offset = arch_insn_adjusted_addend(insn, reloc);
3744 
3745 	if (is_string_sec(sym->sec)) {
3746 		char *str;
3747 
3748 		str = sym->sec->data->d_buf + sym->offset + offset;
3749 		checksum_update(func, insn, str, strlen(str));
3750 		goto alts;
3751 	}
3752 
3753 	if (is_sec_sym(sym)) {
3754 		sym = find_symbol_containing(reloc->sym->sec, offset);
3755 		if (!sym)
3756 			goto alts;
3757 
3758 		offset -= sym->offset;
3759 	}
3760 
3761 	checksum_update(func, insn, sym->demangled_name, strlen(sym->demangled_name));
3762 	checksum_update(func, insn, &offset, sizeof(offset));
3763 
3764 alts:
3765 	for (alt = insn->alts; alt; alt = alt->next) {
3766 		struct alt_group *alt_group = alt->insn->alt_group;
3767 
3768 		/* Prevent __ex_table recursion, e.g. LOAD_SEGMENT() */
3769 		if (in_alt)
3770 			break;
3771 		in_alt = true;
3772 
3773 		checksum_update(func, insn, &alt->type, sizeof(alt->type));
3774 
3775 		if (alt_group && alt_group->orig_group) {
3776 			struct instruction *alt_insn;
3777 
3778 			checksum_update(func, insn, &alt_group->feature, sizeof(alt_group->feature));
3779 
3780 			for (alt_insn = alt->insn; alt_insn; alt_insn = next_insn_same_sec(file, alt_insn)) {
3781 				checksum_update_insn(file, func, alt_insn);
3782 				if (!alt_group->last_insn || alt_insn == alt_group->last_insn)
3783 					break;
3784 			}
3785 		} else {
3786 			checksum_update_insn(file, func, alt->insn);
3787 		}
3788 
3789 		in_alt = false;
3790 	}
3791 }
3792 
3793 static int calculate_checksums(struct objtool_file *file)
3794 {
3795 	struct instruction *insn;
3796 	struct symbol *func;
3797 
3798 	if (checksum_debug_init(file))
3799 		return -1;
3800 
3801 	for_each_sym(file->elf, func) {
3802 		/*
3803 		 * Skip cold subfunctions and aliases: they share the
3804 		 * parent's checksum via func_for_each_insn() which
3805 		 * follows func->cfunc into the cold subfunction.
3806 		 */
3807 		if (!is_func_sym(func) || is_cold_func(func) ||
3808 		    is_alias_sym(func) || !func->len)
3809 			continue;
3810 
3811 		checksum_init(func);
3812 
3813 		func_for_each_insn(file, func, insn)
3814 			checksum_update_insn(file, func, insn);
3815 
3816 		checksum_finish(func);
3817 	}
3818 	return 0;
3819 }
3820 #endif /* BUILD_KLP */
3821 
3822 static int validate_branch(struct objtool_file *file, struct symbol *func,
3823 			   struct instruction *insn, struct insn_state state);
3824 static int do_validate_branch(struct objtool_file *file, struct symbol *func,
3825 			      struct instruction *insn, struct insn_state *state);
3826 
3827 static int validate_insn(struct objtool_file *file, struct symbol *func,
3828 			 struct instruction *insn, struct insn_state *statep,
3829 			 struct instruction *prev_insn, struct instruction *next_insn,
3830 			 bool *dead_end)
3831 {
3832 	char *alt_name __maybe_unused = NULL;
3833 	struct alternative *alt;
3834 	u8 visited;
3835 	int ret;
3836 
3837 	/*
3838 	 * Any returns before the end of this function are effectively dead
3839 	 * ends, i.e. validate_branch() has reached the end of the branch.
3840 	 */
3841 	*dead_end = true;
3842 
3843 	visited = VISITED_BRANCH << statep->uaccess;
3844 	if (insn->visited & VISITED_BRANCH_MASK) {
3845 		if (!insn->hint && !insn_cfi_match(insn, &statep->cfi))
3846 			return 1;
3847 
3848 		if (insn->visited & visited) {
3849 			TRACE_INSN(insn, "already visited");
3850 			return 0;
3851 		}
3852 	} else {
3853 		nr_insns_visited++;
3854 	}
3855 
3856 	if (statep->noinstr)
3857 		statep->instr += insn->instr;
3858 
3859 	if (insn->hint) {
3860 		if (insn->restore) {
3861 			struct instruction *save_insn, *i;
3862 
3863 			i = insn;
3864 			save_insn = NULL;
3865 
3866 			sym_for_each_insn_continue_reverse(file, func, i) {
3867 				if (i->save) {
3868 					save_insn = i;
3869 					break;
3870 				}
3871 			}
3872 
3873 			if (!save_insn) {
3874 				WARN_INSN(insn, "no corresponding CFI save for CFI restore");
3875 				return 1;
3876 			}
3877 
3878 			if (!save_insn->visited) {
3879 				/*
3880 				 * If the restore hint insn is at the
3881 				 * beginning of a basic block and was
3882 				 * branched to from elsewhere, and the
3883 				 * save insn hasn't been visited yet,
3884 				 * defer following this branch for now.
3885 				 * It will be seen later via the
3886 				 * straight-line path.
3887 				 */
3888 				if (!prev_insn) {
3889 					TRACE_INSN(insn, "defer restore");
3890 					return 0;
3891 				}
3892 
3893 				WARN_INSN(insn, "objtool isn't smart enough to handle this CFI save/restore combo");
3894 				return 1;
3895 			}
3896 
3897 			insn->cfi = save_insn->cfi;
3898 			nr_cfi_reused++;
3899 		}
3900 
3901 		statep->cfi = *insn->cfi;
3902 	} else {
3903 		/* XXX track if we actually changed statep->cfi */
3904 
3905 		if (prev_insn && !cficmp(prev_insn->cfi, &statep->cfi)) {
3906 			insn->cfi = prev_insn->cfi;
3907 			nr_cfi_reused++;
3908 		} else {
3909 			insn->cfi = cfi_hash_find_or_add(&statep->cfi);
3910 		}
3911 	}
3912 
3913 	insn->visited |= visited;
3914 
3915 	if (propagate_alt_cfi(file, insn))
3916 		return 1;
3917 
3918 	if (insn->alts) {
3919 		for (alt = insn->alts; alt; alt = alt->next) {
3920 			TRACE_ALT_BEGIN(insn, alt, alt_name);
3921 			ret = validate_branch(file, func, alt->insn, *statep);
3922 			TRACE_ALT_END(insn, alt, alt_name);
3923 			if (ret) {
3924 				BT_INSN(insn, "(alt)");
3925 				return ret;
3926 			}
3927 		}
3928 		TRACE_ALT_INFO_NOADDR(insn, "/ ", "DEFAULT");
3929 	}
3930 
3931 	if (skip_alt_group(insn))
3932 		return 0;
3933 
3934 	if (handle_insn_ops(insn, next_insn, statep))
3935 		return 1;
3936 
3937 	switch (insn->type) {
3938 
3939 	case INSN_RETURN:
3940 		TRACE_INSN(insn, "return");
3941 		return validate_return(func, insn, statep);
3942 
3943 	case INSN_CALL:
3944 	case INSN_CALL_DYNAMIC:
3945 		if (insn->type == INSN_CALL)
3946 			TRACE_INSN(insn, "call");
3947 		else
3948 			TRACE_INSN(insn, "indirect call");
3949 
3950 		ret = validate_call(file, insn, statep);
3951 		if (ret)
3952 			return ret;
3953 
3954 		if (opts.stackval && func && !is_special_call(insn) &&
3955 		    !has_valid_stack_frame(statep)) {
3956 			WARN_INSN(insn, "call without frame pointer save/setup");
3957 			return 1;
3958 		}
3959 
3960 		break;
3961 
3962 	case INSN_JUMP_CONDITIONAL:
3963 	case INSN_JUMP_UNCONDITIONAL:
3964 		if (is_sibling_call(insn)) {
3965 			TRACE_INSN(insn, "sibling call");
3966 			ret = validate_sibling_call(file, insn, statep);
3967 			if (ret)
3968 				return ret;
3969 
3970 		} else if (insn->jump_dest) {
3971 			if (insn->type == INSN_JUMP_UNCONDITIONAL)
3972 				TRACE_INSN(insn, "unconditional jump");
3973 			else
3974 				TRACE_INSN(insn, "jump taken");
3975 
3976 			ret = validate_branch(file, func, insn->jump_dest, *statep);
3977 			if (ret) {
3978 				BT_INSN(insn, "(branch)");
3979 				return ret;
3980 			}
3981 		}
3982 
3983 		if (insn->type == INSN_JUMP_UNCONDITIONAL)
3984 			return 0;
3985 
3986 		TRACE_INSN(insn, "jump not taken");
3987 		break;
3988 
3989 	case INSN_JUMP_DYNAMIC:
3990 	case INSN_JUMP_DYNAMIC_CONDITIONAL:
3991 		TRACE_INSN(insn, "indirect jump");
3992 		if (is_sibling_call(insn)) {
3993 			ret = validate_sibling_call(file, insn, statep);
3994 			if (ret)
3995 				return ret;
3996 		}
3997 
3998 		if (insn->type == INSN_JUMP_DYNAMIC)
3999 			return 0;
4000 
4001 		break;
4002 
4003 	case INSN_SYSCALL:
4004 		TRACE_INSN(insn, "syscall");
4005 		if (func && (!next_insn || !next_insn->hint)) {
4006 			WARN_INSN(insn, "unsupported instruction in callable function");
4007 			return 1;
4008 		}
4009 
4010 		break;
4011 
4012 	case INSN_SYSRET:
4013 		TRACE_INSN(insn, "sysret");
4014 		if (func && (!next_insn || !next_insn->hint)) {
4015 			WARN_INSN(insn, "unsupported instruction in callable function");
4016 			return 1;
4017 		}
4018 
4019 		return 0;
4020 
4021 	case INSN_STAC:
4022 		TRACE_INSN(insn, "stac");
4023 		if (!opts.uaccess)
4024 			break;
4025 
4026 		if (statep->uaccess) {
4027 			WARN_INSN(insn, "recursive UACCESS enable");
4028 			return 1;
4029 		}
4030 
4031 		statep->uaccess = true;
4032 		break;
4033 
4034 	case INSN_CLAC:
4035 		TRACE_INSN(insn, "clac");
4036 		if (!opts.uaccess)
4037 			break;
4038 
4039 		if (!statep->uaccess && func) {
4040 			WARN_INSN(insn, "redundant UACCESS disable");
4041 			return 1;
4042 		}
4043 
4044 		if (func_uaccess_safe(func) && !statep->uaccess_stack) {
4045 			WARN_INSN(insn, "UACCESS-safe disables UACCESS");
4046 			return 1;
4047 		}
4048 
4049 		statep->uaccess = false;
4050 		break;
4051 
4052 	case INSN_STD:
4053 		TRACE_INSN(insn, "std");
4054 		if (statep->df) {
4055 			WARN_INSN(insn, "recursive STD");
4056 			return 1;
4057 		}
4058 
4059 		statep->df = true;
4060 		break;
4061 
4062 	case INSN_CLD:
4063 		TRACE_INSN(insn, "cld");
4064 		if (!statep->df && func) {
4065 			WARN_INSN(insn, "redundant CLD");
4066 			return 1;
4067 		}
4068 
4069 		statep->df = false;
4070 		break;
4071 
4072 	default:
4073 		break;
4074 	}
4075 
4076 	if (insn->dead_end)
4077 		TRACE_INSN(insn, "dead end");
4078 
4079 	*dead_end = insn->dead_end;
4080 	return 0;
4081 }
4082 
4083 /*
4084  * Follow the branch starting at the given instruction, and recursively follow
4085  * any other branches (jumps).  Meanwhile, track the frame pointer state at
4086  * each instruction and validate all the rules described in
4087  * tools/objtool/Documentation/objtool.txt.
4088  */
4089 static int do_validate_branch(struct objtool_file *file, struct symbol *func,
4090 			      struct instruction *insn, struct insn_state *state)
4091 {
4092 	struct instruction *next_insn, *prev_insn = NULL;
4093 	bool dead_end;
4094 	int ret;
4095 
4096 	if (func && func->ignore)
4097 		return 0;
4098 
4099 	do {
4100 		insn->trace = 0;
4101 		next_insn = next_insn_to_validate(file, insn);
4102 
4103 		if (func && insn_func(insn) && func != insn_func(insn)->pfunc) {
4104 			/* Ignore KCFI type preambles, which always fall through */
4105 			if (is_prefix_func(func))
4106 				return 0;
4107 
4108 			if (file->ignore_unreachables)
4109 				return 0;
4110 
4111 			WARN("%s() falls through to next function %s()",
4112 			     func->name, insn_func(insn)->name);
4113 			func->warned = 1;
4114 
4115 			return 1;
4116 		}
4117 
4118 		ret = validate_insn(file, func, insn, state, prev_insn, next_insn,
4119 				    &dead_end);
4120 
4121 		if (!insn->trace) {
4122 			if (ret)
4123 				TRACE_INSN(insn, "warning (%d)", ret);
4124 			else
4125 				TRACE_INSN(insn, NULL);
4126 		}
4127 
4128 		if (!dead_end && !next_insn) {
4129 			if (state->cfi.cfa.base == CFI_UNDEFINED)
4130 				return 0;
4131 			if (file->ignore_unreachables)
4132 				return 0;
4133 
4134 			WARN("%s%sunexpected end of section %s",
4135 			     func ? func->name : "", func ? "(): " : "",
4136 			     insn->sec->name);
4137 			return 1;
4138 		}
4139 
4140 		prev_insn = insn;
4141 		insn = next_insn;
4142 
4143 	} while (!dead_end);
4144 
4145 	return ret;
4146 }
4147 
4148 static int validate_branch(struct objtool_file *file, struct symbol *func,
4149 			   struct instruction *insn, struct insn_state state)
4150 {
4151 	int ret;
4152 
4153 	trace_depth_inc();
4154 	ret = do_validate_branch(file, func, insn, &state);
4155 	trace_depth_dec();
4156 
4157 	return ret;
4158 }
4159 
4160 static int validate_unwind_hint(struct objtool_file *file,
4161 				  struct instruction *insn,
4162 				  struct insn_state *state)
4163 {
4164 	if (insn->hint && !insn->visited) {
4165 		struct symbol *func = insn_func(insn);
4166 		int ret;
4167 
4168 		ret = validate_branch(file, func, insn, *state);
4169 		if (ret)
4170 			BT_INSN(insn, "<=== (hint)");
4171 		return ret;
4172 	}
4173 
4174 	return 0;
4175 }
4176 
4177 static int validate_unwind_hints(struct objtool_file *file, struct section *sec)
4178 {
4179 	struct instruction *insn;
4180 	struct insn_state state;
4181 	int warnings = 0;
4182 
4183 	if (!file->hints)
4184 		return 0;
4185 
4186 	init_insn_state(file, &state, sec);
4187 
4188 	if (sec) {
4189 		sec_for_each_insn(file, sec, insn)
4190 			warnings += validate_unwind_hint(file, insn, &state);
4191 	} else {
4192 		for_each_insn(file, insn)
4193 			warnings += validate_unwind_hint(file, insn, &state);
4194 	}
4195 
4196 	return warnings;
4197 }
4198 
4199 /*
4200  * Validate rethunk entry constraint: must untrain RET before the first RET.
4201  *
4202  * Follow every branch (intra-function) and ensure VALIDATE_UNRET_END comes
4203  * before an actual RET instruction.
4204  */
4205 static int validate_unret(struct objtool_file *file, struct instruction *insn)
4206 {
4207 	struct instruction *next, *dest;
4208 	int ret;
4209 
4210 	for (;;) {
4211 		next = next_insn_to_validate(file, insn);
4212 
4213 		if (insn->visited & VISITED_UNRET)
4214 			return 0;
4215 
4216 		insn->visited |= VISITED_UNRET;
4217 
4218 		if (insn->alts) {
4219 			struct alternative *alt;
4220 			for (alt = insn->alts; alt; alt = alt->next) {
4221 				ret = validate_unret(file, alt->insn);
4222 				if (ret) {
4223 					BT_INSN(insn, "(alt)");
4224 					return ret;
4225 				}
4226 			}
4227 		}
4228 
4229 		switch (insn->type) {
4230 
4231 		case INSN_CALL_DYNAMIC:
4232 		case INSN_JUMP_DYNAMIC:
4233 		case INSN_JUMP_DYNAMIC_CONDITIONAL:
4234 			WARN_INSN(insn, "early indirect call");
4235 			return 1;
4236 
4237 		case INSN_JUMP_UNCONDITIONAL:
4238 		case INSN_JUMP_CONDITIONAL:
4239 			if (!is_sibling_call(insn)) {
4240 				if (!insn->jump_dest) {
4241 					WARN_INSN(insn, "unresolved jump target after linking?!?");
4242 					return 1;
4243 				}
4244 				ret = validate_unret(file, insn->jump_dest);
4245 				if (ret) {
4246 					BT_INSN(insn, "(branch%s)",
4247 						insn->type == INSN_JUMP_CONDITIONAL ? "-cond" : "");
4248 					return ret;
4249 				}
4250 
4251 				if (insn->type == INSN_JUMP_UNCONDITIONAL)
4252 					return 0;
4253 
4254 				break;
4255 			}
4256 
4257 			/* fallthrough */
4258 		case INSN_CALL:
4259 			dest = find_insn(file, insn_call_dest(insn)->sec,
4260 					 insn_call_dest(insn)->offset);
4261 			if (!dest) {
4262 				WARN("Unresolved function after linking!?: %s",
4263 				     insn_call_dest(insn)->name);
4264 				return 1;
4265 			}
4266 
4267 			ret = validate_unret(file, dest);
4268 			if (ret) {
4269 				BT_INSN(insn, "(call)");
4270 				return ret;
4271 			}
4272 			/*
4273 			 * If a call returns without error, it must have seen UNTRAIN_RET.
4274 			 * Therefore any non-error return is a success.
4275 			 */
4276 			return 0;
4277 
4278 		case INSN_RETURN:
4279 			WARN_INSN(insn, "RET before UNTRAIN");
4280 			return 1;
4281 
4282 		case INSN_SYSCALL:
4283 			break;
4284 
4285 		case INSN_SYSRET:
4286 			return 0;
4287 
4288 		case INSN_NOP:
4289 			if (insn->retpoline_safe)
4290 				return 0;
4291 			break;
4292 
4293 		default:
4294 			break;
4295 		}
4296 
4297 		if (insn->dead_end)
4298 			return 0;
4299 
4300 		if (!next) {
4301 			WARN_INSN(insn, "teh end!");
4302 			return 1;
4303 		}
4304 		insn = next;
4305 	}
4306 
4307 	return 0;
4308 }
4309 
4310 /*
4311  * Validate that all branches starting at VALIDATE_UNRET_BEGIN encounter
4312  * VALIDATE_UNRET_END before RET.
4313  */
4314 static int validate_unrets(struct objtool_file *file)
4315 {
4316 	struct instruction *insn;
4317 	int warnings = 0;
4318 
4319 	for_each_insn(file, insn) {
4320 		if (!insn->unret)
4321 			continue;
4322 
4323 		warnings += validate_unret(file, insn);
4324 	}
4325 
4326 	return warnings;
4327 }
4328 
4329 static int validate_retpoline(struct objtool_file *file)
4330 {
4331 	struct instruction *insn;
4332 	int warnings = 0;
4333 
4334 	for_each_insn(file, insn) {
4335 		if (insn->type != INSN_JUMP_DYNAMIC &&
4336 		    insn->type != INSN_CALL_DYNAMIC &&
4337 		    insn->type != INSN_RETURN)
4338 			continue;
4339 
4340 		if (insn->retpoline_safe)
4341 			continue;
4342 
4343 		if (insn->sec->init)
4344 			continue;
4345 
4346 		if (insn->type == INSN_RETURN) {
4347 			if (opts.rethunk) {
4348 				WARN_INSN(insn, "'naked' return found in MITIGATION_RETHUNK build");
4349 				warnings++;
4350 			}
4351 			continue;
4352 		}
4353 
4354 		WARN_INSN(insn, "indirect %s found in MITIGATION_RETPOLINE build",
4355 			  insn->type == INSN_JUMP_DYNAMIC ? "jump" : "call");
4356 		warnings++;
4357 	}
4358 
4359 	if (!opts.cfi)
4360 		return warnings;
4361 
4362 	/*
4363 	 * kCFI call sites look like:
4364 	 *
4365 	 *     movl $(-0x12345678), %r10d
4366 	 *     addl -4(%r11), %r10d
4367 	 *     jz 1f
4368 	 *     ud2
4369 	 *  1: cs call __x86_indirect_thunk_r11
4370 	 *
4371 	 * Verify all indirect calls are kCFI adorned by checking for the
4372 	 * UD2. Notably, doing __nocfi calls to regular (cfi) functions is
4373 	 * broken.
4374 	 */
4375 	list_for_each_entry(insn, &file->retpoline_call_list, call_node) {
4376 		struct symbol *sym = insn->sym;
4377 
4378 		if (sym && (is_notype_sym(sym) ||
4379 			    is_func_sym(sym)) && !sym->nocfi) {
4380 			struct instruction *prev =
4381 				prev_insn_same_sym(file, insn);
4382 
4383 			if (!prev || prev->type != INSN_BUG) {
4384 				WARN_INSN(insn, "no-cfi indirect call!");
4385 				warnings++;
4386 			}
4387 		}
4388 	}
4389 
4390 	return warnings;
4391 }
4392 
4393 static bool is_kasan_insn(struct instruction *insn)
4394 {
4395 	return (insn->type == INSN_CALL &&
4396 		!strcmp(insn_call_dest(insn)->name, "__asan_handle_no_return"));
4397 }
4398 
4399 static bool is_ubsan_insn(struct instruction *insn)
4400 {
4401 	return (insn->type == INSN_CALL &&
4402 		!strcmp(insn_call_dest(insn)->name,
4403 			"__ubsan_handle_builtin_unreachable"));
4404 }
4405 
4406 static bool ignore_unreachable_insn(struct objtool_file *file, struct instruction *insn)
4407 {
4408 	struct symbol *func = insn_func(insn);
4409 	struct instruction *prev_insn;
4410 	int i;
4411 
4412 	if (insn->type == INSN_NOP || insn->type == INSN_TRAP ||
4413 	    insn->hole || (func && func->ignore))
4414 		return true;
4415 
4416 	/*
4417 	 * Ignore alternative replacement instructions.  This can happen
4418 	 * when a whitelisted function uses one of the ALTERNATIVE macros.
4419 	 */
4420 	if (!strcmp(insn->sec->name, ".altinstr_replacement") ||
4421 	    !strcmp(insn->sec->name, ".altinstr_aux"))
4422 		return true;
4423 
4424 	if (!func)
4425 		return false;
4426 
4427 	if (func->static_call_tramp)
4428 		return true;
4429 
4430 	/*
4431 	 * CONFIG_UBSAN_TRAP inserts a UD2 when it sees
4432 	 * __builtin_unreachable().  The BUG() macro has an unreachable() after
4433 	 * the UD2, which causes GCC's undefined trap logic to emit another UD2
4434 	 * (or occasionally a JMP to UD2).
4435 	 *
4436 	 * It may also insert a UD2 after calling a __noreturn function.
4437 	 */
4438 	prev_insn = prev_insn_same_sec(file, insn);
4439 	if (prev_insn && prev_insn->dead_end &&
4440 	    (insn->type == INSN_BUG ||
4441 	     (insn->type == INSN_JUMP_UNCONDITIONAL &&
4442 	      insn->jump_dest && insn->jump_dest->type == INSN_BUG)))
4443 		return true;
4444 
4445 	/*
4446 	 * Check if this (or a subsequent) instruction is related to
4447 	 * CONFIG_UBSAN or CONFIG_KASAN.
4448 	 *
4449 	 * End the search at 5 instructions to avoid going into the weeds.
4450 	 */
4451 	for (i = 0; i < 5; i++) {
4452 
4453 		if (is_kasan_insn(insn) || is_ubsan_insn(insn))
4454 			return true;
4455 
4456 		if (insn->type == INSN_JUMP_UNCONDITIONAL) {
4457 			if (insn->jump_dest &&
4458 			    insn_func(insn->jump_dest) == func) {
4459 				insn = insn->jump_dest;
4460 				continue;
4461 			}
4462 
4463 			break;
4464 		}
4465 
4466 		if (insn->offset + insn->len >= func->offset + func->len)
4467 			break;
4468 
4469 		insn = next_insn_same_sec(file, insn);
4470 	}
4471 
4472 	return false;
4473 }
4474 
4475 /*
4476  * For FineIBT or kCFI, a certain number of bytes preceding the function may be
4477  * NOPs.  Those NOPs may be rewritten at runtime and executed, so give them a
4478  * proper function name: __pfx_<func>.
4479  *
4480  * The NOPs may not exist for the following cases:
4481  *
4482  *   - compiler cloned functions (*.cold, *.part0, etc)
4483  *   - asm functions created with inline asm or without SYM_FUNC_START()
4484  *
4485  * Also, the function may already have a prefix from a previous objtool run
4486  * (livepatch extracted functions, or manually running objtool multiple times).
4487  *
4488  * So return 0 if the NOPs are missing or the function already has a prefix
4489  * symbol.
4490  */
4491 static int create_prefix_symbol(struct objtool_file *file, struct symbol *func)
4492 {
4493 	struct instruction *insn, *prev;
4494 	char name[SYM_NAME_LEN];
4495 	struct cfi_state *cfi;
4496 
4497 	if (!is_func_sym(func) || is_prefix_func(func) || is_cold_func(func) ||
4498 	    func->static_call_tramp)
4499 		return 0;
4500 
4501 	if ((strlen(func->name) + sizeof("__pfx_") > SYM_NAME_LEN)) {
4502 		WARN("%s: symbol name too long, can't create __pfx_ symbol",
4503 		      func->name);
4504 		return 0;
4505 	}
4506 
4507 	if (snprintf_check(name, SYM_NAME_LEN, "__pfx_%s", func->name))
4508 		return -1;
4509 
4510 	if (file->klp) {
4511 		struct symbol *pfx;
4512 
4513 		pfx = find_symbol_by_offset(func->sec, func->offset - opts.prefix);
4514 		if (pfx && is_prefix_func(pfx) && !strcmp(pfx->name, name))
4515 			return 0;
4516 	}
4517 
4518 	insn = find_insn(file, func->sec, func->offset);
4519 	if (!insn) {
4520 		WARN("%s: can't find starting instruction", func->name);
4521 		return -1;
4522 	}
4523 
4524 	for (prev = prev_insn_same_sec(file, insn);
4525 	     prev;
4526 	     prev = prev_insn_same_sec(file, prev)) {
4527 		u64 offset;
4528 
4529 		if (prev->type != INSN_NOP)
4530 			return 0;
4531 
4532 		offset = func->offset - prev->offset;
4533 
4534 		if (offset > opts.prefix)
4535 			return 0;
4536 
4537 		if (offset < opts.prefix)
4538 			continue;
4539 
4540 		if (!elf_create_symbol(file->elf, name, func->sec,
4541 				       GELF_ST_BIND(func->sym.st_info),
4542 				       GELF_ST_TYPE(func->sym.st_info),
4543 				       prev->offset, opts.prefix))
4544 			return -1;
4545 
4546 		break;
4547 	}
4548 
4549 	if (!prev)
4550 		return 0;
4551 
4552 	if (!insn->cfi) {
4553 		/*
4554 		 * This can happen if stack validation isn't enabled or the
4555 		 * function is annotated with STACK_FRAME_NON_STANDARD.
4556 		 */
4557 		return 0;
4558 	}
4559 
4560 	/* Propagate insn->cfi to the prefix code */
4561 	cfi = cfi_hash_find_or_add(insn->cfi);
4562 	for (; prev != insn; prev = next_insn_same_sec(file, prev))
4563 		prev->cfi = cfi;
4564 
4565 	return 0;
4566 }
4567 
4568 static int create_prefix_symbols(struct objtool_file *file)
4569 {
4570 	struct section *sec;
4571 	struct symbol *func;
4572 
4573 	for_each_sec(file->elf, sec) {
4574 		if (!is_text_sec(sec))
4575 			continue;
4576 
4577 		sec_for_each_sym(sec, func) {
4578 			if (create_prefix_symbol(file, func))
4579 				return -1;
4580 		}
4581 	}
4582 
4583 	return 0;
4584 }
4585 
4586 static int validate_symbol(struct objtool_file *file, struct section *sec,
4587 			   struct symbol *sym, struct insn_state *state)
4588 {
4589 	struct instruction *insn;
4590 	struct symbol *func;
4591 	int ret;
4592 
4593 	if (!sym->len) {
4594 		WARN("%s() is missing an ELF size annotation", sym->name);
4595 		return 1;
4596 	}
4597 
4598 	if (sym->pfunc != sym || is_alias_sym(sym))
4599 		return 0;
4600 
4601 	insn = find_insn(file, sec, sym->offset);
4602 	if (!insn || insn->visited)
4603 		return 0;
4604 
4605 	if (opts.uaccess)
4606 		state->uaccess = sym->uaccess_safe;
4607 
4608 	func = insn_func(insn);
4609 
4610 	if (opts.trace && !fnmatch(opts.trace, sym->name, 0)) {
4611 		trace_enable();
4612 		TRACE("%s: validation begin\n", sym->name);
4613 	}
4614 
4615 	ret = validate_branch(file, func, insn, *state);
4616 	if (ret)
4617 		BT_INSN(insn, "<=== (sym)");
4618 
4619 	TRACE("%s: validation %s\n\n", sym->name, ret ? "failed" : "end");
4620 	trace_disable();
4621 
4622 	return ret;
4623 }
4624 
4625 static int validate_section(struct objtool_file *file, struct section *sec)
4626 {
4627 	struct insn_state state;
4628 	struct symbol *func;
4629 	int warnings = 0;
4630 
4631 	sec_for_each_sym(sec, func) {
4632 		if (!is_func_sym(func))
4633 			continue;
4634 
4635 		init_insn_state(file, &state, sec);
4636 		set_func_state(&state.cfi);
4637 
4638 		warnings += validate_symbol(file, sec, func, &state);
4639 	}
4640 
4641 	return warnings;
4642 }
4643 
4644 static int validate_noinstr_sections(struct objtool_file *file)
4645 {
4646 	struct section *sec;
4647 	int warnings = 0;
4648 
4649 	sec = find_section_by_name(file->elf, ".noinstr.text");
4650 	if (sec) {
4651 		warnings += validate_section(file, sec);
4652 		warnings += validate_unwind_hints(file, sec);
4653 	}
4654 
4655 	sec = find_section_by_name(file->elf, ".entry.text");
4656 	if (sec) {
4657 		warnings += validate_section(file, sec);
4658 		warnings += validate_unwind_hints(file, sec);
4659 	}
4660 
4661 	sec = find_section_by_name(file->elf, ".cpuidle.text");
4662 	if (sec) {
4663 		warnings += validate_section(file, sec);
4664 		warnings += validate_unwind_hints(file, sec);
4665 	}
4666 
4667 	return warnings;
4668 }
4669 
4670 static int validate_functions(struct objtool_file *file)
4671 {
4672 	struct section *sec;
4673 	int warnings = 0;
4674 
4675 	for_each_sec(file->elf, sec) {
4676 		if (!is_text_sec(sec))
4677 			continue;
4678 
4679 		warnings += validate_section(file, sec);
4680 	}
4681 
4682 	return warnings;
4683 }
4684 
4685 static void mark_endbr_used(struct instruction *insn)
4686 {
4687 	if (!list_empty(&insn->call_node))
4688 		list_del_init(&insn->call_node);
4689 }
4690 
4691 static bool noendbr_range(struct objtool_file *file, struct instruction *insn)
4692 {
4693 	struct symbol *sym = find_symbol_containing(insn->sec, insn->offset-1);
4694 	struct instruction *first;
4695 
4696 	if (!sym)
4697 		return false;
4698 
4699 	first = find_insn(file, sym->sec, sym->offset);
4700 	if (!first)
4701 		return false;
4702 
4703 	if (first->type != INSN_ENDBR && !first->noendbr)
4704 		return false;
4705 
4706 	return insn->offset == sym->offset + sym->len;
4707 }
4708 
4709 static int __validate_ibt_insn(struct objtool_file *file, struct instruction *insn,
4710 			       struct instruction *dest)
4711 {
4712 	if (dest->type == INSN_ENDBR) {
4713 		mark_endbr_used(dest);
4714 		return 0;
4715 	}
4716 
4717 	if (insn_func(dest) && insn_func(insn) &&
4718 	    insn_func(dest)->pfunc == insn_func(insn)->pfunc) {
4719 		/*
4720 		 * Anything from->to self is either _THIS_IP_ or
4721 		 * IRET-to-self.
4722 		 *
4723 		 * There is no sane way to annotate _THIS_IP_ since the
4724 		 * compiler treats the relocation as a constant and is
4725 		 * happy to fold in offsets, skewing any annotation we
4726 		 * do, leading to vast amounts of false-positives.
4727 		 *
4728 		 * There's also compiler generated _THIS_IP_ through
4729 		 * KCOV and such which we have no hope of annotating.
4730 		 *
4731 		 * As such, blanket accept self-references without
4732 		 * issue.
4733 		 */
4734 		return 0;
4735 	}
4736 
4737 	/*
4738 	 * Accept anything ANNOTATE_NOENDBR.
4739 	 */
4740 	if (dest->noendbr)
4741 		return 0;
4742 
4743 	/*
4744 	 * Accept if this is the instruction after a symbol
4745 	 * that is (no)endbr -- typical code-range usage.
4746 	 */
4747 	if (noendbr_range(file, dest))
4748 		return 0;
4749 
4750 	WARN_INSN(insn, "relocation to !ENDBR: %s", offstr(dest->sec, dest->offset));
4751 	return 1;
4752 }
4753 
4754 static int validate_ibt_insn(struct objtool_file *file, struct instruction *insn)
4755 {
4756 	struct instruction *dest;
4757 	struct reloc *reloc;
4758 	unsigned long off;
4759 	int warnings = 0;
4760 
4761 	/*
4762 	 * Looking for function pointer load relocations.  Ignore
4763 	 * direct/indirect branches:
4764 	 */
4765 	switch (insn->type) {
4766 
4767 	case INSN_CALL:
4768 	case INSN_CALL_DYNAMIC:
4769 	case INSN_JUMP_CONDITIONAL:
4770 	case INSN_JUMP_UNCONDITIONAL:
4771 	case INSN_JUMP_DYNAMIC:
4772 	case INSN_JUMP_DYNAMIC_CONDITIONAL:
4773 	case INSN_RETURN:
4774 	case INSN_NOP:
4775 		return 0;
4776 
4777 	case INSN_LEA_RIP:
4778 		if (!insn_reloc(file, insn)) {
4779 			/* local function pointer reference without reloc */
4780 
4781 			off = arch_jump_destination(insn);
4782 
4783 			dest = find_insn(file, insn->sec, off);
4784 			if (!dest) {
4785 				WARN_INSN(insn, "corrupt function pointer reference");
4786 				return 1;
4787 			}
4788 
4789 			return __validate_ibt_insn(file, insn, dest);
4790 		}
4791 		break;
4792 
4793 	default:
4794 		break;
4795 	}
4796 
4797 	for (reloc = insn_reloc(file, insn);
4798 	     reloc;
4799 	     reloc = find_reloc_by_dest_range(file->elf, insn->sec,
4800 					      reloc_offset(reloc) + 1,
4801 					      (insn->offset + insn->len) - (reloc_offset(reloc) + 1))) {
4802 
4803 		off = reloc->sym->offset + arch_insn_adjusted_addend(insn, reloc);
4804 
4805 		dest = find_insn(file, reloc->sym->sec, off);
4806 		if (!dest)
4807 			continue;
4808 
4809 		warnings += __validate_ibt_insn(file, insn, dest);
4810 	}
4811 
4812 	return warnings;
4813 }
4814 
4815 static int validate_ibt_data_reloc(struct objtool_file *file,
4816 				   struct reloc *reloc)
4817 {
4818 	struct instruction *dest;
4819 
4820 	dest = find_insn(file, reloc->sym->sec,
4821 			 reloc->sym->offset + reloc_addend(reloc));
4822 	if (!dest)
4823 		return 0;
4824 
4825 	if (dest->type == INSN_ENDBR) {
4826 		mark_endbr_used(dest);
4827 		return 0;
4828 	}
4829 
4830 	if (dest->noendbr)
4831 		return 0;
4832 
4833 	WARN_FUNC(reloc->sec->base, reloc_offset(reloc),
4834 		  "data relocation to !ENDBR: %s", offstr(dest->sec, dest->offset));
4835 
4836 	return 1;
4837 }
4838 
4839 /*
4840  * Validate IBT rules and remove used ENDBR instructions from the seal list.
4841  * Unused ENDBR instructions will be annotated for sealing (i.e., replaced with
4842  * NOPs) later, in create_ibt_endbr_seal_sections().
4843  */
4844 static int validate_ibt(struct objtool_file *file)
4845 {
4846 	struct section *sec;
4847 	struct reloc *reloc;
4848 	struct instruction *insn;
4849 	int warnings = 0;
4850 
4851 	for_each_insn(file, insn)
4852 		warnings += validate_ibt_insn(file, insn);
4853 
4854 	for_each_sec(file->elf, sec) {
4855 
4856 		/* Already done by validate_ibt_insn() */
4857 		if (is_text_sec(sec))
4858 			continue;
4859 
4860 		if (!sec->rsec)
4861 			continue;
4862 
4863 		/*
4864 		 * These sections can reference text addresses, but not with
4865 		 * the intent to indirect branch to them.
4866 		 */
4867 		if ((!strncmp(sec->name, ".discard", 8) &&
4868 		     strcmp(sec->name, ".discard.ibt_endbr_noseal"))	||
4869 		    !strncmp(sec->name, ".debug", 6)			||
4870 		    !strcmp(sec->name, ".altinstructions")		||
4871 		    !strcmp(sec->name, ".ibt_endbr_seal")		||
4872 		    !strcmp(sec->name, ".kcfi_traps")			||
4873 		    !strcmp(sec->name, ".orc_unwind_ip")		||
4874 		    !strcmp(sec->name, ".retpoline_sites")		||
4875 		    !strcmp(sec->name, ".smp_locks")			||
4876 		    !strcmp(sec->name, ".static_call_sites")		||
4877 		    !strcmp(sec->name, "_error_injection_whitelist")	||
4878 		    !strcmp(sec->name, "_kprobe_blacklist")		||
4879 		    !strcmp(sec->name, "__bug_table")			||
4880 		    !strcmp(sec->name, "__ex_table")			||
4881 		    !strcmp(sec->name, "__jump_table")			||
4882 		    !strcmp(sec->name, ".init.klp_funcs")		||
4883 		    !strcmp(sec->name, "__mcount_loc")			||
4884 		    !strcmp(sec->name, ".llvm.call-graph-profile")	||
4885 		    !strcmp(sec->name, ".llvm_bb_addr_map")		||
4886 		    !strcmp(sec->name, "__tracepoints")			||
4887 		    !strcmp(sec->name, ".return_sites")			||
4888 		    !strcmp(sec->name, ".call_sites")			||
4889 		    !strcmp(sec->name, "__patchable_function_entries"))
4890 			continue;
4891 
4892 		for_each_reloc(sec->rsec, reloc)
4893 			warnings += validate_ibt_data_reloc(file, reloc);
4894 	}
4895 
4896 	return warnings;
4897 }
4898 
4899 static int validate_sls(struct objtool_file *file)
4900 {
4901 	struct instruction *insn, *next_insn;
4902 	int warnings = 0;
4903 
4904 	for_each_insn(file, insn) {
4905 		next_insn = next_insn_same_sec(file, insn);
4906 
4907 		if (insn->retpoline_safe)
4908 			continue;
4909 
4910 		switch (insn->type) {
4911 		case INSN_RETURN:
4912 			if (!next_insn || next_insn->type != INSN_TRAP) {
4913 				WARN_INSN(insn, "missing int3 after ret");
4914 				warnings++;
4915 			}
4916 
4917 			break;
4918 		case INSN_JUMP_DYNAMIC:
4919 			if (!next_insn || next_insn->type != INSN_TRAP) {
4920 				WARN_INSN(insn, "missing int3 after indirect jump");
4921 				warnings++;
4922 			}
4923 			break;
4924 		default:
4925 			break;
4926 		}
4927 	}
4928 
4929 	return warnings;
4930 }
4931 
4932 static int validate_reachable_instructions(struct objtool_file *file)
4933 {
4934 	struct instruction *insn, *prev_insn;
4935 	struct symbol *call_dest;
4936 	int warnings = 0;
4937 
4938 	if (file->ignore_unreachables)
4939 		return 0;
4940 
4941 	for_each_insn(file, insn) {
4942 		if (insn->visited || ignore_unreachable_insn(file, insn))
4943 			continue;
4944 
4945 		prev_insn = prev_insn_same_sec(file, insn);
4946 		if (prev_insn && prev_insn->dead_end) {
4947 			call_dest = insn_call_dest(prev_insn);
4948 			if (call_dest) {
4949 				WARN_INSN(insn, "%s() missing __noreturn in .c/.h or NORETURN() in noreturns.h",
4950 					  call_dest->name);
4951 				warnings++;
4952 				continue;
4953 			}
4954 		}
4955 
4956 		WARN_INSN(insn, "unreachable instruction");
4957 		warnings++;
4958 	}
4959 
4960 	return warnings;
4961 }
4962 
4963 __weak bool arch_absolute_reloc(struct elf *elf, struct reloc *reloc)
4964 {
4965 	unsigned int type = reloc_type(reloc);
4966 	size_t sz = elf_addr_size(elf);
4967 
4968 	return (sz == 8) ? (type == R_ABS64) : (type == R_ABS32);
4969 }
4970 
4971 static int check_abs_references(struct objtool_file *file)
4972 {
4973 	struct section *sec;
4974 	struct reloc *reloc;
4975 	int ret = 0;
4976 
4977 	for_each_sec(file->elf, sec) {
4978 		/* absolute references in non-loadable sections are fine */
4979 		if (!(sec->sh.sh_flags & SHF_ALLOC))
4980 			continue;
4981 
4982 		/* section must have an associated .rela section */
4983 		if (!sec->rsec)
4984 			continue;
4985 
4986 		/*
4987 		 * Special case for compiler generated metadata that is not
4988 		 * consumed until after boot.
4989 		 */
4990 		if (!strcmp(sec->name, "__patchable_function_entries"))
4991 			continue;
4992 
4993 		for_each_reloc(sec->rsec, reloc) {
4994 			if (arch_absolute_reloc(file->elf, reloc)) {
4995 				WARN("section %s has absolute relocation at offset 0x%llx",
4996 				     sec->name, (unsigned long long)reloc_offset(reloc));
4997 				ret++;
4998 			}
4999 		}
5000 	}
5001 	return ret;
5002 }
5003 
5004 struct insn_chunk {
5005 	void *addr;
5006 	struct insn_chunk *next;
5007 };
5008 
5009 /*
5010  * Reduce peak RSS usage by freeing insns memory before writing the ELF file,
5011  * which can trigger more allocations for .debug_* sections whose data hasn't
5012  * been read yet.
5013  */
5014 void free_insns(struct objtool_file *file)
5015 {
5016 	struct instruction *insn;
5017 	struct insn_chunk *chunks = NULL, *chunk;
5018 
5019 	for_each_insn(file, insn) {
5020 		if (!insn->idx) {
5021 			chunk = malloc(sizeof(*chunk));
5022 			chunk->addr = insn;
5023 			chunk->next = chunks;
5024 			chunks = chunk;
5025 		}
5026 	}
5027 
5028 	for (chunk = chunks; chunk; chunk = chunk->next)
5029 		free(chunk->addr);
5030 }
5031 
5032 const char *objtool_disas_insn(struct instruction *insn)
5033 {
5034 	struct disas_context *dctx = objtool_disas_ctx;
5035 
5036 	if (!dctx)
5037 		return "";
5038 
5039 	disas_insn(dctx, insn);
5040 	return disas_result(dctx);
5041 }
5042 
5043 int check(struct objtool_file *file)
5044 {
5045 	struct disas_context *disas_ctx = NULL;
5046 	int ret = 0, warnings = 0;
5047 
5048 	/*
5049 	 * Create a disassembly context if we might disassemble any
5050 	 * instruction or function.
5051 	 */
5052 	if (opts.verbose || opts.backtrace || opts.trace || opts.disas) {
5053 		disas_ctx = disas_context_create(file);
5054 		if (!disas_ctx) {
5055 			opts.disas = false;
5056 			opts.trace = false;
5057 		}
5058 		objtool_disas_ctx = disas_ctx;
5059 	}
5060 
5061 	ret = decode_file(file);
5062 	if (ret)
5063 		goto out;
5064 
5065 	if (!nr_insns)
5066 		goto out;
5067 
5068 	if (opts.retpoline)
5069 		warnings += validate_retpoline(file);
5070 
5071 	if (validate_branch_enabled()) {
5072 		int w = 0;
5073 
5074 		w += validate_functions(file);
5075 		w += validate_unwind_hints(file, NULL);
5076 		if (!w)
5077 			w += validate_reachable_instructions(file);
5078 
5079 		warnings += w;
5080 
5081 	} else if (opts.noinstr) {
5082 		warnings += validate_noinstr_sections(file);
5083 	}
5084 
5085 	if (opts.unret) {
5086 		/*
5087 		 * Must be after validate_branch() and friends, it plays
5088 		 * further games with insn->visited.
5089 		 */
5090 		warnings += validate_unrets(file);
5091 	}
5092 
5093 	if (opts.ibt)
5094 		warnings += validate_ibt(file);
5095 
5096 	if (opts.sls)
5097 		warnings += validate_sls(file);
5098 
5099 	if (opts.static_call) {
5100 		ret = create_static_call_sections(file);
5101 		if (ret)
5102 			goto out;
5103 	}
5104 
5105 	if (opts.retpoline) {
5106 		ret = create_retpoline_sites_sections(file);
5107 		if (ret)
5108 			goto out;
5109 	}
5110 
5111 	if (opts.cfi) {
5112 		ret = create_cfi_sections(file);
5113 		if (ret)
5114 			goto out;
5115 	}
5116 
5117 	if (opts.rethunk) {
5118 		ret = create_return_sites_sections(file);
5119 		if (ret)
5120 			goto out;
5121 
5122 		if (opts.hack_skylake) {
5123 			ret = create_direct_call_sections(file);
5124 			if (ret)
5125 				goto out;
5126 		}
5127 	}
5128 
5129 	if (opts.mcount) {
5130 		ret = create_mcount_loc_sections(file);
5131 		if (ret)
5132 			goto out;
5133 	}
5134 
5135 	if (opts.prefix) {
5136 		ret = create_prefix_symbols(file);
5137 		if (ret)
5138 			goto out;
5139 	}
5140 
5141 	if (opts.ibt) {
5142 		ret = create_ibt_endbr_seal_sections(file);
5143 		if (ret)
5144 			goto out;
5145 	}
5146 
5147 	if (opts.noabs)
5148 		warnings += check_abs_references(file);
5149 
5150 	if (opts.checksum) {
5151 		ret = calculate_checksums(file);
5152 		if (ret)
5153 			goto out;
5154 		ret = create_sym_checksum_section(file);
5155 		if (ret)
5156 			goto out;
5157 	}
5158 
5159 	if (opts.orc && nr_insns) {
5160 		ret = orc_create(file);
5161 		if (ret)
5162 			goto out;
5163 	}
5164 
5165 	if (opts.stats) {
5166 		printf("nr_insns_visited: %ld\n", nr_insns_visited);
5167 		printf("nr_cfi: %ld\n", nr_cfi);
5168 		printf("nr_cfi_reused: %ld\n", nr_cfi_reused);
5169 		printf("nr_cfi_cache: %ld\n", nr_cfi_cache);
5170 	}
5171 
5172 out:
5173 	if (ret || warnings) {
5174 		if (opts.werror && warnings)
5175 			ret = 1;
5176 
5177 		if (opts.verbose) {
5178 			if (opts.werror && warnings)
5179 				WARN("%d warning(s) upgraded to errors", warnings);
5180 			disas_warned_funcs(disas_ctx);
5181 		}
5182 	}
5183 
5184 	if (opts.disas)
5185 		disas_funcs(disas_ctx);
5186 
5187 	if (disas_ctx) {
5188 		disas_context_destroy(disas_ctx);
5189 		objtool_disas_ctx = NULL;
5190 	}
5191 
5192 	free_insns(file);
5193 
5194 	if (!ret && !warnings)
5195 		return 0;
5196 
5197 	if (opts.backup && make_backup())
5198 		return 1;
5199 
5200 	return ret;
5201 }
5202