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