objtool: Add STT_NOTYPE noinstr validation
[linux-2.6-microblaze.git] / tools / objtool / check.c
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
9 #include "builtin.h"
10 #include "check.h"
11 #include "elf.h"
12 #include "special.h"
13 #include "arch.h"
14 #include "warn.h"
15
16 #include <linux/hashtable.h>
17 #include <linux/kernel.h>
18
19 #define FAKE_JUMP_OFFSET -1
20
21 #define C_JUMP_TABLE_SECTION ".rodata..c_jump_table"
22
23 struct alternative {
24         struct list_head list;
25         struct instruction *insn;
26         bool skip_orig;
27 };
28
29 const char *objname;
30 struct cfi_init_state initial_func_cfi;
31
32 struct instruction *find_insn(struct objtool_file *file,
33                               struct section *sec, unsigned long offset)
34 {
35         struct instruction *insn;
36
37         hash_for_each_possible(file->insn_hash, insn, hash, sec_offset_hash(sec, offset)) {
38                 if (insn->sec == sec && insn->offset == offset)
39                         return insn;
40         }
41
42         return NULL;
43 }
44
45 static struct instruction *next_insn_same_sec(struct objtool_file *file,
46                                               struct instruction *insn)
47 {
48         struct instruction *next = list_next_entry(insn, list);
49
50         if (!next || &next->list == &file->insn_list || next->sec != insn->sec)
51                 return NULL;
52
53         return next;
54 }
55
56 static struct instruction *next_insn_same_func(struct objtool_file *file,
57                                                struct instruction *insn)
58 {
59         struct instruction *next = list_next_entry(insn, list);
60         struct symbol *func = insn->func;
61
62         if (!func)
63                 return NULL;
64
65         if (&next->list != &file->insn_list && next->func == func)
66                 return next;
67
68         /* Check if we're already in the subfunction: */
69         if (func == func->cfunc)
70                 return NULL;
71
72         /* Move to the subfunction: */
73         return find_insn(file, func->cfunc->sec, func->cfunc->offset);
74 }
75
76 #define func_for_each_insn(file, func, insn)                            \
77         for (insn = find_insn(file, func->sec, func->offset);           \
78              insn;                                                      \
79              insn = next_insn_same_func(file, insn))
80
81 #define sym_for_each_insn(file, sym, insn)                              \
82         for (insn = find_insn(file, sym->sec, sym->offset);             \
83              insn && &insn->list != &file->insn_list &&                 \
84                 insn->sec == sym->sec &&                                \
85                 insn->offset < sym->offset + sym->len;                  \
86              insn = list_next_entry(insn, list))
87
88 #define sym_for_each_insn_continue_reverse(file, sym, insn)             \
89         for (insn = list_prev_entry(insn, list);                        \
90              &insn->list != &file->insn_list &&                         \
91                 insn->sec == sym->sec && insn->offset >= sym->offset;   \
92              insn = list_prev_entry(insn, list))
93
94 #define sec_for_each_insn_from(file, insn)                              \
95         for (; insn; insn = next_insn_same_sec(file, insn))
96
97 #define sec_for_each_insn_continue(file, insn)                          \
98         for (insn = next_insn_same_sec(file, insn); insn;               \
99              insn = next_insn_same_sec(file, insn))
100
101 static bool is_static_jump(struct instruction *insn)
102 {
103         return insn->type == INSN_JUMP_CONDITIONAL ||
104                insn->type == INSN_JUMP_UNCONDITIONAL;
105 }
106
107 static bool is_sibling_call(struct instruction *insn)
108 {
109         /* An indirect jump is either a sibling call or a jump to a table. */
110         if (insn->type == INSN_JUMP_DYNAMIC)
111                 return list_empty(&insn->alts);
112
113         if (!is_static_jump(insn))
114                 return false;
115
116         /* add_jump_destinations() sets insn->call_dest for sibling calls. */
117         return !!insn->call_dest;
118 }
119
120 /*
121  * This checks to see if the given function is a "noreturn" function.
122  *
123  * For global functions which are outside the scope of this object file, we
124  * have to keep a manual list of them.
125  *
126  * For local functions, we have to detect them manually by simply looking for
127  * the lack of a return instruction.
128  */
129 static bool __dead_end_function(struct objtool_file *file, struct symbol *func,
130                                 int recursion)
131 {
132         int i;
133         struct instruction *insn;
134         bool empty = true;
135
136         /*
137          * Unfortunately these have to be hard coded because the noreturn
138          * attribute isn't provided in ELF data.
139          */
140         static const char * const global_noreturns[] = {
141                 "__stack_chk_fail",
142                 "panic",
143                 "do_exit",
144                 "do_task_dead",
145                 "__module_put_and_exit",
146                 "complete_and_exit",
147                 "__reiserfs_panic",
148                 "lbug_with_loc",
149                 "fortify_panic",
150                 "usercopy_abort",
151                 "machine_real_restart",
152                 "rewind_stack_do_exit",
153                 "kunit_try_catch_throw",
154         };
155
156         if (!func)
157                 return false;
158
159         if (func->bind == STB_WEAK)
160                 return false;
161
162         if (func->bind == STB_GLOBAL)
163                 for (i = 0; i < ARRAY_SIZE(global_noreturns); i++)
164                         if (!strcmp(func->name, global_noreturns[i]))
165                                 return true;
166
167         if (!func->len)
168                 return false;
169
170         insn = find_insn(file, func->sec, func->offset);
171         if (!insn->func)
172                 return false;
173
174         func_for_each_insn(file, func, insn) {
175                 empty = false;
176
177                 if (insn->type == INSN_RETURN)
178                         return false;
179         }
180
181         if (empty)
182                 return false;
183
184         /*
185          * A function can have a sibling call instead of a return.  In that
186          * case, the function's dead-end status depends on whether the target
187          * of the sibling call returns.
188          */
189         func_for_each_insn(file, func, insn) {
190                 if (is_sibling_call(insn)) {
191                         struct instruction *dest = insn->jump_dest;
192
193                         if (!dest)
194                                 /* sibling call to another file */
195                                 return false;
196
197                         /* local sibling call */
198                         if (recursion == 5) {
199                                 /*
200                                  * Infinite recursion: two functions have
201                                  * sibling calls to each other.  This is a very
202                                  * rare case.  It means they aren't dead ends.
203                                  */
204                                 return false;
205                         }
206
207                         return __dead_end_function(file, dest->func, recursion+1);
208                 }
209         }
210
211         return true;
212 }
213
214 static bool dead_end_function(struct objtool_file *file, struct symbol *func)
215 {
216         return __dead_end_function(file, func, 0);
217 }
218
219 static void init_cfi_state(struct cfi_state *cfi)
220 {
221         int i;
222
223         for (i = 0; i < CFI_NUM_REGS; i++) {
224                 cfi->regs[i].base = CFI_UNDEFINED;
225                 cfi->vals[i].base = CFI_UNDEFINED;
226         }
227         cfi->cfa.base = CFI_UNDEFINED;
228         cfi->drap_reg = CFI_UNDEFINED;
229         cfi->drap_offset = -1;
230 }
231
232 static void init_insn_state(struct insn_state *state, struct section *sec)
233 {
234         memset(state, 0, sizeof(*state));
235         init_cfi_state(&state->cfi);
236
237         /*
238          * We need the full vmlinux for noinstr validation, otherwise we can
239          * not correctly determine insn->call_dest->sec (external symbols do
240          * not have a section).
241          */
242         if (vmlinux && sec)
243                 state->noinstr = sec->noinstr;
244 }
245
246 /*
247  * Call the arch-specific instruction decoder for all the instructions and add
248  * them to the global instruction list.
249  */
250 static int decode_instructions(struct objtool_file *file)
251 {
252         struct section *sec;
253         struct symbol *func;
254         unsigned long offset;
255         struct instruction *insn;
256         unsigned long nr_insns = 0;
257         int ret;
258
259         for_each_sec(file, sec) {
260
261                 if (!(sec->sh.sh_flags & SHF_EXECINSTR))
262                         continue;
263
264                 if (strcmp(sec->name, ".altinstr_replacement") &&
265                     strcmp(sec->name, ".altinstr_aux") &&
266                     strncmp(sec->name, ".discard.", 9))
267                         sec->text = true;
268
269                 if (!strcmp(sec->name, ".noinstr.text"))
270                         sec->noinstr = true;
271
272                 for (offset = 0; offset < sec->len; offset += insn->len) {
273                         insn = malloc(sizeof(*insn));
274                         if (!insn) {
275                                 WARN("malloc failed");
276                                 return -1;
277                         }
278                         memset(insn, 0, sizeof(*insn));
279                         INIT_LIST_HEAD(&insn->alts);
280                         INIT_LIST_HEAD(&insn->stack_ops);
281                         init_cfi_state(&insn->cfi);
282
283                         insn->sec = sec;
284                         insn->offset = offset;
285
286                         ret = arch_decode_instruction(file->elf, sec, offset,
287                                                       sec->len - offset,
288                                                       &insn->len, &insn->type,
289                                                       &insn->immediate,
290                                                       &insn->stack_ops);
291                         if (ret)
292                                 goto err;
293
294                         hash_add(file->insn_hash, &insn->hash, sec_offset_hash(sec, insn->offset));
295                         list_add_tail(&insn->list, &file->insn_list);
296                         nr_insns++;
297                 }
298
299                 list_for_each_entry(func, &sec->symbol_list, list) {
300                         if (func->type != STT_FUNC || func->alias != func)
301                                 continue;
302
303                         if (!find_insn(file, sec, func->offset)) {
304                                 WARN("%s(): can't find starting instruction",
305                                      func->name);
306                                 return -1;
307                         }
308
309                         sym_for_each_insn(file, func, insn)
310                                 insn->func = func;
311                 }
312         }
313
314         if (stats)
315                 printf("nr_insns: %lu\n", nr_insns);
316
317         return 0;
318
319 err:
320         free(insn);
321         return ret;
322 }
323
324 /*
325  * Mark "ud2" instructions and manually annotated dead ends.
326  */
327 static int add_dead_ends(struct objtool_file *file)
328 {
329         struct section *sec;
330         struct rela *rela;
331         struct instruction *insn;
332         bool found;
333
334         /*
335          * By default, "ud2" is a dead end unless otherwise annotated, because
336          * GCC 7 inserts it for certain divide-by-zero cases.
337          */
338         for_each_insn(file, insn)
339                 if (insn->type == INSN_BUG)
340                         insn->dead_end = true;
341
342         /*
343          * Check for manually annotated dead ends.
344          */
345         sec = find_section_by_name(file->elf, ".rela.discard.unreachable");
346         if (!sec)
347                 goto reachable;
348
349         list_for_each_entry(rela, &sec->rela_list, list) {
350                 if (rela->sym->type != STT_SECTION) {
351                         WARN("unexpected relocation symbol type in %s", sec->name);
352                         return -1;
353                 }
354                 insn = find_insn(file, rela->sym->sec, rela->addend);
355                 if (insn)
356                         insn = list_prev_entry(insn, list);
357                 else if (rela->addend == rela->sym->sec->len) {
358                         found = false;
359                         list_for_each_entry_reverse(insn, &file->insn_list, list) {
360                                 if (insn->sec == rela->sym->sec) {
361                                         found = true;
362                                         break;
363                                 }
364                         }
365
366                         if (!found) {
367                                 WARN("can't find unreachable insn at %s+0x%x",
368                                      rela->sym->sec->name, rela->addend);
369                                 return -1;
370                         }
371                 } else {
372                         WARN("can't find unreachable insn at %s+0x%x",
373                              rela->sym->sec->name, rela->addend);
374                         return -1;
375                 }
376
377                 insn->dead_end = true;
378         }
379
380 reachable:
381         /*
382          * These manually annotated reachable checks are needed for GCC 4.4,
383          * where the Linux unreachable() macro isn't supported.  In that case
384          * GCC doesn't know the "ud2" is fatal, so it generates code as if it's
385          * not a dead end.
386          */
387         sec = find_section_by_name(file->elf, ".rela.discard.reachable");
388         if (!sec)
389                 return 0;
390
391         list_for_each_entry(rela, &sec->rela_list, list) {
392                 if (rela->sym->type != STT_SECTION) {
393                         WARN("unexpected relocation symbol type in %s", sec->name);
394                         return -1;
395                 }
396                 insn = find_insn(file, rela->sym->sec, rela->addend);
397                 if (insn)
398                         insn = list_prev_entry(insn, list);
399                 else if (rela->addend == rela->sym->sec->len) {
400                         found = false;
401                         list_for_each_entry_reverse(insn, &file->insn_list, list) {
402                                 if (insn->sec == rela->sym->sec) {
403                                         found = true;
404                                         break;
405                                 }
406                         }
407
408                         if (!found) {
409                                 WARN("can't find reachable insn at %s+0x%x",
410                                      rela->sym->sec->name, rela->addend);
411                                 return -1;
412                         }
413                 } else {
414                         WARN("can't find reachable insn at %s+0x%x",
415                              rela->sym->sec->name, rela->addend);
416                         return -1;
417                 }
418
419                 insn->dead_end = false;
420         }
421
422         return 0;
423 }
424
425 /*
426  * Warnings shouldn't be reported for ignored functions.
427  */
428 static void add_ignores(struct objtool_file *file)
429 {
430         struct instruction *insn;
431         struct section *sec;
432         struct symbol *func;
433         struct rela *rela;
434
435         sec = find_section_by_name(file->elf, ".rela.discard.func_stack_frame_non_standard");
436         if (!sec)
437                 return;
438
439         list_for_each_entry(rela, &sec->rela_list, list) {
440                 switch (rela->sym->type) {
441                 case STT_FUNC:
442                         func = rela->sym;
443                         break;
444
445                 case STT_SECTION:
446                         func = find_func_by_offset(rela->sym->sec, rela->addend);
447                         if (!func)
448                                 continue;
449                         break;
450
451                 default:
452                         WARN("unexpected relocation symbol type in %s: %d", sec->name, rela->sym->type);
453                         continue;
454                 }
455
456                 func_for_each_insn(file, func, insn)
457                         insn->ignore = true;
458         }
459 }
460
461 /*
462  * This is a whitelist of functions that is allowed to be called with AC set.
463  * The list is meant to be minimal and only contains compiler instrumentation
464  * ABI and a few functions used to implement *_{to,from}_user() functions.
465  *
466  * These functions must not directly change AC, but may PUSHF/POPF.
467  */
468 static const char *uaccess_safe_builtin[] = {
469         /* KASAN */
470         "kasan_report",
471         "check_memory_region",
472         /* KASAN out-of-line */
473         "__asan_loadN_noabort",
474         "__asan_load1_noabort",
475         "__asan_load2_noabort",
476         "__asan_load4_noabort",
477         "__asan_load8_noabort",
478         "__asan_load16_noabort",
479         "__asan_storeN_noabort",
480         "__asan_store1_noabort",
481         "__asan_store2_noabort",
482         "__asan_store4_noabort",
483         "__asan_store8_noabort",
484         "__asan_store16_noabort",
485         /* KASAN in-line */
486         "__asan_report_load_n_noabort",
487         "__asan_report_load1_noabort",
488         "__asan_report_load2_noabort",
489         "__asan_report_load4_noabort",
490         "__asan_report_load8_noabort",
491         "__asan_report_load16_noabort",
492         "__asan_report_store_n_noabort",
493         "__asan_report_store1_noabort",
494         "__asan_report_store2_noabort",
495         "__asan_report_store4_noabort",
496         "__asan_report_store8_noabort",
497         "__asan_report_store16_noabort",
498         /* KCOV */
499         "write_comp_data",
500         "__sanitizer_cov_trace_pc",
501         "__sanitizer_cov_trace_const_cmp1",
502         "__sanitizer_cov_trace_const_cmp2",
503         "__sanitizer_cov_trace_const_cmp4",
504         "__sanitizer_cov_trace_const_cmp8",
505         "__sanitizer_cov_trace_cmp1",
506         "__sanitizer_cov_trace_cmp2",
507         "__sanitizer_cov_trace_cmp4",
508         "__sanitizer_cov_trace_cmp8",
509         "__sanitizer_cov_trace_switch",
510         /* UBSAN */
511         "ubsan_type_mismatch_common",
512         "__ubsan_handle_type_mismatch",
513         "__ubsan_handle_type_mismatch_v1",
514         "__ubsan_handle_shift_out_of_bounds",
515         /* misc */
516         "csum_partial_copy_generic",
517         "__memcpy_mcsafe",
518         "mcsafe_handle_tail",
519         "ftrace_likely_update", /* CONFIG_TRACE_BRANCH_PROFILING */
520         NULL
521 };
522
523 static void add_uaccess_safe(struct objtool_file *file)
524 {
525         struct symbol *func;
526         const char **name;
527
528         if (!uaccess)
529                 return;
530
531         for (name = uaccess_safe_builtin; *name; name++) {
532                 func = find_symbol_by_name(file->elf, *name);
533                 if (!func)
534                         continue;
535
536                 func->uaccess_safe = true;
537         }
538 }
539
540 /*
541  * FIXME: For now, just ignore any alternatives which add retpolines.  This is
542  * a temporary hack, as it doesn't allow ORC to unwind from inside a retpoline.
543  * But it at least allows objtool to understand the control flow *around* the
544  * retpoline.
545  */
546 static int add_ignore_alternatives(struct objtool_file *file)
547 {
548         struct section *sec;
549         struct rela *rela;
550         struct instruction *insn;
551
552         sec = find_section_by_name(file->elf, ".rela.discard.ignore_alts");
553         if (!sec)
554                 return 0;
555
556         list_for_each_entry(rela, &sec->rela_list, list) {
557                 if (rela->sym->type != STT_SECTION) {
558                         WARN("unexpected relocation symbol type in %s", sec->name);
559                         return -1;
560                 }
561
562                 insn = find_insn(file, rela->sym->sec, rela->addend);
563                 if (!insn) {
564                         WARN("bad .discard.ignore_alts entry");
565                         return -1;
566                 }
567
568                 insn->ignore_alts = true;
569         }
570
571         return 0;
572 }
573
574 /*
575  * Find the destination instructions for all jumps.
576  */
577 static int add_jump_destinations(struct objtool_file *file)
578 {
579         struct instruction *insn;
580         struct rela *rela;
581         struct section *dest_sec;
582         unsigned long dest_off;
583
584         for_each_insn(file, insn) {
585                 if (!is_static_jump(insn))
586                         continue;
587
588                 if (insn->ignore || insn->offset == FAKE_JUMP_OFFSET)
589                         continue;
590
591                 rela = find_rela_by_dest_range(file->elf, insn->sec,
592                                                insn->offset, insn->len);
593                 if (!rela) {
594                         dest_sec = insn->sec;
595                         dest_off = arch_jump_destination(insn);
596                 } else if (rela->sym->type == STT_SECTION) {
597                         dest_sec = rela->sym->sec;
598                         dest_off = arch_dest_rela_offset(rela->addend);
599                 } else if (rela->sym->sec->idx) {
600                         dest_sec = rela->sym->sec;
601                         dest_off = rela->sym->sym.st_value +
602                                    arch_dest_rela_offset(rela->addend);
603                 } else if (strstr(rela->sym->name, "_indirect_thunk_")) {
604                         /*
605                          * Retpoline jumps are really dynamic jumps in
606                          * disguise, so convert them accordingly.
607                          */
608                         if (insn->type == INSN_JUMP_UNCONDITIONAL)
609                                 insn->type = INSN_JUMP_DYNAMIC;
610                         else
611                                 insn->type = INSN_JUMP_DYNAMIC_CONDITIONAL;
612
613                         insn->retpoline_safe = true;
614                         continue;
615                 } else {
616                         /* external sibling call */
617                         insn->call_dest = rela->sym;
618                         continue;
619                 }
620
621                 insn->jump_dest = find_insn(file, dest_sec, dest_off);
622                 if (!insn->jump_dest) {
623
624                         /*
625                          * This is a special case where an alt instruction
626                          * jumps past the end of the section.  These are
627                          * handled later in handle_group_alt().
628                          */
629                         if (!strcmp(insn->sec->name, ".altinstr_replacement"))
630                                 continue;
631
632                         WARN_FUNC("can't find jump dest instruction at %s+0x%lx",
633                                   insn->sec, insn->offset, dest_sec->name,
634                                   dest_off);
635                         return -1;
636                 }
637
638                 /*
639                  * Cross-function jump.
640                  */
641                 if (insn->func && insn->jump_dest->func &&
642                     insn->func != insn->jump_dest->func) {
643
644                         /*
645                          * For GCC 8+, create parent/child links for any cold
646                          * subfunctions.  This is _mostly_ redundant with a
647                          * similar initialization in read_symbols().
648                          *
649                          * If a function has aliases, we want the *first* such
650                          * function in the symbol table to be the subfunction's
651                          * parent.  In that case we overwrite the
652                          * initialization done in read_symbols().
653                          *
654                          * However this code can't completely replace the
655                          * read_symbols() code because this doesn't detect the
656                          * case where the parent function's only reference to a
657                          * subfunction is through a jump table.
658                          */
659                         if (!strstr(insn->func->name, ".cold.") &&
660                             strstr(insn->jump_dest->func->name, ".cold.")) {
661                                 insn->func->cfunc = insn->jump_dest->func;
662                                 insn->jump_dest->func->pfunc = insn->func;
663
664                         } else if (insn->jump_dest->func->pfunc != insn->func->pfunc &&
665                                    insn->jump_dest->offset == insn->jump_dest->func->offset) {
666
667                                 /* internal sibling call */
668                                 insn->call_dest = insn->jump_dest->func;
669                         }
670                 }
671         }
672
673         return 0;
674 }
675
676 /*
677  * Find the destination instructions for all calls.
678  */
679 static int add_call_destinations(struct objtool_file *file)
680 {
681         struct instruction *insn;
682         unsigned long dest_off;
683         struct rela *rela;
684
685         for_each_insn(file, insn) {
686                 if (insn->type != INSN_CALL)
687                         continue;
688
689                 rela = find_rela_by_dest_range(file->elf, insn->sec,
690                                                insn->offset, insn->len);
691                 if (!rela) {
692                         dest_off = arch_jump_destination(insn);
693                         insn->call_dest = find_func_by_offset(insn->sec, dest_off);
694                         if (!insn->call_dest)
695                                 insn->call_dest = find_symbol_by_offset(insn->sec, dest_off);
696
697                         if (insn->ignore)
698                                 continue;
699
700                         if (!insn->call_dest) {
701                                 WARN_FUNC("unsupported intra-function call",
702                                           insn->sec, insn->offset);
703                                 if (retpoline)
704                                         WARN("If this is a retpoline, please patch it in with alternatives and annotate it with ANNOTATE_NOSPEC_ALTERNATIVE.");
705                                 return -1;
706                         }
707
708                         if (insn->func && insn->call_dest->type != STT_FUNC) {
709                                 WARN_FUNC("unsupported call to non-function",
710                                           insn->sec, insn->offset);
711                                 return -1;
712                         }
713
714                 } else if (rela->sym->type == STT_SECTION) {
715                         dest_off = arch_dest_rela_offset(rela->addend);
716                         insn->call_dest = find_func_by_offset(rela->sym->sec,
717                                                               dest_off);
718                         if (!insn->call_dest) {
719                                 WARN_FUNC("can't find call dest symbol at %s+0x%lx",
720                                           insn->sec, insn->offset,
721                                           rela->sym->sec->name,
722                                           dest_off);
723                                 return -1;
724                         }
725                 } else
726                         insn->call_dest = rela->sym;
727         }
728
729         return 0;
730 }
731
732 /*
733  * The .alternatives section requires some extra special care, over and above
734  * what other special sections require:
735  *
736  * 1. Because alternatives are patched in-place, we need to insert a fake jump
737  *    instruction at the end so that validate_branch() skips all the original
738  *    replaced instructions when validating the new instruction path.
739  *
740  * 2. An added wrinkle is that the new instruction length might be zero.  In
741  *    that case the old instructions are replaced with noops.  We simulate that
742  *    by creating a fake jump as the only new instruction.
743  *
744  * 3. In some cases, the alternative section includes an instruction which
745  *    conditionally jumps to the _end_ of the entry.  We have to modify these
746  *    jumps' destinations to point back to .text rather than the end of the
747  *    entry in .altinstr_replacement.
748  */
749 static int handle_group_alt(struct objtool_file *file,
750                             struct special_alt *special_alt,
751                             struct instruction *orig_insn,
752                             struct instruction **new_insn)
753 {
754         struct instruction *last_orig_insn, *last_new_insn, *insn, *fake_jump = NULL;
755         unsigned long dest_off;
756
757         last_orig_insn = NULL;
758         insn = orig_insn;
759         sec_for_each_insn_from(file, insn) {
760                 if (insn->offset >= special_alt->orig_off + special_alt->orig_len)
761                         break;
762
763                 insn->alt_group = true;
764                 last_orig_insn = insn;
765         }
766
767         if (next_insn_same_sec(file, last_orig_insn)) {
768                 fake_jump = malloc(sizeof(*fake_jump));
769                 if (!fake_jump) {
770                         WARN("malloc failed");
771                         return -1;
772                 }
773                 memset(fake_jump, 0, sizeof(*fake_jump));
774                 INIT_LIST_HEAD(&fake_jump->alts);
775                 INIT_LIST_HEAD(&fake_jump->stack_ops);
776                 init_cfi_state(&fake_jump->cfi);
777
778                 fake_jump->sec = special_alt->new_sec;
779                 fake_jump->offset = FAKE_JUMP_OFFSET;
780                 fake_jump->type = INSN_JUMP_UNCONDITIONAL;
781                 fake_jump->jump_dest = list_next_entry(last_orig_insn, list);
782                 fake_jump->func = orig_insn->func;
783         }
784
785         if (!special_alt->new_len) {
786                 if (!fake_jump) {
787                         WARN("%s: empty alternative at end of section",
788                              special_alt->orig_sec->name);
789                         return -1;
790                 }
791
792                 *new_insn = fake_jump;
793                 return 0;
794         }
795
796         last_new_insn = NULL;
797         insn = *new_insn;
798         sec_for_each_insn_from(file, insn) {
799                 if (insn->offset >= special_alt->new_off + special_alt->new_len)
800                         break;
801
802                 last_new_insn = insn;
803
804                 insn->ignore = orig_insn->ignore_alts;
805                 insn->func = orig_insn->func;
806
807                 /*
808                  * Since alternative replacement code is copy/pasted by the
809                  * kernel after applying relocations, generally such code can't
810                  * have relative-address relocation references to outside the
811                  * .altinstr_replacement section, unless the arch's
812                  * alternatives code can adjust the relative offsets
813                  * accordingly.
814                  *
815                  * The x86 alternatives code adjusts the offsets only when it
816                  * encounters a branch instruction at the very beginning of the
817                  * replacement group.
818                  */
819                 if ((insn->offset != special_alt->new_off ||
820                     (insn->type != INSN_CALL && !is_static_jump(insn))) &&
821                     find_rela_by_dest_range(file->elf, insn->sec, insn->offset, insn->len)) {
822
823                         WARN_FUNC("unsupported relocation in alternatives section",
824                                   insn->sec, insn->offset);
825                         return -1;
826                 }
827
828                 if (!is_static_jump(insn))
829                         continue;
830
831                 if (!insn->immediate)
832                         continue;
833
834                 dest_off = arch_jump_destination(insn);
835                 if (dest_off == special_alt->new_off + special_alt->new_len) {
836                         if (!fake_jump) {
837                                 WARN("%s: alternative jump to end of section",
838                                      special_alt->orig_sec->name);
839                                 return -1;
840                         }
841                         insn->jump_dest = fake_jump;
842                 }
843
844                 if (!insn->jump_dest) {
845                         WARN_FUNC("can't find alternative jump destination",
846                                   insn->sec, insn->offset);
847                         return -1;
848                 }
849         }
850
851         if (!last_new_insn) {
852                 WARN_FUNC("can't find last new alternative instruction",
853                           special_alt->new_sec, special_alt->new_off);
854                 return -1;
855         }
856
857         if (fake_jump)
858                 list_add(&fake_jump->list, &last_new_insn->list);
859
860         return 0;
861 }
862
863 /*
864  * A jump table entry can either convert a nop to a jump or a jump to a nop.
865  * If the original instruction is a jump, make the alt entry an effective nop
866  * by just skipping the original instruction.
867  */
868 static int handle_jump_alt(struct objtool_file *file,
869                            struct special_alt *special_alt,
870                            struct instruction *orig_insn,
871                            struct instruction **new_insn)
872 {
873         if (orig_insn->type == INSN_NOP)
874                 return 0;
875
876         if (orig_insn->type != INSN_JUMP_UNCONDITIONAL) {
877                 WARN_FUNC("unsupported instruction at jump label",
878                           orig_insn->sec, orig_insn->offset);
879                 return -1;
880         }
881
882         *new_insn = list_next_entry(orig_insn, list);
883         return 0;
884 }
885
886 /*
887  * Read all the special sections which have alternate instructions which can be
888  * patched in or redirected to at runtime.  Each instruction having alternate
889  * instruction(s) has them added to its insn->alts list, which will be
890  * traversed in validate_branch().
891  */
892 static int add_special_section_alts(struct objtool_file *file)
893 {
894         struct list_head special_alts;
895         struct instruction *orig_insn, *new_insn;
896         struct special_alt *special_alt, *tmp;
897         struct alternative *alt;
898         int ret;
899
900         ret = special_get_alts(file->elf, &special_alts);
901         if (ret)
902                 return ret;
903
904         list_for_each_entry_safe(special_alt, tmp, &special_alts, list) {
905
906                 orig_insn = find_insn(file, special_alt->orig_sec,
907                                       special_alt->orig_off);
908                 if (!orig_insn) {
909                         WARN_FUNC("special: can't find orig instruction",
910                                   special_alt->orig_sec, special_alt->orig_off);
911                         ret = -1;
912                         goto out;
913                 }
914
915                 new_insn = NULL;
916                 if (!special_alt->group || special_alt->new_len) {
917                         new_insn = find_insn(file, special_alt->new_sec,
918                                              special_alt->new_off);
919                         if (!new_insn) {
920                                 WARN_FUNC("special: can't find new instruction",
921                                           special_alt->new_sec,
922                                           special_alt->new_off);
923                                 ret = -1;
924                                 goto out;
925                         }
926                 }
927
928                 if (special_alt->group) {
929                         if (!special_alt->orig_len) {
930                                 WARN_FUNC("empty alternative entry",
931                                           orig_insn->sec, orig_insn->offset);
932                                 continue;
933                         }
934
935                         ret = handle_group_alt(file, special_alt, orig_insn,
936                                                &new_insn);
937                         if (ret)
938                                 goto out;
939                 } else if (special_alt->jump_or_nop) {
940                         ret = handle_jump_alt(file, special_alt, orig_insn,
941                                               &new_insn);
942                         if (ret)
943                                 goto out;
944                 }
945
946                 alt = malloc(sizeof(*alt));
947                 if (!alt) {
948                         WARN("malloc failed");
949                         ret = -1;
950                         goto out;
951                 }
952
953                 alt->insn = new_insn;
954                 alt->skip_orig = special_alt->skip_orig;
955                 orig_insn->ignore_alts |= special_alt->skip_alt;
956                 list_add_tail(&alt->list, &orig_insn->alts);
957
958                 list_del(&special_alt->list);
959                 free(special_alt);
960         }
961
962 out:
963         return ret;
964 }
965
966 static int add_jump_table(struct objtool_file *file, struct instruction *insn,
967                             struct rela *table)
968 {
969         struct rela *rela = table;
970         struct instruction *dest_insn;
971         struct alternative *alt;
972         struct symbol *pfunc = insn->func->pfunc;
973         unsigned int prev_offset = 0;
974
975         /*
976          * Each @rela is a switch table relocation which points to the target
977          * instruction.
978          */
979         list_for_each_entry_from(rela, &table->sec->rela_list, list) {
980
981                 /* Check for the end of the table: */
982                 if (rela != table && rela->jump_table_start)
983                         break;
984
985                 /* Make sure the table entries are consecutive: */
986                 if (prev_offset && rela->offset != prev_offset + 8)
987                         break;
988
989                 /* Detect function pointers from contiguous objects: */
990                 if (rela->sym->sec == pfunc->sec &&
991                     rela->addend == pfunc->offset)
992                         break;
993
994                 dest_insn = find_insn(file, rela->sym->sec, rela->addend);
995                 if (!dest_insn)
996                         break;
997
998                 /* Make sure the destination is in the same function: */
999                 if (!dest_insn->func || dest_insn->func->pfunc != pfunc)
1000                         break;
1001
1002                 alt = malloc(sizeof(*alt));
1003                 if (!alt) {
1004                         WARN("malloc failed");
1005                         return -1;
1006                 }
1007
1008                 alt->insn = dest_insn;
1009                 list_add_tail(&alt->list, &insn->alts);
1010                 prev_offset = rela->offset;
1011         }
1012
1013         if (!prev_offset) {
1014                 WARN_FUNC("can't find switch jump table",
1015                           insn->sec, insn->offset);
1016                 return -1;
1017         }
1018
1019         return 0;
1020 }
1021
1022 /*
1023  * find_jump_table() - Given a dynamic jump, find the switch jump table in
1024  * .rodata associated with it.
1025  *
1026  * There are 3 basic patterns:
1027  *
1028  * 1. jmpq *[rodata addr](,%reg,8)
1029  *
1030  *    This is the most common case by far.  It jumps to an address in a simple
1031  *    jump table which is stored in .rodata.
1032  *
1033  * 2. jmpq *[rodata addr](%rip)
1034  *
1035  *    This is caused by a rare GCC quirk, currently only seen in three driver
1036  *    functions in the kernel, only with certain obscure non-distro configs.
1037  *
1038  *    As part of an optimization, GCC makes a copy of an existing switch jump
1039  *    table, modifies it, and then hard-codes the jump (albeit with an indirect
1040  *    jump) to use a single entry in the table.  The rest of the jump table and
1041  *    some of its jump targets remain as dead code.
1042  *
1043  *    In such a case we can just crudely ignore all unreachable instruction
1044  *    warnings for the entire object file.  Ideally we would just ignore them
1045  *    for the function, but that would require redesigning the code quite a
1046  *    bit.  And honestly that's just not worth doing: unreachable instruction
1047  *    warnings are of questionable value anyway, and this is such a rare issue.
1048  *
1049  * 3. mov [rodata addr],%reg1
1050  *    ... some instructions ...
1051  *    jmpq *(%reg1,%reg2,8)
1052  *
1053  *    This is a fairly uncommon pattern which is new for GCC 6.  As of this
1054  *    writing, there are 11 occurrences of it in the allmodconfig kernel.
1055  *
1056  *    As of GCC 7 there are quite a few more of these and the 'in between' code
1057  *    is significant. Esp. with KASAN enabled some of the code between the mov
1058  *    and jmpq uses .rodata itself, which can confuse things.
1059  *
1060  *    TODO: Once we have DWARF CFI and smarter instruction decoding logic,
1061  *    ensure the same register is used in the mov and jump instructions.
1062  *
1063  *    NOTE: RETPOLINE made it harder still to decode dynamic jumps.
1064  */
1065 static struct rela *find_jump_table(struct objtool_file *file,
1066                                       struct symbol *func,
1067                                       struct instruction *insn)
1068 {
1069         struct rela *text_rela, *table_rela;
1070         struct instruction *dest_insn, *orig_insn = insn;
1071         struct section *table_sec;
1072         unsigned long table_offset;
1073
1074         /*
1075          * Backward search using the @first_jump_src links, these help avoid
1076          * much of the 'in between' code. Which avoids us getting confused by
1077          * it.
1078          */
1079         for (;
1080              &insn->list != &file->insn_list && insn->func && insn->func->pfunc == func;
1081              insn = insn->first_jump_src ?: list_prev_entry(insn, list)) {
1082
1083                 if (insn != orig_insn && insn->type == INSN_JUMP_DYNAMIC)
1084                         break;
1085
1086                 /* allow small jumps within the range */
1087                 if (insn->type == INSN_JUMP_UNCONDITIONAL &&
1088                     insn->jump_dest &&
1089                     (insn->jump_dest->offset <= insn->offset ||
1090                      insn->jump_dest->offset > orig_insn->offset))
1091                     break;
1092
1093                 /* look for a relocation which references .rodata */
1094                 text_rela = find_rela_by_dest_range(file->elf, insn->sec,
1095                                                     insn->offset, insn->len);
1096                 if (!text_rela || text_rela->sym->type != STT_SECTION ||
1097                     !text_rela->sym->sec->rodata)
1098                         continue;
1099
1100                 table_offset = text_rela->addend;
1101                 table_sec = text_rela->sym->sec;
1102
1103                 if (text_rela->type == R_X86_64_PC32)
1104                         table_offset += 4;
1105
1106                 /*
1107                  * Make sure the .rodata address isn't associated with a
1108                  * symbol.  GCC jump tables are anonymous data.
1109                  *
1110                  * Also support C jump tables which are in the same format as
1111                  * switch jump tables.  For objtool to recognize them, they
1112                  * need to be placed in the C_JUMP_TABLE_SECTION section.  They
1113                  * have symbols associated with them.
1114                  */
1115                 if (find_symbol_containing(table_sec, table_offset) &&
1116                     strcmp(table_sec->name, C_JUMP_TABLE_SECTION))
1117                         continue;
1118
1119                 /*
1120                  * Each table entry has a rela associated with it.  The rela
1121                  * should reference text in the same function as the original
1122                  * instruction.
1123                  */
1124                 table_rela = find_rela_by_dest(file->elf, table_sec, table_offset);
1125                 if (!table_rela)
1126                         continue;
1127                 dest_insn = find_insn(file, table_rela->sym->sec, table_rela->addend);
1128                 if (!dest_insn || !dest_insn->func || dest_insn->func->pfunc != func)
1129                         continue;
1130
1131                 /*
1132                  * Use of RIP-relative switch jumps is quite rare, and
1133                  * indicates a rare GCC quirk/bug which can leave dead code
1134                  * behind.
1135                  */
1136                 if (text_rela->type == R_X86_64_PC32)
1137                         file->ignore_unreachables = true;
1138
1139                 return table_rela;
1140         }
1141
1142         return NULL;
1143 }
1144
1145 /*
1146  * First pass: Mark the head of each jump table so that in the next pass,
1147  * we know when a given jump table ends and the next one starts.
1148  */
1149 static void mark_func_jump_tables(struct objtool_file *file,
1150                                     struct symbol *func)
1151 {
1152         struct instruction *insn, *last = NULL;
1153         struct rela *rela;
1154
1155         func_for_each_insn(file, func, insn) {
1156                 if (!last)
1157                         last = insn;
1158
1159                 /*
1160                  * Store back-pointers for unconditional forward jumps such
1161                  * that find_jump_table() can back-track using those and
1162                  * avoid some potentially confusing code.
1163                  */
1164                 if (insn->type == INSN_JUMP_UNCONDITIONAL && insn->jump_dest &&
1165                     insn->offset > last->offset &&
1166                     insn->jump_dest->offset > insn->offset &&
1167                     !insn->jump_dest->first_jump_src) {
1168
1169                         insn->jump_dest->first_jump_src = insn;
1170                         last = insn->jump_dest;
1171                 }
1172
1173                 if (insn->type != INSN_JUMP_DYNAMIC)
1174                         continue;
1175
1176                 rela = find_jump_table(file, func, insn);
1177                 if (rela) {
1178                         rela->jump_table_start = true;
1179                         insn->jump_table = rela;
1180                 }
1181         }
1182 }
1183
1184 static int add_func_jump_tables(struct objtool_file *file,
1185                                   struct symbol *func)
1186 {
1187         struct instruction *insn;
1188         int ret;
1189
1190         func_for_each_insn(file, func, insn) {
1191                 if (!insn->jump_table)
1192                         continue;
1193
1194                 ret = add_jump_table(file, insn, insn->jump_table);
1195                 if (ret)
1196                         return ret;
1197         }
1198
1199         return 0;
1200 }
1201
1202 /*
1203  * For some switch statements, gcc generates a jump table in the .rodata
1204  * section which contains a list of addresses within the function to jump to.
1205  * This finds these jump tables and adds them to the insn->alts lists.
1206  */
1207 static int add_jump_table_alts(struct objtool_file *file)
1208 {
1209         struct section *sec;
1210         struct symbol *func;
1211         int ret;
1212
1213         if (!file->rodata)
1214                 return 0;
1215
1216         for_each_sec(file, sec) {
1217                 list_for_each_entry(func, &sec->symbol_list, list) {
1218                         if (func->type != STT_FUNC)
1219                                 continue;
1220
1221                         mark_func_jump_tables(file, func);
1222                         ret = add_func_jump_tables(file, func);
1223                         if (ret)
1224                                 return ret;
1225                 }
1226         }
1227
1228         return 0;
1229 }
1230
1231 static int read_unwind_hints(struct objtool_file *file)
1232 {
1233         struct section *sec, *relasec;
1234         struct rela *rela;
1235         struct unwind_hint *hint;
1236         struct instruction *insn;
1237         struct cfi_reg *cfa;
1238         int i;
1239
1240         sec = find_section_by_name(file->elf, ".discard.unwind_hints");
1241         if (!sec)
1242                 return 0;
1243
1244         relasec = sec->rela;
1245         if (!relasec) {
1246                 WARN("missing .rela.discard.unwind_hints section");
1247                 return -1;
1248         }
1249
1250         if (sec->len % sizeof(struct unwind_hint)) {
1251                 WARN("struct unwind_hint size mismatch");
1252                 return -1;
1253         }
1254
1255         file->hints = true;
1256
1257         for (i = 0; i < sec->len / sizeof(struct unwind_hint); i++) {
1258                 hint = (struct unwind_hint *)sec->data->d_buf + i;
1259
1260                 rela = find_rela_by_dest(file->elf, sec, i * sizeof(*hint));
1261                 if (!rela) {
1262                         WARN("can't find rela for unwind_hints[%d]", i);
1263                         return -1;
1264                 }
1265
1266                 insn = find_insn(file, rela->sym->sec, rela->addend);
1267                 if (!insn) {
1268                         WARN("can't find insn for unwind_hints[%d]", i);
1269                         return -1;
1270                 }
1271
1272                 cfa = &insn->cfi.cfa;
1273
1274                 if (hint->type == UNWIND_HINT_TYPE_RET_OFFSET) {
1275                         insn->ret_offset = hint->sp_offset;
1276                         continue;
1277                 }
1278
1279                 insn->hint = true;
1280
1281                 switch (hint->sp_reg) {
1282                 case ORC_REG_UNDEFINED:
1283                         cfa->base = CFI_UNDEFINED;
1284                         break;
1285                 case ORC_REG_SP:
1286                         cfa->base = CFI_SP;
1287                         break;
1288                 case ORC_REG_BP:
1289                         cfa->base = CFI_BP;
1290                         break;
1291                 case ORC_REG_SP_INDIRECT:
1292                         cfa->base = CFI_SP_INDIRECT;
1293                         break;
1294                 case ORC_REG_R10:
1295                         cfa->base = CFI_R10;
1296                         break;
1297                 case ORC_REG_R13:
1298                         cfa->base = CFI_R13;
1299                         break;
1300                 case ORC_REG_DI:
1301                         cfa->base = CFI_DI;
1302                         break;
1303                 case ORC_REG_DX:
1304                         cfa->base = CFI_DX;
1305                         break;
1306                 default:
1307                         WARN_FUNC("unsupported unwind_hint sp base reg %d",
1308                                   insn->sec, insn->offset, hint->sp_reg);
1309                         return -1;
1310                 }
1311
1312                 cfa->offset = hint->sp_offset;
1313                 insn->cfi.type = hint->type;
1314                 insn->cfi.end = hint->end;
1315         }
1316
1317         return 0;
1318 }
1319
1320 static int read_retpoline_hints(struct objtool_file *file)
1321 {
1322         struct section *sec;
1323         struct instruction *insn;
1324         struct rela *rela;
1325
1326         sec = find_section_by_name(file->elf, ".rela.discard.retpoline_safe");
1327         if (!sec)
1328                 return 0;
1329
1330         list_for_each_entry(rela, &sec->rela_list, list) {
1331                 if (rela->sym->type != STT_SECTION) {
1332                         WARN("unexpected relocation symbol type in %s", sec->name);
1333                         return -1;
1334                 }
1335
1336                 insn = find_insn(file, rela->sym->sec, rela->addend);
1337                 if (!insn) {
1338                         WARN("bad .discard.retpoline_safe entry");
1339                         return -1;
1340                 }
1341
1342                 if (insn->type != INSN_JUMP_DYNAMIC &&
1343                     insn->type != INSN_CALL_DYNAMIC) {
1344                         WARN_FUNC("retpoline_safe hint not an indirect jump/call",
1345                                   insn->sec, insn->offset);
1346                         return -1;
1347                 }
1348
1349                 insn->retpoline_safe = true;
1350         }
1351
1352         return 0;
1353 }
1354
1355 static int read_instr_hints(struct objtool_file *file)
1356 {
1357         struct section *sec;
1358         struct instruction *insn;
1359         struct rela *rela;
1360
1361         sec = find_section_by_name(file->elf, ".rela.discard.instr_end");
1362         if (!sec)
1363                 return 0;
1364
1365         list_for_each_entry(rela, &sec->rela_list, list) {
1366                 if (rela->sym->type != STT_SECTION) {
1367                         WARN("unexpected relocation symbol type in %s", sec->name);
1368                         return -1;
1369                 }
1370
1371                 insn = find_insn(file, rela->sym->sec, rela->addend);
1372                 if (!insn) {
1373                         WARN("bad .discard.instr_end entry");
1374                         return -1;
1375                 }
1376
1377                 insn->instr--;
1378         }
1379
1380         sec = find_section_by_name(file->elf, ".rela.discard.instr_begin");
1381         if (!sec)
1382                 return 0;
1383
1384         list_for_each_entry(rela, &sec->rela_list, list) {
1385                 if (rela->sym->type != STT_SECTION) {
1386                         WARN("unexpected relocation symbol type in %s", sec->name);
1387                         return -1;
1388                 }
1389
1390                 insn = find_insn(file, rela->sym->sec, rela->addend);
1391                 if (!insn) {
1392                         WARN("bad .discard.instr_begin entry");
1393                         return -1;
1394                 }
1395
1396                 insn->instr++;
1397         }
1398
1399         return 0;
1400 }
1401
1402 static void mark_rodata(struct objtool_file *file)
1403 {
1404         struct section *sec;
1405         bool found = false;
1406
1407         /*
1408          * Search for the following rodata sections, each of which can
1409          * potentially contain jump tables:
1410          *
1411          * - .rodata: can contain GCC switch tables
1412          * - .rodata.<func>: same, if -fdata-sections is being used
1413          * - .rodata..c_jump_table: contains C annotated jump tables
1414          *
1415          * .rodata.str1.* sections are ignored; they don't contain jump tables.
1416          */
1417         for_each_sec(file, sec) {
1418                 if (!strncmp(sec->name, ".rodata", 7) &&
1419                     !strstr(sec->name, ".str1.")) {
1420                         sec->rodata = true;
1421                         found = true;
1422                 }
1423         }
1424
1425         file->rodata = found;
1426 }
1427
1428 static int decode_sections(struct objtool_file *file)
1429 {
1430         int ret;
1431
1432         mark_rodata(file);
1433
1434         ret = decode_instructions(file);
1435         if (ret)
1436                 return ret;
1437
1438         ret = add_dead_ends(file);
1439         if (ret)
1440                 return ret;
1441
1442         add_ignores(file);
1443         add_uaccess_safe(file);
1444
1445         ret = add_ignore_alternatives(file);
1446         if (ret)
1447                 return ret;
1448
1449         ret = add_jump_destinations(file);
1450         if (ret)
1451                 return ret;
1452
1453         ret = add_special_section_alts(file);
1454         if (ret)
1455                 return ret;
1456
1457         ret = add_call_destinations(file);
1458         if (ret)
1459                 return ret;
1460
1461         ret = add_jump_table_alts(file);
1462         if (ret)
1463                 return ret;
1464
1465         ret = read_unwind_hints(file);
1466         if (ret)
1467                 return ret;
1468
1469         ret = read_retpoline_hints(file);
1470         if (ret)
1471                 return ret;
1472
1473         ret = read_instr_hints(file);
1474         if (ret)
1475                 return ret;
1476
1477         return 0;
1478 }
1479
1480 static bool is_fentry_call(struct instruction *insn)
1481 {
1482         if (insn->type == INSN_CALL &&
1483             insn->call_dest->type == STT_NOTYPE &&
1484             !strcmp(insn->call_dest->name, "__fentry__"))
1485                 return true;
1486
1487         return false;
1488 }
1489
1490 static bool has_modified_stack_frame(struct instruction *insn, struct insn_state *state)
1491 {
1492         u8 ret_offset = insn->ret_offset;
1493         struct cfi_state *cfi = &state->cfi;
1494         int i;
1495
1496         if (cfi->cfa.base != initial_func_cfi.cfa.base || cfi->drap)
1497                 return true;
1498
1499         if (cfi->cfa.offset != initial_func_cfi.cfa.offset + ret_offset)
1500                 return true;
1501
1502         if (cfi->stack_size != initial_func_cfi.cfa.offset + ret_offset)
1503                 return true;
1504
1505         for (i = 0; i < CFI_NUM_REGS; i++) {
1506                 if (cfi->regs[i].base != initial_func_cfi.regs[i].base ||
1507                     cfi->regs[i].offset != initial_func_cfi.regs[i].offset)
1508                         return true;
1509         }
1510
1511         return false;
1512 }
1513
1514 static bool has_valid_stack_frame(struct insn_state *state)
1515 {
1516         struct cfi_state *cfi = &state->cfi;
1517
1518         if (cfi->cfa.base == CFI_BP && cfi->regs[CFI_BP].base == CFI_CFA &&
1519             cfi->regs[CFI_BP].offset == -16)
1520                 return true;
1521
1522         if (cfi->drap && cfi->regs[CFI_BP].base == CFI_BP)
1523                 return true;
1524
1525         return false;
1526 }
1527
1528 static int update_cfi_state_regs(struct instruction *insn,
1529                                   struct cfi_state *cfi,
1530                                   struct stack_op *op)
1531 {
1532         struct cfi_reg *cfa = &cfi->cfa;
1533
1534         if (cfa->base != CFI_SP)
1535                 return 0;
1536
1537         /* push */
1538         if (op->dest.type == OP_DEST_PUSH || op->dest.type == OP_DEST_PUSHF)
1539                 cfa->offset += 8;
1540
1541         /* pop */
1542         if (op->src.type == OP_SRC_POP || op->src.type == OP_SRC_POPF)
1543                 cfa->offset -= 8;
1544
1545         /* add immediate to sp */
1546         if (op->dest.type == OP_DEST_REG && op->src.type == OP_SRC_ADD &&
1547             op->dest.reg == CFI_SP && op->src.reg == CFI_SP)
1548                 cfa->offset -= op->src.offset;
1549
1550         return 0;
1551 }
1552
1553 static void save_reg(struct cfi_state *cfi, unsigned char reg, int base, int offset)
1554 {
1555         if (arch_callee_saved_reg(reg) &&
1556             cfi->regs[reg].base == CFI_UNDEFINED) {
1557                 cfi->regs[reg].base = base;
1558                 cfi->regs[reg].offset = offset;
1559         }
1560 }
1561
1562 static void restore_reg(struct cfi_state *cfi, unsigned char reg)
1563 {
1564         cfi->regs[reg].base = initial_func_cfi.regs[reg].base;
1565         cfi->regs[reg].offset = initial_func_cfi.regs[reg].offset;
1566 }
1567
1568 /*
1569  * A note about DRAP stack alignment:
1570  *
1571  * GCC has the concept of a DRAP register, which is used to help keep track of
1572  * the stack pointer when aligning the stack.  r10 or r13 is used as the DRAP
1573  * register.  The typical DRAP pattern is:
1574  *
1575  *   4c 8d 54 24 08             lea    0x8(%rsp),%r10
1576  *   48 83 e4 c0                and    $0xffffffffffffffc0,%rsp
1577  *   41 ff 72 f8                pushq  -0x8(%r10)
1578  *   55                         push   %rbp
1579  *   48 89 e5                   mov    %rsp,%rbp
1580  *                              (more pushes)
1581  *   41 52                      push   %r10
1582  *                              ...
1583  *   41 5a                      pop    %r10
1584  *                              (more pops)
1585  *   5d                         pop    %rbp
1586  *   49 8d 62 f8                lea    -0x8(%r10),%rsp
1587  *   c3                         retq
1588  *
1589  * There are some variations in the epilogues, like:
1590  *
1591  *   5b                         pop    %rbx
1592  *   41 5a                      pop    %r10
1593  *   41 5c                      pop    %r12
1594  *   41 5d                      pop    %r13
1595  *   41 5e                      pop    %r14
1596  *   c9                         leaveq
1597  *   49 8d 62 f8                lea    -0x8(%r10),%rsp
1598  *   c3                         retq
1599  *
1600  * and:
1601  *
1602  *   4c 8b 55 e8                mov    -0x18(%rbp),%r10
1603  *   48 8b 5d e0                mov    -0x20(%rbp),%rbx
1604  *   4c 8b 65 f0                mov    -0x10(%rbp),%r12
1605  *   4c 8b 6d f8                mov    -0x8(%rbp),%r13
1606  *   c9                         leaveq
1607  *   49 8d 62 f8                lea    -0x8(%r10),%rsp
1608  *   c3                         retq
1609  *
1610  * Sometimes r13 is used as the DRAP register, in which case it's saved and
1611  * restored beforehand:
1612  *
1613  *   41 55                      push   %r13
1614  *   4c 8d 6c 24 10             lea    0x10(%rsp),%r13
1615  *   48 83 e4 f0                and    $0xfffffffffffffff0,%rsp
1616  *                              ...
1617  *   49 8d 65 f0                lea    -0x10(%r13),%rsp
1618  *   41 5d                      pop    %r13
1619  *   c3                         retq
1620  */
1621 static int update_cfi_state(struct instruction *insn, struct cfi_state *cfi,
1622                              struct stack_op *op)
1623 {
1624         struct cfi_reg *cfa = &cfi->cfa;
1625         struct cfi_reg *regs = cfi->regs;
1626
1627         /* stack operations don't make sense with an undefined CFA */
1628         if (cfa->base == CFI_UNDEFINED) {
1629                 if (insn->func) {
1630                         WARN_FUNC("undefined stack state", insn->sec, insn->offset);
1631                         return -1;
1632                 }
1633                 return 0;
1634         }
1635
1636         if (cfi->type == ORC_TYPE_REGS || cfi->type == ORC_TYPE_REGS_IRET)
1637                 return update_cfi_state_regs(insn, cfi, op);
1638
1639         switch (op->dest.type) {
1640
1641         case OP_DEST_REG:
1642                 switch (op->src.type) {
1643
1644                 case OP_SRC_REG:
1645                         if (op->src.reg == CFI_SP && op->dest.reg == CFI_BP &&
1646                             cfa->base == CFI_SP &&
1647                             regs[CFI_BP].base == CFI_CFA &&
1648                             regs[CFI_BP].offset == -cfa->offset) {
1649
1650                                 /* mov %rsp, %rbp */
1651                                 cfa->base = op->dest.reg;
1652                                 cfi->bp_scratch = false;
1653                         }
1654
1655                         else if (op->src.reg == CFI_SP &&
1656                                  op->dest.reg == CFI_BP && cfi->drap) {
1657
1658                                 /* drap: mov %rsp, %rbp */
1659                                 regs[CFI_BP].base = CFI_BP;
1660                                 regs[CFI_BP].offset = -cfi->stack_size;
1661                                 cfi->bp_scratch = false;
1662                         }
1663
1664                         else if (op->src.reg == CFI_SP && cfa->base == CFI_SP) {
1665
1666                                 /*
1667                                  * mov %rsp, %reg
1668                                  *
1669                                  * This is needed for the rare case where GCC
1670                                  * does:
1671                                  *
1672                                  *   mov    %rsp, %rax
1673                                  *   ...
1674                                  *   mov    %rax, %rsp
1675                                  */
1676                                 cfi->vals[op->dest.reg].base = CFI_CFA;
1677                                 cfi->vals[op->dest.reg].offset = -cfi->stack_size;
1678                         }
1679
1680                         else if (op->src.reg == CFI_BP && op->dest.reg == CFI_SP &&
1681                                  cfa->base == CFI_BP) {
1682
1683                                 /*
1684                                  * mov %rbp, %rsp
1685                                  *
1686                                  * Restore the original stack pointer (Clang).
1687                                  */
1688                                 cfi->stack_size = -cfi->regs[CFI_BP].offset;
1689                         }
1690
1691                         else if (op->dest.reg == cfa->base) {
1692
1693                                 /* mov %reg, %rsp */
1694                                 if (cfa->base == CFI_SP &&
1695                                     cfi->vals[op->src.reg].base == CFI_CFA) {
1696
1697                                         /*
1698                                          * This is needed for the rare case
1699                                          * where GCC does something dumb like:
1700                                          *
1701                                          *   lea    0x8(%rsp), %rcx
1702                                          *   ...
1703                                          *   mov    %rcx, %rsp
1704                                          */
1705                                         cfa->offset = -cfi->vals[op->src.reg].offset;
1706                                         cfi->stack_size = cfa->offset;
1707
1708                                 } else {
1709                                         cfa->base = CFI_UNDEFINED;
1710                                         cfa->offset = 0;
1711                                 }
1712                         }
1713
1714                         break;
1715
1716                 case OP_SRC_ADD:
1717                         if (op->dest.reg == CFI_SP && op->src.reg == CFI_SP) {
1718
1719                                 /* add imm, %rsp */
1720                                 cfi->stack_size -= op->src.offset;
1721                                 if (cfa->base == CFI_SP)
1722                                         cfa->offset -= op->src.offset;
1723                                 break;
1724                         }
1725
1726                         if (op->dest.reg == CFI_SP && op->src.reg == CFI_BP) {
1727
1728                                 /* lea disp(%rbp), %rsp */
1729                                 cfi->stack_size = -(op->src.offset + regs[CFI_BP].offset);
1730                                 break;
1731                         }
1732
1733                         if (op->src.reg == CFI_SP && cfa->base == CFI_SP) {
1734
1735                                 /* drap: lea disp(%rsp), %drap */
1736                                 cfi->drap_reg = op->dest.reg;
1737
1738                                 /*
1739                                  * lea disp(%rsp), %reg
1740                                  *
1741                                  * This is needed for the rare case where GCC
1742                                  * does something dumb like:
1743                                  *
1744                                  *   lea    0x8(%rsp), %rcx
1745                                  *   ...
1746                                  *   mov    %rcx, %rsp
1747                                  */
1748                                 cfi->vals[op->dest.reg].base = CFI_CFA;
1749                                 cfi->vals[op->dest.reg].offset = \
1750                                         -cfi->stack_size + op->src.offset;
1751
1752                                 break;
1753                         }
1754
1755                         if (cfi->drap && op->dest.reg == CFI_SP &&
1756                             op->src.reg == cfi->drap_reg) {
1757
1758                                  /* drap: lea disp(%drap), %rsp */
1759                                 cfa->base = CFI_SP;
1760                                 cfa->offset = cfi->stack_size = -op->src.offset;
1761                                 cfi->drap_reg = CFI_UNDEFINED;
1762                                 cfi->drap = false;
1763                                 break;
1764                         }
1765
1766                         if (op->dest.reg == cfi->cfa.base) {
1767                                 WARN_FUNC("unsupported stack register modification",
1768                                           insn->sec, insn->offset);
1769                                 return -1;
1770                         }
1771
1772                         break;
1773
1774                 case OP_SRC_AND:
1775                         if (op->dest.reg != CFI_SP ||
1776                             (cfi->drap_reg != CFI_UNDEFINED && cfa->base != CFI_SP) ||
1777                             (cfi->drap_reg == CFI_UNDEFINED && cfa->base != CFI_BP)) {
1778                                 WARN_FUNC("unsupported stack pointer realignment",
1779                                           insn->sec, insn->offset);
1780                                 return -1;
1781                         }
1782
1783                         if (cfi->drap_reg != CFI_UNDEFINED) {
1784                                 /* drap: and imm, %rsp */
1785                                 cfa->base = cfi->drap_reg;
1786                                 cfa->offset = cfi->stack_size = 0;
1787                                 cfi->drap = true;
1788                         }
1789
1790                         /*
1791                          * Older versions of GCC (4.8ish) realign the stack
1792                          * without DRAP, with a frame pointer.
1793                          */
1794
1795                         break;
1796
1797                 case OP_SRC_POP:
1798                 case OP_SRC_POPF:
1799                         if (!cfi->drap && op->dest.reg == cfa->base) {
1800
1801                                 /* pop %rbp */
1802                                 cfa->base = CFI_SP;
1803                         }
1804
1805                         if (cfi->drap && cfa->base == CFI_BP_INDIRECT &&
1806                             op->dest.reg == cfi->drap_reg &&
1807                             cfi->drap_offset == -cfi->stack_size) {
1808
1809                                 /* drap: pop %drap */
1810                                 cfa->base = cfi->drap_reg;
1811                                 cfa->offset = 0;
1812                                 cfi->drap_offset = -1;
1813
1814                         } else if (regs[op->dest.reg].offset == -cfi->stack_size) {
1815
1816                                 /* pop %reg */
1817                                 restore_reg(cfi, op->dest.reg);
1818                         }
1819
1820                         cfi->stack_size -= 8;
1821                         if (cfa->base == CFI_SP)
1822                                 cfa->offset -= 8;
1823
1824                         break;
1825
1826                 case OP_SRC_REG_INDIRECT:
1827                         if (cfi->drap && op->src.reg == CFI_BP &&
1828                             op->src.offset == cfi->drap_offset) {
1829
1830                                 /* drap: mov disp(%rbp), %drap */
1831                                 cfa->base = cfi->drap_reg;
1832                                 cfa->offset = 0;
1833                                 cfi->drap_offset = -1;
1834                         }
1835
1836                         if (cfi->drap && op->src.reg == CFI_BP &&
1837                             op->src.offset == regs[op->dest.reg].offset) {
1838
1839                                 /* drap: mov disp(%rbp), %reg */
1840                                 restore_reg(cfi, op->dest.reg);
1841
1842                         } else if (op->src.reg == cfa->base &&
1843                             op->src.offset == regs[op->dest.reg].offset + cfa->offset) {
1844
1845                                 /* mov disp(%rbp), %reg */
1846                                 /* mov disp(%rsp), %reg */
1847                                 restore_reg(cfi, op->dest.reg);
1848                         }
1849
1850                         break;
1851
1852                 default:
1853                         WARN_FUNC("unknown stack-related instruction",
1854                                   insn->sec, insn->offset);
1855                         return -1;
1856                 }
1857
1858                 break;
1859
1860         case OP_DEST_PUSH:
1861         case OP_DEST_PUSHF:
1862                 cfi->stack_size += 8;
1863                 if (cfa->base == CFI_SP)
1864                         cfa->offset += 8;
1865
1866                 if (op->src.type != OP_SRC_REG)
1867                         break;
1868
1869                 if (cfi->drap) {
1870                         if (op->src.reg == cfa->base && op->src.reg == cfi->drap_reg) {
1871
1872                                 /* drap: push %drap */
1873                                 cfa->base = CFI_BP_INDIRECT;
1874                                 cfa->offset = -cfi->stack_size;
1875
1876                                 /* save drap so we know when to restore it */
1877                                 cfi->drap_offset = -cfi->stack_size;
1878
1879                         } else if (op->src.reg == CFI_BP && cfa->base == cfi->drap_reg) {
1880
1881                                 /* drap: push %rbp */
1882                                 cfi->stack_size = 0;
1883
1884                         } else if (regs[op->src.reg].base == CFI_UNDEFINED) {
1885
1886                                 /* drap: push %reg */
1887                                 save_reg(cfi, op->src.reg, CFI_BP, -cfi->stack_size);
1888                         }
1889
1890                 } else {
1891
1892                         /* push %reg */
1893                         save_reg(cfi, op->src.reg, CFI_CFA, -cfi->stack_size);
1894                 }
1895
1896                 /* detect when asm code uses rbp as a scratch register */
1897                 if (!no_fp && insn->func && op->src.reg == CFI_BP &&
1898                     cfa->base != CFI_BP)
1899                         cfi->bp_scratch = true;
1900                 break;
1901
1902         case OP_DEST_REG_INDIRECT:
1903
1904                 if (cfi->drap) {
1905                         if (op->src.reg == cfa->base && op->src.reg == cfi->drap_reg) {
1906
1907                                 /* drap: mov %drap, disp(%rbp) */
1908                                 cfa->base = CFI_BP_INDIRECT;
1909                                 cfa->offset = op->dest.offset;
1910
1911                                 /* save drap offset so we know when to restore it */
1912                                 cfi->drap_offset = op->dest.offset;
1913                         }
1914
1915                         else if (regs[op->src.reg].base == CFI_UNDEFINED) {
1916
1917                                 /* drap: mov reg, disp(%rbp) */
1918                                 save_reg(cfi, op->src.reg, CFI_BP, op->dest.offset);
1919                         }
1920
1921                 } else if (op->dest.reg == cfa->base) {
1922
1923                         /* mov reg, disp(%rbp) */
1924                         /* mov reg, disp(%rsp) */
1925                         save_reg(cfi, op->src.reg, CFI_CFA,
1926                                  op->dest.offset - cfi->cfa.offset);
1927                 }
1928
1929                 break;
1930
1931         case OP_DEST_LEAVE:
1932                 if ((!cfi->drap && cfa->base != CFI_BP) ||
1933                     (cfi->drap && cfa->base != cfi->drap_reg)) {
1934                         WARN_FUNC("leave instruction with modified stack frame",
1935                                   insn->sec, insn->offset);
1936                         return -1;
1937                 }
1938
1939                 /* leave (mov %rbp, %rsp; pop %rbp) */
1940
1941                 cfi->stack_size = -cfi->regs[CFI_BP].offset - 8;
1942                 restore_reg(cfi, CFI_BP);
1943
1944                 if (!cfi->drap) {
1945                         cfa->base = CFI_SP;
1946                         cfa->offset -= 8;
1947                 }
1948
1949                 break;
1950
1951         case OP_DEST_MEM:
1952                 if (op->src.type != OP_SRC_POP && op->src.type != OP_SRC_POPF) {
1953                         WARN_FUNC("unknown stack-related memory operation",
1954                                   insn->sec, insn->offset);
1955                         return -1;
1956                 }
1957
1958                 /* pop mem */
1959                 cfi->stack_size -= 8;
1960                 if (cfa->base == CFI_SP)
1961                         cfa->offset -= 8;
1962
1963                 break;
1964
1965         default:
1966                 WARN_FUNC("unknown stack-related instruction",
1967                           insn->sec, insn->offset);
1968                 return -1;
1969         }
1970
1971         return 0;
1972 }
1973
1974 static int handle_insn_ops(struct instruction *insn, struct insn_state *state)
1975 {
1976         struct stack_op *op;
1977
1978         list_for_each_entry(op, &insn->stack_ops, list) {
1979                 int res;
1980
1981                 res = update_cfi_state(insn, &state->cfi, op);
1982                 if (res)
1983                         return res;
1984
1985                 if (op->dest.type == OP_DEST_PUSHF) {
1986                         if (!state->uaccess_stack) {
1987                                 state->uaccess_stack = 1;
1988                         } else if (state->uaccess_stack >> 31) {
1989                                 WARN_FUNC("PUSHF stack exhausted",
1990                                           insn->sec, insn->offset);
1991                                 return 1;
1992                         }
1993                         state->uaccess_stack <<= 1;
1994                         state->uaccess_stack  |= state->uaccess;
1995                 }
1996
1997                 if (op->src.type == OP_SRC_POPF) {
1998                         if (state->uaccess_stack) {
1999                                 state->uaccess = state->uaccess_stack & 1;
2000                                 state->uaccess_stack >>= 1;
2001                                 if (state->uaccess_stack == 1)
2002                                         state->uaccess_stack = 0;
2003                         }
2004                 }
2005         }
2006
2007         return 0;
2008 }
2009
2010 static bool insn_cfi_match(struct instruction *insn, struct cfi_state *cfi2)
2011 {
2012         struct cfi_state *cfi1 = &insn->cfi;
2013         int i;
2014
2015         if (memcmp(&cfi1->cfa, &cfi2->cfa, sizeof(cfi1->cfa))) {
2016
2017                 WARN_FUNC("stack state mismatch: cfa1=%d%+d cfa2=%d%+d",
2018                           insn->sec, insn->offset,
2019                           cfi1->cfa.base, cfi1->cfa.offset,
2020                           cfi2->cfa.base, cfi2->cfa.offset);
2021
2022         } else if (memcmp(&cfi1->regs, &cfi2->regs, sizeof(cfi1->regs))) {
2023                 for (i = 0; i < CFI_NUM_REGS; i++) {
2024                         if (!memcmp(&cfi1->regs[i], &cfi2->regs[i],
2025                                     sizeof(struct cfi_reg)))
2026                                 continue;
2027
2028                         WARN_FUNC("stack state mismatch: reg1[%d]=%d%+d reg2[%d]=%d%+d",
2029                                   insn->sec, insn->offset,
2030                                   i, cfi1->regs[i].base, cfi1->regs[i].offset,
2031                                   i, cfi2->regs[i].base, cfi2->regs[i].offset);
2032                         break;
2033                 }
2034
2035         } else if (cfi1->type != cfi2->type) {
2036
2037                 WARN_FUNC("stack state mismatch: type1=%d type2=%d",
2038                           insn->sec, insn->offset, cfi1->type, cfi2->type);
2039
2040         } else if (cfi1->drap != cfi2->drap ||
2041                    (cfi1->drap && cfi1->drap_reg != cfi2->drap_reg) ||
2042                    (cfi1->drap && cfi1->drap_offset != cfi2->drap_offset)) {
2043
2044                 WARN_FUNC("stack state mismatch: drap1=%d(%d,%d) drap2=%d(%d,%d)",
2045                           insn->sec, insn->offset,
2046                           cfi1->drap, cfi1->drap_reg, cfi1->drap_offset,
2047                           cfi2->drap, cfi2->drap_reg, cfi2->drap_offset);
2048
2049         } else
2050                 return true;
2051
2052         return false;
2053 }
2054
2055 static inline bool func_uaccess_safe(struct symbol *func)
2056 {
2057         if (func)
2058                 return func->uaccess_safe;
2059
2060         return false;
2061 }
2062
2063 static inline const char *call_dest_name(struct instruction *insn)
2064 {
2065         if (insn->call_dest)
2066                 return insn->call_dest->name;
2067
2068         return "{dynamic}";
2069 }
2070
2071 static int validate_call(struct instruction *insn, struct insn_state *state)
2072 {
2073         if (state->noinstr && state->instr <= 0 &&
2074             (!insn->call_dest || insn->call_dest->sec != insn->sec)) {
2075                 WARN_FUNC("call to %s() leaves .noinstr.text section",
2076                                 insn->sec, insn->offset, call_dest_name(insn));
2077                 return 1;
2078         }
2079
2080         if (state->uaccess && !func_uaccess_safe(insn->call_dest)) {
2081                 WARN_FUNC("call to %s() with UACCESS enabled",
2082                                 insn->sec, insn->offset, call_dest_name(insn));
2083                 return 1;
2084         }
2085
2086         if (state->df) {
2087                 WARN_FUNC("call to %s() with DF set",
2088                                 insn->sec, insn->offset, call_dest_name(insn));
2089                 return 1;
2090         }
2091
2092         return 0;
2093 }
2094
2095 static int validate_sibling_call(struct instruction *insn, struct insn_state *state)
2096 {
2097         if (has_modified_stack_frame(insn, state)) {
2098                 WARN_FUNC("sibling call from callable instruction with modified stack frame",
2099                                 insn->sec, insn->offset);
2100                 return 1;
2101         }
2102
2103         return validate_call(insn, state);
2104 }
2105
2106 static int validate_return(struct symbol *func, struct instruction *insn, struct insn_state *state)
2107 {
2108         if (state->noinstr && state->instr > 0) {
2109                 WARN_FUNC("return with instrumentation enabled",
2110                           insn->sec, insn->offset);
2111                 return 1;
2112         }
2113
2114         if (state->uaccess && !func_uaccess_safe(func)) {
2115                 WARN_FUNC("return with UACCESS enabled",
2116                           insn->sec, insn->offset);
2117                 return 1;
2118         }
2119
2120         if (!state->uaccess && func_uaccess_safe(func)) {
2121                 WARN_FUNC("return with UACCESS disabled from a UACCESS-safe function",
2122                           insn->sec, insn->offset);
2123                 return 1;
2124         }
2125
2126         if (state->df) {
2127                 WARN_FUNC("return with DF set",
2128                           insn->sec, insn->offset);
2129                 return 1;
2130         }
2131
2132         if (func && has_modified_stack_frame(insn, state)) {
2133                 WARN_FUNC("return with modified stack frame",
2134                           insn->sec, insn->offset);
2135                 return 1;
2136         }
2137
2138         if (state->cfi.bp_scratch) {
2139                 WARN_FUNC("BP used as a scratch register",
2140                           insn->sec, insn->offset);
2141                 return 1;
2142         }
2143
2144         return 0;
2145 }
2146
2147 /*
2148  * Follow the branch starting at the given instruction, and recursively follow
2149  * any other branches (jumps).  Meanwhile, track the frame pointer state at
2150  * each instruction and validate all the rules described in
2151  * tools/objtool/Documentation/stack-validation.txt.
2152  */
2153 static int validate_branch(struct objtool_file *file, struct symbol *func,
2154                            struct instruction *insn, struct insn_state state)
2155 {
2156         struct alternative *alt;
2157         struct instruction *next_insn;
2158         struct section *sec;
2159         u8 visited;
2160         int ret;
2161
2162         sec = insn->sec;
2163
2164         if (insn->alt_group && list_empty(&insn->alts)) {
2165                 WARN_FUNC("don't know how to handle branch to middle of alternative instruction group",
2166                           sec, insn->offset);
2167                 return 1;
2168         }
2169
2170         while (1) {
2171                 next_insn = next_insn_same_sec(file, insn);
2172
2173                 if (file->c_file && func && insn->func && func != insn->func->pfunc) {
2174                         WARN("%s() falls through to next function %s()",
2175                              func->name, insn->func->name);
2176                         return 1;
2177                 }
2178
2179                 if (func && insn->ignore) {
2180                         WARN_FUNC("BUG: why am I validating an ignored function?",
2181                                   sec, insn->offset);
2182                         return 1;
2183                 }
2184
2185                 visited = 1 << state.uaccess;
2186                 if (insn->visited) {
2187                         if (!insn->hint && !insn_cfi_match(insn, &state.cfi))
2188                                 return 1;
2189
2190                         if (insn->visited & visited)
2191                                 return 0;
2192                 }
2193
2194                 if (state.noinstr)
2195                         state.instr += insn->instr;
2196
2197                 if (insn->hint)
2198                         state.cfi = insn->cfi;
2199                 else
2200                         insn->cfi = state.cfi;
2201
2202                 insn->visited |= visited;
2203
2204                 if (!insn->ignore_alts) {
2205                         bool skip_orig = false;
2206
2207                         list_for_each_entry(alt, &insn->alts, list) {
2208                                 if (alt->skip_orig)
2209                                         skip_orig = true;
2210
2211                                 ret = validate_branch(file, func, alt->insn, state);
2212                                 if (ret) {
2213                                         if (backtrace)
2214                                                 BT_FUNC("(alt)", insn);
2215                                         return ret;
2216                                 }
2217                         }
2218
2219                         if (skip_orig)
2220                                 return 0;
2221                 }
2222
2223                 switch (insn->type) {
2224
2225                 case INSN_RETURN:
2226                         return validate_return(func, insn, &state);
2227
2228                 case INSN_CALL:
2229                 case INSN_CALL_DYNAMIC:
2230                         ret = validate_call(insn, &state);
2231                         if (ret)
2232                                 return ret;
2233
2234                         if (!no_fp && func && !is_fentry_call(insn) &&
2235                             !has_valid_stack_frame(&state)) {
2236                                 WARN_FUNC("call without frame pointer save/setup",
2237                                           sec, insn->offset);
2238                                 return 1;
2239                         }
2240
2241                         if (dead_end_function(file, insn->call_dest))
2242                                 return 0;
2243
2244                         break;
2245
2246                 case INSN_JUMP_CONDITIONAL:
2247                 case INSN_JUMP_UNCONDITIONAL:
2248                         if (func && is_sibling_call(insn)) {
2249                                 ret = validate_sibling_call(insn, &state);
2250                                 if (ret)
2251                                         return ret;
2252
2253                         } else if (insn->jump_dest) {
2254                                 ret = validate_branch(file, func,
2255                                                       insn->jump_dest, state);
2256                                 if (ret) {
2257                                         if (backtrace)
2258                                                 BT_FUNC("(branch)", insn);
2259                                         return ret;
2260                                 }
2261                         }
2262
2263                         if (insn->type == INSN_JUMP_UNCONDITIONAL)
2264                                 return 0;
2265
2266                         break;
2267
2268                 case INSN_JUMP_DYNAMIC:
2269                 case INSN_JUMP_DYNAMIC_CONDITIONAL:
2270                         if (func && is_sibling_call(insn)) {
2271                                 ret = validate_sibling_call(insn, &state);
2272                                 if (ret)
2273                                         return ret;
2274                         }
2275
2276                         if (insn->type == INSN_JUMP_DYNAMIC)
2277                                 return 0;
2278
2279                         break;
2280
2281                 case INSN_EXCEPTION_RETURN:
2282                         if (handle_insn_ops(insn, &state))
2283                                 return 1;
2284
2285                         /*
2286                          * This handles x86's sync_core() case, where we use an
2287                          * IRET to self. All 'normal' IRET instructions are in
2288                          * STT_NOTYPE entry symbols.
2289                          */
2290                         if (func)
2291                                 break;
2292
2293                         return 0;
2294
2295                 case INSN_CONTEXT_SWITCH:
2296                         if (func && (!next_insn || !next_insn->hint)) {
2297                                 WARN_FUNC("unsupported instruction in callable function",
2298                                           sec, insn->offset);
2299                                 return 1;
2300                         }
2301                         return 0;
2302
2303                 case INSN_STACK:
2304                         if (handle_insn_ops(insn, &state))
2305                                 return 1;
2306                         break;
2307
2308                 case INSN_STAC:
2309                         if (state.uaccess) {
2310                                 WARN_FUNC("recursive UACCESS enable", sec, insn->offset);
2311                                 return 1;
2312                         }
2313
2314                         state.uaccess = true;
2315                         break;
2316
2317                 case INSN_CLAC:
2318                         if (!state.uaccess && func) {
2319                                 WARN_FUNC("redundant UACCESS disable", sec, insn->offset);
2320                                 return 1;
2321                         }
2322
2323                         if (func_uaccess_safe(func) && !state.uaccess_stack) {
2324                                 WARN_FUNC("UACCESS-safe disables UACCESS", sec, insn->offset);
2325                                 return 1;
2326                         }
2327
2328                         state.uaccess = false;
2329                         break;
2330
2331                 case INSN_STD:
2332                         if (state.df)
2333                                 WARN_FUNC("recursive STD", sec, insn->offset);
2334
2335                         state.df = true;
2336                         break;
2337
2338                 case INSN_CLD:
2339                         if (!state.df && func)
2340                                 WARN_FUNC("redundant CLD", sec, insn->offset);
2341
2342                         state.df = false;
2343                         break;
2344
2345                 default:
2346                         break;
2347                 }
2348
2349                 if (insn->dead_end)
2350                         return 0;
2351
2352                 if (!next_insn) {
2353                         if (state.cfi.cfa.base == CFI_UNDEFINED)
2354                                 return 0;
2355                         WARN("%s: unexpected end of section", sec->name);
2356                         return 1;
2357                 }
2358
2359                 insn = next_insn;
2360         }
2361
2362         return 0;
2363 }
2364
2365 static int validate_unwind_hints(struct objtool_file *file, struct section *sec)
2366 {
2367         struct instruction *insn;
2368         struct insn_state state;
2369         int ret, warnings = 0;
2370
2371         if (!file->hints)
2372                 return 0;
2373
2374         init_insn_state(&state, sec);
2375
2376         if (sec) {
2377                 insn = find_insn(file, sec, 0);
2378                 if (!insn)
2379                         return 0;
2380         } else {
2381                 insn = list_first_entry(&file->insn_list, typeof(*insn), list);
2382         }
2383
2384         while (&insn->list != &file->insn_list && (!sec || insn->sec == sec)) {
2385                 if (insn->hint && !insn->visited) {
2386                         ret = validate_branch(file, insn->func, insn, state);
2387                         if (ret && backtrace)
2388                                 BT_FUNC("<=== (hint)", insn);
2389                         warnings += ret;
2390                 }
2391
2392                 insn = list_next_entry(insn, list);
2393         }
2394
2395         return warnings;
2396 }
2397
2398 static int validate_retpoline(struct objtool_file *file)
2399 {
2400         struct instruction *insn;
2401         int warnings = 0;
2402
2403         for_each_insn(file, insn) {
2404                 if (insn->type != INSN_JUMP_DYNAMIC &&
2405                     insn->type != INSN_CALL_DYNAMIC)
2406                         continue;
2407
2408                 if (insn->retpoline_safe)
2409                         continue;
2410
2411                 /*
2412                  * .init.text code is ran before userspace and thus doesn't
2413                  * strictly need retpolines, except for modules which are
2414                  * loaded late, they very much do need retpoline in their
2415                  * .init.text
2416                  */
2417                 if (!strcmp(insn->sec->name, ".init.text") && !module)
2418                         continue;
2419
2420                 WARN_FUNC("indirect %s found in RETPOLINE build",
2421                           insn->sec, insn->offset,
2422                           insn->type == INSN_JUMP_DYNAMIC ? "jump" : "call");
2423
2424                 warnings++;
2425         }
2426
2427         return warnings;
2428 }
2429
2430 static bool is_kasan_insn(struct instruction *insn)
2431 {
2432         return (insn->type == INSN_CALL &&
2433                 !strcmp(insn->call_dest->name, "__asan_handle_no_return"));
2434 }
2435
2436 static bool is_ubsan_insn(struct instruction *insn)
2437 {
2438         return (insn->type == INSN_CALL &&
2439                 !strcmp(insn->call_dest->name,
2440                         "__ubsan_handle_builtin_unreachable"));
2441 }
2442
2443 static bool ignore_unreachable_insn(struct instruction *insn)
2444 {
2445         int i;
2446
2447         if (insn->ignore || insn->type == INSN_NOP)
2448                 return true;
2449
2450         /*
2451          * Ignore any unused exceptions.  This can happen when a whitelisted
2452          * function has an exception table entry.
2453          *
2454          * Also ignore alternative replacement instructions.  This can happen
2455          * when a whitelisted function uses one of the ALTERNATIVE macros.
2456          */
2457         if (!strcmp(insn->sec->name, ".fixup") ||
2458             !strcmp(insn->sec->name, ".altinstr_replacement") ||
2459             !strcmp(insn->sec->name, ".altinstr_aux"))
2460                 return true;
2461
2462         if (!insn->func)
2463                 return false;
2464
2465         /*
2466          * CONFIG_UBSAN_TRAP inserts a UD2 when it sees
2467          * __builtin_unreachable().  The BUG() macro has an unreachable() after
2468          * the UD2, which causes GCC's undefined trap logic to emit another UD2
2469          * (or occasionally a JMP to UD2).
2470          */
2471         if (list_prev_entry(insn, list)->dead_end &&
2472             (insn->type == INSN_BUG ||
2473              (insn->type == INSN_JUMP_UNCONDITIONAL &&
2474               insn->jump_dest && insn->jump_dest->type == INSN_BUG)))
2475                 return true;
2476
2477         /*
2478          * Check if this (or a subsequent) instruction is related to
2479          * CONFIG_UBSAN or CONFIG_KASAN.
2480          *
2481          * End the search at 5 instructions to avoid going into the weeds.
2482          */
2483         for (i = 0; i < 5; i++) {
2484
2485                 if (is_kasan_insn(insn) || is_ubsan_insn(insn))
2486                         return true;
2487
2488                 if (insn->type == INSN_JUMP_UNCONDITIONAL) {
2489                         if (insn->jump_dest &&
2490                             insn->jump_dest->func == insn->func) {
2491                                 insn = insn->jump_dest;
2492                                 continue;
2493                         }
2494
2495                         break;
2496                 }
2497
2498                 if (insn->offset + insn->len >= insn->func->offset + insn->func->len)
2499                         break;
2500
2501                 insn = list_next_entry(insn, list);
2502         }
2503
2504         return false;
2505 }
2506
2507 static int validate_symbol(struct objtool_file *file, struct section *sec,
2508                            struct symbol *sym, struct insn_state *state)
2509 {
2510         struct instruction *insn;
2511         int ret;
2512
2513         if (!sym->len) {
2514                 WARN("%s() is missing an ELF size annotation", sym->name);
2515                 return 1;
2516         }
2517
2518         if (sym->pfunc != sym || sym->alias != sym)
2519                 return 0;
2520
2521         insn = find_insn(file, sec, sym->offset);
2522         if (!insn || insn->ignore || insn->visited)
2523                 return 0;
2524
2525         state->uaccess = sym->uaccess_safe;
2526
2527         ret = validate_branch(file, insn->func, insn, *state);
2528         if (ret && backtrace)
2529                 BT_FUNC("<=== (sym)", insn);
2530         return ret;
2531 }
2532
2533 static int validate_section(struct objtool_file *file, struct section *sec)
2534 {
2535         struct insn_state state;
2536         struct symbol *func;
2537         int warnings = 0;
2538
2539         list_for_each_entry(func, &sec->symbol_list, list) {
2540                 if (func->type != STT_FUNC)
2541                         continue;
2542
2543                 init_insn_state(&state, sec);
2544                 state.cfi.cfa = initial_func_cfi.cfa;
2545                 memcpy(&state.cfi.regs, &initial_func_cfi.regs,
2546                        CFI_NUM_REGS * sizeof(struct cfi_reg));
2547                 state.cfi.stack_size = initial_func_cfi.cfa.offset;
2548
2549                 warnings += validate_symbol(file, sec, func, &state);
2550         }
2551
2552         return warnings;
2553 }
2554
2555 static int validate_vmlinux_functions(struct objtool_file *file)
2556 {
2557         struct section *sec;
2558         int warnings = 0;
2559
2560         sec = find_section_by_name(file->elf, ".noinstr.text");
2561         if (!sec)
2562                 return 0;
2563
2564         warnings += validate_section(file, sec);
2565         warnings += validate_unwind_hints(file, sec);
2566
2567         return warnings;
2568 }
2569
2570 static int validate_functions(struct objtool_file *file)
2571 {
2572         struct section *sec;
2573         int warnings = 0;
2574
2575         for_each_sec(file, sec) {
2576                 if (!(sec->sh.sh_flags & SHF_EXECINSTR))
2577                         continue;
2578
2579                 warnings += validate_section(file, sec);
2580         }
2581
2582         return warnings;
2583 }
2584
2585 static int validate_reachable_instructions(struct objtool_file *file)
2586 {
2587         struct instruction *insn;
2588
2589         if (file->ignore_unreachables)
2590                 return 0;
2591
2592         for_each_insn(file, insn) {
2593                 if (insn->visited || ignore_unreachable_insn(insn))
2594                         continue;
2595
2596                 WARN_FUNC("unreachable instruction", insn->sec, insn->offset);
2597                 return 1;
2598         }
2599
2600         return 0;
2601 }
2602
2603 static struct objtool_file file;
2604
2605 int check(const char *_objname, bool orc)
2606 {
2607         int ret, warnings = 0;
2608
2609         objname = _objname;
2610
2611         file.elf = elf_read(objname, orc ? O_RDWR : O_RDONLY);
2612         if (!file.elf)
2613                 return 1;
2614
2615         INIT_LIST_HEAD(&file.insn_list);
2616         hash_init(file.insn_hash);
2617         file.c_file = find_section_by_name(file.elf, ".comment");
2618         file.ignore_unreachables = no_unreachable;
2619         file.hints = false;
2620
2621         arch_initial_func_cfi_state(&initial_func_cfi);
2622
2623         ret = decode_sections(&file);
2624         if (ret < 0)
2625                 goto out;
2626         warnings += ret;
2627
2628         if (list_empty(&file.insn_list))
2629                 goto out;
2630
2631         if (vmlinux && !validate_dup) {
2632                 ret = validate_vmlinux_functions(&file);
2633                 if (ret < 0)
2634                         goto out;
2635
2636                 warnings += ret;
2637                 goto out;
2638         }
2639
2640         if (retpoline) {
2641                 ret = validate_retpoline(&file);
2642                 if (ret < 0)
2643                         return ret;
2644                 warnings += ret;
2645         }
2646
2647         ret = validate_functions(&file);
2648         if (ret < 0)
2649                 goto out;
2650         warnings += ret;
2651
2652         ret = validate_unwind_hints(&file, NULL);
2653         if (ret < 0)
2654                 goto out;
2655         warnings += ret;
2656
2657         if (!warnings) {
2658                 ret = validate_reachable_instructions(&file);
2659                 if (ret < 0)
2660                         goto out;
2661                 warnings += ret;
2662         }
2663
2664         if (orc) {
2665                 ret = create_orc(&file);
2666                 if (ret < 0)
2667                         goto out;
2668
2669                 ret = create_orc_sections(&file);
2670                 if (ret < 0)
2671                         goto out;
2672
2673                 ret = elf_write(file.elf);
2674                 if (ret < 0)
2675                         goto out;
2676         }
2677
2678 out:
2679         if (ret < 0) {
2680                 /*
2681                  *  Fatal error.  The binary is corrupt or otherwise broken in
2682                  *  some way, or objtool itself is broken.  Fail the kernel
2683                  *  build.
2684                  */
2685                 return ret;
2686         }
2687
2688         return 0;
2689 }