objtool: Rework the elf_rebuild_reloc_section() logic
[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 <arch/elf.h>
10 #include <objtool/builtin.h>
11 #include <objtool/cfi.h>
12 #include <objtool/arch.h>
13 #include <objtool/check.h>
14 #include <objtool/special.h>
15 #include <objtool/warn.h>
16 #include <objtool/endianness.h>
17
18 #include <linux/objtool.h>
19 #include <linux/hashtable.h>
20 #include <linux/kernel.h>
21 #include <linux/static_call_types.h>
22
23 struct alternative {
24         struct list_head list;
25         struct instruction *insn;
26         bool skip_orig;
27 };
28
29 struct cfi_init_state initial_func_cfi;
30
31 struct instruction *find_insn(struct objtool_file *file,
32                               struct section *sec, unsigned long offset)
33 {
34         struct instruction *insn;
35
36         hash_for_each_possible(file->insn_hash, insn, hash, sec_offset_hash(sec, offset)) {
37                 if (insn->sec == sec && insn->offset == offset)
38                         return insn;
39         }
40
41         return NULL;
42 }
43
44 static struct instruction *next_insn_same_sec(struct objtool_file *file,
45                                               struct instruction *insn)
46 {
47         struct instruction *next = list_next_entry(insn, list);
48
49         if (!next || &next->list == &file->insn_list || next->sec != insn->sec)
50                 return NULL;
51
52         return next;
53 }
54
55 static struct instruction *next_insn_same_func(struct objtool_file *file,
56                                                struct instruction *insn)
57 {
58         struct instruction *next = list_next_entry(insn, list);
59         struct symbol *func = insn->func;
60
61         if (!func)
62                 return NULL;
63
64         if (&next->list != &file->insn_list && next->func == func)
65                 return next;
66
67         /* Check if we're already in the subfunction: */
68         if (func == func->cfunc)
69                 return NULL;
70
71         /* Move to the subfunction: */
72         return find_insn(file, func->cfunc->sec, func->cfunc->offset);
73 }
74
75 static struct instruction *prev_insn_same_sym(struct objtool_file *file,
76                                                struct instruction *insn)
77 {
78         struct instruction *prev = list_prev_entry(insn, list);
79
80         if (&prev->list != &file->insn_list && prev->func == insn->func)
81                 return prev;
82
83         return NULL;
84 }
85
86 #define func_for_each_insn(file, func, insn)                            \
87         for (insn = find_insn(file, func->sec, func->offset);           \
88              insn;                                                      \
89              insn = next_insn_same_func(file, insn))
90
91 #define sym_for_each_insn(file, sym, insn)                              \
92         for (insn = find_insn(file, sym->sec, sym->offset);             \
93              insn && &insn->list != &file->insn_list &&                 \
94                 insn->sec == sym->sec &&                                \
95                 insn->offset < sym->offset + sym->len;                  \
96              insn = list_next_entry(insn, list))
97
98 #define sym_for_each_insn_continue_reverse(file, sym, insn)             \
99         for (insn = list_prev_entry(insn, list);                        \
100              &insn->list != &file->insn_list &&                         \
101                 insn->sec == sym->sec && insn->offset >= sym->offset;   \
102              insn = list_prev_entry(insn, list))
103
104 #define sec_for_each_insn_from(file, insn)                              \
105         for (; insn; insn = next_insn_same_sec(file, insn))
106
107 #define sec_for_each_insn_continue(file, insn)                          \
108         for (insn = next_insn_same_sec(file, insn); insn;               \
109              insn = next_insn_same_sec(file, insn))
110
111 static bool is_sibling_call(struct instruction *insn)
112 {
113         /*
114          * Assume only ELF functions can make sibling calls.  This ensures
115          * sibling call detection consistency between vmlinux.o and individual
116          * objects.
117          */
118         if (!insn->func)
119                 return false;
120
121         /* An indirect jump is either a sibling call or a jump to a table. */
122         if (insn->type == INSN_JUMP_DYNAMIC)
123                 return list_empty(&insn->alts);
124
125         /* add_jump_destinations() sets insn->call_dest for sibling calls. */
126         return (is_static_jump(insn) && insn->call_dest);
127 }
128
129 /*
130  * This checks to see if the given function is a "noreturn" function.
131  *
132  * For global functions which are outside the scope of this object file, we
133  * have to keep a manual list of them.
134  *
135  * For local functions, we have to detect them manually by simply looking for
136  * the lack of a return instruction.
137  */
138 static bool __dead_end_function(struct objtool_file *file, struct symbol *func,
139                                 int recursion)
140 {
141         int i;
142         struct instruction *insn;
143         bool empty = true;
144
145         /*
146          * Unfortunately these have to be hard coded because the noreturn
147          * attribute isn't provided in ELF data.
148          */
149         static const char * const global_noreturns[] = {
150                 "__stack_chk_fail",
151                 "panic",
152                 "do_exit",
153                 "do_task_dead",
154                 "__module_put_and_exit",
155                 "complete_and_exit",
156                 "__reiserfs_panic",
157                 "lbug_with_loc",
158                 "fortify_panic",
159                 "usercopy_abort",
160                 "machine_real_restart",
161                 "rewind_stack_do_exit",
162                 "kunit_try_catch_throw",
163                 "xen_start_kernel",
164         };
165
166         if (!func)
167                 return false;
168
169         if (func->bind == STB_WEAK)
170                 return false;
171
172         if (func->bind == STB_GLOBAL)
173                 for (i = 0; i < ARRAY_SIZE(global_noreturns); i++)
174                         if (!strcmp(func->name, global_noreturns[i]))
175                                 return true;
176
177         if (!func->len)
178                 return false;
179
180         insn = find_insn(file, func->sec, func->offset);
181         if (!insn->func)
182                 return false;
183
184         func_for_each_insn(file, func, insn) {
185                 empty = false;
186
187                 if (insn->type == INSN_RETURN)
188                         return false;
189         }
190
191         if (empty)
192                 return false;
193
194         /*
195          * A function can have a sibling call instead of a return.  In that
196          * case, the function's dead-end status depends on whether the target
197          * of the sibling call returns.
198          */
199         func_for_each_insn(file, func, insn) {
200                 if (is_sibling_call(insn)) {
201                         struct instruction *dest = insn->jump_dest;
202
203                         if (!dest)
204                                 /* sibling call to another file */
205                                 return false;
206
207                         /* local sibling call */
208                         if (recursion == 5) {
209                                 /*
210                                  * Infinite recursion: two functions have
211                                  * sibling calls to each other.  This is a very
212                                  * rare case.  It means they aren't dead ends.
213                                  */
214                                 return false;
215                         }
216
217                         return __dead_end_function(file, dest->func, recursion+1);
218                 }
219         }
220
221         return true;
222 }
223
224 static bool dead_end_function(struct objtool_file *file, struct symbol *func)
225 {
226         return __dead_end_function(file, func, 0);
227 }
228
229 static void init_cfi_state(struct cfi_state *cfi)
230 {
231         int i;
232
233         for (i = 0; i < CFI_NUM_REGS; i++) {
234                 cfi->regs[i].base = CFI_UNDEFINED;
235                 cfi->vals[i].base = CFI_UNDEFINED;
236         }
237         cfi->cfa.base = CFI_UNDEFINED;
238         cfi->drap_reg = CFI_UNDEFINED;
239         cfi->drap_offset = -1;
240 }
241
242 static void init_insn_state(struct insn_state *state, struct section *sec)
243 {
244         memset(state, 0, sizeof(*state));
245         init_cfi_state(&state->cfi);
246
247         /*
248          * We need the full vmlinux for noinstr validation, otherwise we can
249          * not correctly determine insn->call_dest->sec (external symbols do
250          * not have a section).
251          */
252         if (vmlinux && noinstr && sec)
253                 state->noinstr = sec->noinstr;
254 }
255
256 /*
257  * Call the arch-specific instruction decoder for all the instructions and add
258  * them to the global instruction list.
259  */
260 static int decode_instructions(struct objtool_file *file)
261 {
262         struct section *sec;
263         struct symbol *func;
264         unsigned long offset;
265         struct instruction *insn;
266         unsigned long nr_insns = 0;
267         int ret;
268
269         for_each_sec(file, sec) {
270
271                 if (!(sec->sh.sh_flags & SHF_EXECINSTR))
272                         continue;
273
274                 if (strcmp(sec->name, ".altinstr_replacement") &&
275                     strcmp(sec->name, ".altinstr_aux") &&
276                     strncmp(sec->name, ".discard.", 9))
277                         sec->text = true;
278
279                 if (!strcmp(sec->name, ".noinstr.text") ||
280                     !strcmp(sec->name, ".entry.text"))
281                         sec->noinstr = true;
282
283                 for (offset = 0; offset < sec->len; offset += insn->len) {
284                         insn = malloc(sizeof(*insn));
285                         if (!insn) {
286                                 WARN("malloc failed");
287                                 return -1;
288                         }
289                         memset(insn, 0, sizeof(*insn));
290                         INIT_LIST_HEAD(&insn->alts);
291                         INIT_LIST_HEAD(&insn->stack_ops);
292                         init_cfi_state(&insn->cfi);
293
294                         insn->sec = sec;
295                         insn->offset = offset;
296
297                         ret = arch_decode_instruction(file->elf, sec, offset,
298                                                       sec->len - offset,
299                                                       &insn->len, &insn->type,
300                                                       &insn->immediate,
301                                                       &insn->stack_ops);
302                         if (ret)
303                                 goto err;
304
305                         hash_add(file->insn_hash, &insn->hash, sec_offset_hash(sec, insn->offset));
306                         list_add_tail(&insn->list, &file->insn_list);
307                         nr_insns++;
308                 }
309
310                 list_for_each_entry(func, &sec->symbol_list, list) {
311                         if (func->type != STT_FUNC || func->alias != func)
312                                 continue;
313
314                         if (!find_insn(file, sec, func->offset)) {
315                                 WARN("%s(): can't find starting instruction",
316                                      func->name);
317                                 return -1;
318                         }
319
320                         sym_for_each_insn(file, func, insn)
321                                 insn->func = func;
322                 }
323         }
324
325         if (stats)
326                 printf("nr_insns: %lu\n", nr_insns);
327
328         return 0;
329
330 err:
331         free(insn);
332         return ret;
333 }
334
335 static struct instruction *find_last_insn(struct objtool_file *file,
336                                           struct section *sec)
337 {
338         struct instruction *insn = NULL;
339         unsigned int offset;
340         unsigned int end = (sec->len > 10) ? sec->len - 10 : 0;
341
342         for (offset = sec->len - 1; offset >= end && !insn; offset--)
343                 insn = find_insn(file, sec, offset);
344
345         return insn;
346 }
347
348 /*
349  * Mark "ud2" instructions and manually annotated dead ends.
350  */
351 static int add_dead_ends(struct objtool_file *file)
352 {
353         struct section *sec;
354         struct reloc *reloc;
355         struct instruction *insn;
356
357         /*
358          * By default, "ud2" is a dead end unless otherwise annotated, because
359          * GCC 7 inserts it for certain divide-by-zero cases.
360          */
361         for_each_insn(file, insn)
362                 if (insn->type == INSN_BUG)
363                         insn->dead_end = true;
364
365         /*
366          * Check for manually annotated dead ends.
367          */
368         sec = find_section_by_name(file->elf, ".rela.discard.unreachable");
369         if (!sec)
370                 goto reachable;
371
372         list_for_each_entry(reloc, &sec->reloc_list, list) {
373                 if (reloc->sym->type != STT_SECTION) {
374                         WARN("unexpected relocation symbol type in %s", sec->name);
375                         return -1;
376                 }
377                 insn = find_insn(file, reloc->sym->sec, reloc->addend);
378                 if (insn)
379                         insn = list_prev_entry(insn, list);
380                 else if (reloc->addend == reloc->sym->sec->len) {
381                         insn = find_last_insn(file, reloc->sym->sec);
382                         if (!insn) {
383                                 WARN("can't find unreachable insn at %s+0x%x",
384                                      reloc->sym->sec->name, reloc->addend);
385                                 return -1;
386                         }
387                 } else {
388                         WARN("can't find unreachable insn at %s+0x%x",
389                              reloc->sym->sec->name, reloc->addend);
390                         return -1;
391                 }
392
393                 insn->dead_end = true;
394         }
395
396 reachable:
397         /*
398          * These manually annotated reachable checks are needed for GCC 4.4,
399          * where the Linux unreachable() macro isn't supported.  In that case
400          * GCC doesn't know the "ud2" is fatal, so it generates code as if it's
401          * not a dead end.
402          */
403         sec = find_section_by_name(file->elf, ".rela.discard.reachable");
404         if (!sec)
405                 return 0;
406
407         list_for_each_entry(reloc, &sec->reloc_list, list) {
408                 if (reloc->sym->type != STT_SECTION) {
409                         WARN("unexpected relocation symbol type in %s", sec->name);
410                         return -1;
411                 }
412                 insn = find_insn(file, reloc->sym->sec, reloc->addend);
413                 if (insn)
414                         insn = list_prev_entry(insn, list);
415                 else if (reloc->addend == reloc->sym->sec->len) {
416                         insn = find_last_insn(file, reloc->sym->sec);
417                         if (!insn) {
418                                 WARN("can't find reachable insn at %s+0x%x",
419                                      reloc->sym->sec->name, reloc->addend);
420                                 return -1;
421                         }
422                 } else {
423                         WARN("can't find reachable insn at %s+0x%x",
424                              reloc->sym->sec->name, reloc->addend);
425                         return -1;
426                 }
427
428                 insn->dead_end = false;
429         }
430
431         return 0;
432 }
433
434 static int create_static_call_sections(struct objtool_file *file)
435 {
436         struct section *sec, *reloc_sec;
437         struct reloc *reloc;
438         struct static_call_site *site;
439         struct instruction *insn;
440         struct symbol *key_sym;
441         char *key_name, *tmp;
442         int idx;
443
444         sec = find_section_by_name(file->elf, ".static_call_sites");
445         if (sec) {
446                 INIT_LIST_HEAD(&file->static_call_list);
447                 WARN("file already has .static_call_sites section, skipping");
448                 return 0;
449         }
450
451         if (list_empty(&file->static_call_list))
452                 return 0;
453
454         idx = 0;
455         list_for_each_entry(insn, &file->static_call_list, static_call_node)
456                 idx++;
457
458         sec = elf_create_section(file->elf, ".static_call_sites", SHF_WRITE,
459                                  sizeof(struct static_call_site), idx);
460         if (!sec)
461                 return -1;
462
463         reloc_sec = elf_create_reloc_section(file->elf, sec, SHT_RELA);
464         if (!reloc_sec)
465                 return -1;
466
467         idx = 0;
468         list_for_each_entry(insn, &file->static_call_list, static_call_node) {
469
470                 site = (struct static_call_site *)sec->data->d_buf + idx;
471                 memset(site, 0, sizeof(struct static_call_site));
472
473                 /* populate reloc for 'addr' */
474                 reloc = malloc(sizeof(*reloc));
475
476                 if (!reloc) {
477                         perror("malloc");
478                         return -1;
479                 }
480                 memset(reloc, 0, sizeof(*reloc));
481
482                 insn_to_reloc_sym_addend(insn->sec, insn->offset, reloc);
483                 if (!reloc->sym) {
484                         WARN_FUNC("static call tramp: missing containing symbol",
485                                   insn->sec, insn->offset);
486                         return -1;
487                 }
488
489                 reloc->type = R_X86_64_PC32;
490                 reloc->offset = idx * sizeof(struct static_call_site);
491                 reloc->sec = reloc_sec;
492                 elf_add_reloc(file->elf, reloc);
493
494                 /* find key symbol */
495                 key_name = strdup(insn->call_dest->name);
496                 if (!key_name) {
497                         perror("strdup");
498                         return -1;
499                 }
500                 if (strncmp(key_name, STATIC_CALL_TRAMP_PREFIX_STR,
501                             STATIC_CALL_TRAMP_PREFIX_LEN)) {
502                         WARN("static_call: trampoline name malformed: %s", key_name);
503                         return -1;
504                 }
505                 tmp = key_name + STATIC_CALL_TRAMP_PREFIX_LEN - STATIC_CALL_KEY_PREFIX_LEN;
506                 memcpy(tmp, STATIC_CALL_KEY_PREFIX_STR, STATIC_CALL_KEY_PREFIX_LEN);
507
508                 key_sym = find_symbol_by_name(file->elf, tmp);
509                 if (!key_sym) {
510                         if (!module) {
511                                 WARN("static_call: can't find static_call_key symbol: %s", tmp);
512                                 return -1;
513                         }
514
515                         /*
516                          * For modules(), the key might not be exported, which
517                          * means the module can make static calls but isn't
518                          * allowed to change them.
519                          *
520                          * In that case we temporarily set the key to be the
521                          * trampoline address.  This is fixed up in
522                          * static_call_add_module().
523                          */
524                         key_sym = insn->call_dest;
525                 }
526                 free(key_name);
527
528                 /* populate reloc for 'key' */
529                 reloc = malloc(sizeof(*reloc));
530                 if (!reloc) {
531                         perror("malloc");
532                         return -1;
533                 }
534                 memset(reloc, 0, sizeof(*reloc));
535                 reloc->sym = key_sym;
536                 reloc->addend = is_sibling_call(insn) ? STATIC_CALL_SITE_TAIL : 0;
537                 reloc->type = R_X86_64_PC32;
538                 reloc->offset = idx * sizeof(struct static_call_site) + 4;
539                 reloc->sec = reloc_sec;
540                 elf_add_reloc(file->elf, reloc);
541
542                 idx++;
543         }
544
545         return 0;
546 }
547
548 static int create_mcount_loc_sections(struct objtool_file *file)
549 {
550         struct section *sec, *reloc_sec;
551         struct reloc *reloc;
552         unsigned long *loc;
553         struct instruction *insn;
554         int idx;
555
556         sec = find_section_by_name(file->elf, "__mcount_loc");
557         if (sec) {
558                 INIT_LIST_HEAD(&file->mcount_loc_list);
559                 WARN("file already has __mcount_loc section, skipping");
560                 return 0;
561         }
562
563         if (list_empty(&file->mcount_loc_list))
564                 return 0;
565
566         idx = 0;
567         list_for_each_entry(insn, &file->mcount_loc_list, mcount_loc_node)
568                 idx++;
569
570         sec = elf_create_section(file->elf, "__mcount_loc", 0, sizeof(unsigned long), idx);
571         if (!sec)
572                 return -1;
573
574         reloc_sec = elf_create_reloc_section(file->elf, sec, SHT_RELA);
575         if (!reloc_sec)
576                 return -1;
577
578         idx = 0;
579         list_for_each_entry(insn, &file->mcount_loc_list, mcount_loc_node) {
580
581                 loc = (unsigned long *)sec->data->d_buf + idx;
582                 memset(loc, 0, sizeof(unsigned long));
583
584                 reloc = malloc(sizeof(*reloc));
585                 if (!reloc) {
586                         perror("malloc");
587                         return -1;
588                 }
589                 memset(reloc, 0, sizeof(*reloc));
590
591                 if (insn->sec->sym) {
592                         reloc->sym = insn->sec->sym;
593                         reloc->addend = insn->offset;
594                 } else {
595                         reloc->sym = find_symbol_containing(insn->sec, insn->offset);
596
597                         if (!reloc->sym) {
598                                 WARN("missing symbol for insn at offset 0x%lx\n",
599                                      insn->offset);
600                                 return -1;
601                         }
602
603                         reloc->addend = insn->offset - reloc->sym->offset;
604                 }
605
606                 reloc->type = R_X86_64_64;
607                 reloc->offset = idx * sizeof(unsigned long);
608                 reloc->sec = reloc_sec;
609                 elf_add_reloc(file->elf, reloc);
610
611                 idx++;
612         }
613
614         return 0;
615 }
616
617 /*
618  * Warnings shouldn't be reported for ignored functions.
619  */
620 static void add_ignores(struct objtool_file *file)
621 {
622         struct instruction *insn;
623         struct section *sec;
624         struct symbol *func;
625         struct reloc *reloc;
626
627         sec = find_section_by_name(file->elf, ".rela.discard.func_stack_frame_non_standard");
628         if (!sec)
629                 return;
630
631         list_for_each_entry(reloc, &sec->reloc_list, list) {
632                 switch (reloc->sym->type) {
633                 case STT_FUNC:
634                         func = reloc->sym;
635                         break;
636
637                 case STT_SECTION:
638                         func = find_func_by_offset(reloc->sym->sec, reloc->addend);
639                         if (!func)
640                                 continue;
641                         break;
642
643                 default:
644                         WARN("unexpected relocation symbol type in %s: %d", sec->name, reloc->sym->type);
645                         continue;
646                 }
647
648                 func_for_each_insn(file, func, insn)
649                         insn->ignore = true;
650         }
651 }
652
653 /*
654  * This is a whitelist of functions that is allowed to be called with AC set.
655  * The list is meant to be minimal and only contains compiler instrumentation
656  * ABI and a few functions used to implement *_{to,from}_user() functions.
657  *
658  * These functions must not directly change AC, but may PUSHF/POPF.
659  */
660 static const char *uaccess_safe_builtin[] = {
661         /* KASAN */
662         "kasan_report",
663         "kasan_check_range",
664         /* KASAN out-of-line */
665         "__asan_loadN_noabort",
666         "__asan_load1_noabort",
667         "__asan_load2_noabort",
668         "__asan_load4_noabort",
669         "__asan_load8_noabort",
670         "__asan_load16_noabort",
671         "__asan_storeN_noabort",
672         "__asan_store1_noabort",
673         "__asan_store2_noabort",
674         "__asan_store4_noabort",
675         "__asan_store8_noabort",
676         "__asan_store16_noabort",
677         "__kasan_check_read",
678         "__kasan_check_write",
679         /* KASAN in-line */
680         "__asan_report_load_n_noabort",
681         "__asan_report_load1_noabort",
682         "__asan_report_load2_noabort",
683         "__asan_report_load4_noabort",
684         "__asan_report_load8_noabort",
685         "__asan_report_load16_noabort",
686         "__asan_report_store_n_noabort",
687         "__asan_report_store1_noabort",
688         "__asan_report_store2_noabort",
689         "__asan_report_store4_noabort",
690         "__asan_report_store8_noabort",
691         "__asan_report_store16_noabort",
692         /* KCSAN */
693         "__kcsan_check_access",
694         "kcsan_found_watchpoint",
695         "kcsan_setup_watchpoint",
696         "kcsan_check_scoped_accesses",
697         "kcsan_disable_current",
698         "kcsan_enable_current_nowarn",
699         /* KCSAN/TSAN */
700         "__tsan_func_entry",
701         "__tsan_func_exit",
702         "__tsan_read_range",
703         "__tsan_write_range",
704         "__tsan_read1",
705         "__tsan_read2",
706         "__tsan_read4",
707         "__tsan_read8",
708         "__tsan_read16",
709         "__tsan_write1",
710         "__tsan_write2",
711         "__tsan_write4",
712         "__tsan_write8",
713         "__tsan_write16",
714         "__tsan_read_write1",
715         "__tsan_read_write2",
716         "__tsan_read_write4",
717         "__tsan_read_write8",
718         "__tsan_read_write16",
719         "__tsan_atomic8_load",
720         "__tsan_atomic16_load",
721         "__tsan_atomic32_load",
722         "__tsan_atomic64_load",
723         "__tsan_atomic8_store",
724         "__tsan_atomic16_store",
725         "__tsan_atomic32_store",
726         "__tsan_atomic64_store",
727         "__tsan_atomic8_exchange",
728         "__tsan_atomic16_exchange",
729         "__tsan_atomic32_exchange",
730         "__tsan_atomic64_exchange",
731         "__tsan_atomic8_fetch_add",
732         "__tsan_atomic16_fetch_add",
733         "__tsan_atomic32_fetch_add",
734         "__tsan_atomic64_fetch_add",
735         "__tsan_atomic8_fetch_sub",
736         "__tsan_atomic16_fetch_sub",
737         "__tsan_atomic32_fetch_sub",
738         "__tsan_atomic64_fetch_sub",
739         "__tsan_atomic8_fetch_and",
740         "__tsan_atomic16_fetch_and",
741         "__tsan_atomic32_fetch_and",
742         "__tsan_atomic64_fetch_and",
743         "__tsan_atomic8_fetch_or",
744         "__tsan_atomic16_fetch_or",
745         "__tsan_atomic32_fetch_or",
746         "__tsan_atomic64_fetch_or",
747         "__tsan_atomic8_fetch_xor",
748         "__tsan_atomic16_fetch_xor",
749         "__tsan_atomic32_fetch_xor",
750         "__tsan_atomic64_fetch_xor",
751         "__tsan_atomic8_fetch_nand",
752         "__tsan_atomic16_fetch_nand",
753         "__tsan_atomic32_fetch_nand",
754         "__tsan_atomic64_fetch_nand",
755         "__tsan_atomic8_compare_exchange_strong",
756         "__tsan_atomic16_compare_exchange_strong",
757         "__tsan_atomic32_compare_exchange_strong",
758         "__tsan_atomic64_compare_exchange_strong",
759         "__tsan_atomic8_compare_exchange_weak",
760         "__tsan_atomic16_compare_exchange_weak",
761         "__tsan_atomic32_compare_exchange_weak",
762         "__tsan_atomic64_compare_exchange_weak",
763         "__tsan_atomic8_compare_exchange_val",
764         "__tsan_atomic16_compare_exchange_val",
765         "__tsan_atomic32_compare_exchange_val",
766         "__tsan_atomic64_compare_exchange_val",
767         "__tsan_atomic_thread_fence",
768         "__tsan_atomic_signal_fence",
769         /* KCOV */
770         "write_comp_data",
771         "check_kcov_mode",
772         "__sanitizer_cov_trace_pc",
773         "__sanitizer_cov_trace_const_cmp1",
774         "__sanitizer_cov_trace_const_cmp2",
775         "__sanitizer_cov_trace_const_cmp4",
776         "__sanitizer_cov_trace_const_cmp8",
777         "__sanitizer_cov_trace_cmp1",
778         "__sanitizer_cov_trace_cmp2",
779         "__sanitizer_cov_trace_cmp4",
780         "__sanitizer_cov_trace_cmp8",
781         "__sanitizer_cov_trace_switch",
782         /* UBSAN */
783         "ubsan_type_mismatch_common",
784         "__ubsan_handle_type_mismatch",
785         "__ubsan_handle_type_mismatch_v1",
786         "__ubsan_handle_shift_out_of_bounds",
787         /* misc */
788         "csum_partial_copy_generic",
789         "copy_mc_fragile",
790         "copy_mc_fragile_handle_tail",
791         "copy_mc_enhanced_fast_string",
792         "ftrace_likely_update", /* CONFIG_TRACE_BRANCH_PROFILING */
793         NULL
794 };
795
796 static void add_uaccess_safe(struct objtool_file *file)
797 {
798         struct symbol *func;
799         const char **name;
800
801         if (!uaccess)
802                 return;
803
804         for (name = uaccess_safe_builtin; *name; name++) {
805                 func = find_symbol_by_name(file->elf, *name);
806                 if (!func)
807                         continue;
808
809                 func->uaccess_safe = true;
810         }
811 }
812
813 /*
814  * FIXME: For now, just ignore any alternatives which add retpolines.  This is
815  * a temporary hack, as it doesn't allow ORC to unwind from inside a retpoline.
816  * But it at least allows objtool to understand the control flow *around* the
817  * retpoline.
818  */
819 static int add_ignore_alternatives(struct objtool_file *file)
820 {
821         struct section *sec;
822         struct reloc *reloc;
823         struct instruction *insn;
824
825         sec = find_section_by_name(file->elf, ".rela.discard.ignore_alts");
826         if (!sec)
827                 return 0;
828
829         list_for_each_entry(reloc, &sec->reloc_list, list) {
830                 if (reloc->sym->type != STT_SECTION) {
831                         WARN("unexpected relocation symbol type in %s", sec->name);
832                         return -1;
833                 }
834
835                 insn = find_insn(file, reloc->sym->sec, reloc->addend);
836                 if (!insn) {
837                         WARN("bad .discard.ignore_alts entry");
838                         return -1;
839                 }
840
841                 insn->ignore_alts = true;
842         }
843
844         return 0;
845 }
846
847 __weak bool arch_is_retpoline(struct symbol *sym)
848 {
849         return false;
850 }
851
852 /*
853  * Find the destination instructions for all jumps.
854  */
855 static int add_jump_destinations(struct objtool_file *file)
856 {
857         struct instruction *insn;
858         struct reloc *reloc;
859         struct section *dest_sec;
860         unsigned long dest_off;
861
862         for_each_insn(file, insn) {
863                 if (!is_static_jump(insn))
864                         continue;
865
866                 reloc = find_reloc_by_dest_range(file->elf, insn->sec,
867                                                  insn->offset, insn->len);
868                 if (!reloc) {
869                         dest_sec = insn->sec;
870                         dest_off = arch_jump_destination(insn);
871                 } else if (reloc->sym->type == STT_SECTION) {
872                         dest_sec = reloc->sym->sec;
873                         dest_off = arch_dest_reloc_offset(reloc->addend);
874                 } else if (arch_is_retpoline(reloc->sym)) {
875                         /*
876                          * Retpoline jumps are really dynamic jumps in
877                          * disguise, so convert them accordingly.
878                          */
879                         if (insn->type == INSN_JUMP_UNCONDITIONAL)
880                                 insn->type = INSN_JUMP_DYNAMIC;
881                         else
882                                 insn->type = INSN_JUMP_DYNAMIC_CONDITIONAL;
883
884                         insn->retpoline_safe = true;
885                         continue;
886                 } else if (insn->func) {
887                         /* internal or external sibling call (with reloc) */
888                         insn->call_dest = reloc->sym;
889                         if (insn->call_dest->static_call_tramp) {
890                                 list_add_tail(&insn->static_call_node,
891                                               &file->static_call_list);
892                         }
893                         continue;
894                 } else if (reloc->sym->sec->idx) {
895                         dest_sec = reloc->sym->sec;
896                         dest_off = reloc->sym->sym.st_value +
897                                    arch_dest_reloc_offset(reloc->addend);
898                 } else {
899                         /* non-func asm code jumping to another file */
900                         continue;
901                 }
902
903                 insn->jump_dest = find_insn(file, dest_sec, dest_off);
904                 if (!insn->jump_dest) {
905
906                         /*
907                          * This is a special case where an alt instruction
908                          * jumps past the end of the section.  These are
909                          * handled later in handle_group_alt().
910                          */
911                         if (!strcmp(insn->sec->name, ".altinstr_replacement"))
912                                 continue;
913
914                         WARN_FUNC("can't find jump dest instruction at %s+0x%lx",
915                                   insn->sec, insn->offset, dest_sec->name,
916                                   dest_off);
917                         return -1;
918                 }
919
920                 /*
921                  * Cross-function jump.
922                  */
923                 if (insn->func && insn->jump_dest->func &&
924                     insn->func != insn->jump_dest->func) {
925
926                         /*
927                          * For GCC 8+, create parent/child links for any cold
928                          * subfunctions.  This is _mostly_ redundant with a
929                          * similar initialization in read_symbols().
930                          *
931                          * If a function has aliases, we want the *first* such
932                          * function in the symbol table to be the subfunction's
933                          * parent.  In that case we overwrite the
934                          * initialization done in read_symbols().
935                          *
936                          * However this code can't completely replace the
937                          * read_symbols() code because this doesn't detect the
938                          * case where the parent function's only reference to a
939                          * subfunction is through a jump table.
940                          */
941                         if (!strstr(insn->func->name, ".cold") &&
942                             strstr(insn->jump_dest->func->name, ".cold")) {
943                                 insn->func->cfunc = insn->jump_dest->func;
944                                 insn->jump_dest->func->pfunc = insn->func;
945
946                         } else if (insn->jump_dest->func->pfunc != insn->func->pfunc &&
947                                    insn->jump_dest->offset == insn->jump_dest->func->offset) {
948
949                                 /* internal sibling call (without reloc) */
950                                 insn->call_dest = insn->jump_dest->func;
951                                 if (insn->call_dest->static_call_tramp) {
952                                         list_add_tail(&insn->static_call_node,
953                                                       &file->static_call_list);
954                                 }
955                         }
956                 }
957         }
958
959         return 0;
960 }
961
962 static void remove_insn_ops(struct instruction *insn)
963 {
964         struct stack_op *op, *tmp;
965
966         list_for_each_entry_safe(op, tmp, &insn->stack_ops, list) {
967                 list_del(&op->list);
968                 free(op);
969         }
970 }
971
972 static struct symbol *find_call_destination(struct section *sec, unsigned long offset)
973 {
974         struct symbol *call_dest;
975
976         call_dest = find_func_by_offset(sec, offset);
977         if (!call_dest)
978                 call_dest = find_symbol_by_offset(sec, offset);
979
980         return call_dest;
981 }
982
983 /*
984  * Find the destination instructions for all calls.
985  */
986 static int add_call_destinations(struct objtool_file *file)
987 {
988         struct instruction *insn;
989         unsigned long dest_off;
990         struct reloc *reloc;
991
992         for_each_insn(file, insn) {
993                 if (insn->type != INSN_CALL)
994                         continue;
995
996                 reloc = find_reloc_by_dest_range(file->elf, insn->sec,
997                                                insn->offset, insn->len);
998                 if (!reloc) {
999                         dest_off = arch_jump_destination(insn);
1000                         insn->call_dest = find_call_destination(insn->sec, dest_off);
1001
1002                         if (insn->ignore)
1003                                 continue;
1004
1005                         if (!insn->call_dest) {
1006                                 WARN_FUNC("unannotated intra-function call", insn->sec, insn->offset);
1007                                 return -1;
1008                         }
1009
1010                         if (insn->func && insn->call_dest->type != STT_FUNC) {
1011                                 WARN_FUNC("unsupported call to non-function",
1012                                           insn->sec, insn->offset);
1013                                 return -1;
1014                         }
1015
1016                 } else if (reloc->sym->type == STT_SECTION) {
1017                         dest_off = arch_dest_reloc_offset(reloc->addend);
1018                         insn->call_dest = find_call_destination(reloc->sym->sec,
1019                                                                 dest_off);
1020                         if (!insn->call_dest) {
1021                                 WARN_FUNC("can't find call dest symbol at %s+0x%lx",
1022                                           insn->sec, insn->offset,
1023                                           reloc->sym->sec->name,
1024                                           dest_off);
1025                                 return -1;
1026                         }
1027
1028                 } else if (arch_is_retpoline(reloc->sym)) {
1029                         /*
1030                          * Retpoline calls are really dynamic calls in
1031                          * disguise, so convert them accordingly.
1032                          */
1033                         insn->type = INSN_CALL_DYNAMIC;
1034                         insn->retpoline_safe = true;
1035
1036                         remove_insn_ops(insn);
1037                         continue;
1038
1039                 } else
1040                         insn->call_dest = reloc->sym;
1041
1042                 if (insn->call_dest && insn->call_dest->static_call_tramp) {
1043                         list_add_tail(&insn->static_call_node,
1044                                       &file->static_call_list);
1045                 }
1046
1047                 /*
1048                  * Many compilers cannot disable KCOV with a function attribute
1049                  * so they need a little help, NOP out any KCOV calls from noinstr
1050                  * text.
1051                  */
1052                 if (insn->sec->noinstr &&
1053                     !strncmp(insn->call_dest->name, "__sanitizer_cov_", 16)) {
1054                         if (reloc) {
1055                                 reloc->type = R_NONE;
1056                                 elf_write_reloc(file->elf, reloc);
1057                         }
1058
1059                         elf_write_insn(file->elf, insn->sec,
1060                                        insn->offset, insn->len,
1061                                        arch_nop_insn(insn->len));
1062                         insn->type = INSN_NOP;
1063                 }
1064
1065                 if (mcount && !strcmp(insn->call_dest->name, "__fentry__")) {
1066                         if (reloc) {
1067                                 reloc->type = R_NONE;
1068                                 elf_write_reloc(file->elf, reloc);
1069                         }
1070
1071                         elf_write_insn(file->elf, insn->sec,
1072                                        insn->offset, insn->len,
1073                                        arch_nop_insn(insn->len));
1074
1075                         insn->type = INSN_NOP;
1076
1077                         list_add_tail(&insn->mcount_loc_node,
1078                                       &file->mcount_loc_list);
1079                 }
1080
1081                 /*
1082                  * Whatever stack impact regular CALLs have, should be undone
1083                  * by the RETURN of the called function.
1084                  *
1085                  * Annotated intra-function calls retain the stack_ops but
1086                  * are converted to JUMP, see read_intra_function_calls().
1087                  */
1088                 remove_insn_ops(insn);
1089         }
1090
1091         return 0;
1092 }
1093
1094 /*
1095  * The .alternatives section requires some extra special care over and above
1096  * other special sections because alternatives are patched in place.
1097  */
1098 static int handle_group_alt(struct objtool_file *file,
1099                             struct special_alt *special_alt,
1100                             struct instruction *orig_insn,
1101                             struct instruction **new_insn)
1102 {
1103         struct instruction *last_orig_insn, *last_new_insn = NULL, *insn, *nop = NULL;
1104         struct alt_group *orig_alt_group, *new_alt_group;
1105         unsigned long dest_off;
1106
1107
1108         orig_alt_group = malloc(sizeof(*orig_alt_group));
1109         if (!orig_alt_group) {
1110                 WARN("malloc failed");
1111                 return -1;
1112         }
1113         orig_alt_group->cfi = calloc(special_alt->orig_len,
1114                                      sizeof(struct cfi_state *));
1115         if (!orig_alt_group->cfi) {
1116                 WARN("calloc failed");
1117                 return -1;
1118         }
1119
1120         last_orig_insn = NULL;
1121         insn = orig_insn;
1122         sec_for_each_insn_from(file, insn) {
1123                 if (insn->offset >= special_alt->orig_off + special_alt->orig_len)
1124                         break;
1125
1126                 insn->alt_group = orig_alt_group;
1127                 last_orig_insn = insn;
1128         }
1129         orig_alt_group->orig_group = NULL;
1130         orig_alt_group->first_insn = orig_insn;
1131         orig_alt_group->last_insn = last_orig_insn;
1132
1133
1134         new_alt_group = malloc(sizeof(*new_alt_group));
1135         if (!new_alt_group) {
1136                 WARN("malloc failed");
1137                 return -1;
1138         }
1139
1140         if (special_alt->new_len < special_alt->orig_len) {
1141                 /*
1142                  * Insert a fake nop at the end to make the replacement
1143                  * alt_group the same size as the original.  This is needed to
1144                  * allow propagate_alt_cfi() to do its magic.  When the last
1145                  * instruction affects the stack, the instruction after it (the
1146                  * nop) will propagate the new state to the shared CFI array.
1147                  */
1148                 nop = malloc(sizeof(*nop));
1149                 if (!nop) {
1150                         WARN("malloc failed");
1151                         return -1;
1152                 }
1153                 memset(nop, 0, sizeof(*nop));
1154                 INIT_LIST_HEAD(&nop->alts);
1155                 INIT_LIST_HEAD(&nop->stack_ops);
1156                 init_cfi_state(&nop->cfi);
1157
1158                 nop->sec = special_alt->new_sec;
1159                 nop->offset = special_alt->new_off + special_alt->new_len;
1160                 nop->len = special_alt->orig_len - special_alt->new_len;
1161                 nop->type = INSN_NOP;
1162                 nop->func = orig_insn->func;
1163                 nop->alt_group = new_alt_group;
1164                 nop->ignore = orig_insn->ignore_alts;
1165         }
1166
1167         if (!special_alt->new_len) {
1168                 *new_insn = nop;
1169                 goto end;
1170         }
1171
1172         insn = *new_insn;
1173         sec_for_each_insn_from(file, insn) {
1174                 struct reloc *alt_reloc;
1175
1176                 if (insn->offset >= special_alt->new_off + special_alt->new_len)
1177                         break;
1178
1179                 last_new_insn = insn;
1180
1181                 insn->ignore = orig_insn->ignore_alts;
1182                 insn->func = orig_insn->func;
1183                 insn->alt_group = new_alt_group;
1184
1185                 /*
1186                  * Since alternative replacement code is copy/pasted by the
1187                  * kernel after applying relocations, generally such code can't
1188                  * have relative-address relocation references to outside the
1189                  * .altinstr_replacement section, unless the arch's
1190                  * alternatives code can adjust the relative offsets
1191                  * accordingly.
1192                  */
1193                 alt_reloc = find_reloc_by_dest_range(file->elf, insn->sec,
1194                                                    insn->offset, insn->len);
1195                 if (alt_reloc &&
1196                     !arch_support_alt_relocation(special_alt, insn, alt_reloc)) {
1197
1198                         WARN_FUNC("unsupported relocation in alternatives section",
1199                                   insn->sec, insn->offset);
1200                         return -1;
1201                 }
1202
1203                 if (!is_static_jump(insn))
1204                         continue;
1205
1206                 if (!insn->immediate)
1207                         continue;
1208
1209                 dest_off = arch_jump_destination(insn);
1210                 if (dest_off == special_alt->new_off + special_alt->new_len)
1211                         insn->jump_dest = next_insn_same_sec(file, last_orig_insn);
1212
1213                 if (!insn->jump_dest) {
1214                         WARN_FUNC("can't find alternative jump destination",
1215                                   insn->sec, insn->offset);
1216                         return -1;
1217                 }
1218         }
1219
1220         if (!last_new_insn) {
1221                 WARN_FUNC("can't find last new alternative instruction",
1222                           special_alt->new_sec, special_alt->new_off);
1223                 return -1;
1224         }
1225
1226         if (nop)
1227                 list_add(&nop->list, &last_new_insn->list);
1228 end:
1229         new_alt_group->orig_group = orig_alt_group;
1230         new_alt_group->first_insn = *new_insn;
1231         new_alt_group->last_insn = nop ? : last_new_insn;
1232         new_alt_group->cfi = orig_alt_group->cfi;
1233         return 0;
1234 }
1235
1236 /*
1237  * A jump table entry can either convert a nop to a jump or a jump to a nop.
1238  * If the original instruction is a jump, make the alt entry an effective nop
1239  * by just skipping the original instruction.
1240  */
1241 static int handle_jump_alt(struct objtool_file *file,
1242                            struct special_alt *special_alt,
1243                            struct instruction *orig_insn,
1244                            struct instruction **new_insn)
1245 {
1246         if (orig_insn->type == INSN_NOP)
1247                 return 0;
1248
1249         if (orig_insn->type != INSN_JUMP_UNCONDITIONAL) {
1250                 WARN_FUNC("unsupported instruction at jump label",
1251                           orig_insn->sec, orig_insn->offset);
1252                 return -1;
1253         }
1254
1255         *new_insn = list_next_entry(orig_insn, list);
1256         return 0;
1257 }
1258
1259 /*
1260  * Read all the special sections which have alternate instructions which can be
1261  * patched in or redirected to at runtime.  Each instruction having alternate
1262  * instruction(s) has them added to its insn->alts list, which will be
1263  * traversed in validate_branch().
1264  */
1265 static int add_special_section_alts(struct objtool_file *file)
1266 {
1267         struct list_head special_alts;
1268         struct instruction *orig_insn, *new_insn;
1269         struct special_alt *special_alt, *tmp;
1270         struct alternative *alt;
1271         int ret;
1272
1273         ret = special_get_alts(file->elf, &special_alts);
1274         if (ret)
1275                 return ret;
1276
1277         list_for_each_entry_safe(special_alt, tmp, &special_alts, list) {
1278
1279                 orig_insn = find_insn(file, special_alt->orig_sec,
1280                                       special_alt->orig_off);
1281                 if (!orig_insn) {
1282                         WARN_FUNC("special: can't find orig instruction",
1283                                   special_alt->orig_sec, special_alt->orig_off);
1284                         ret = -1;
1285                         goto out;
1286                 }
1287
1288                 new_insn = NULL;
1289                 if (!special_alt->group || special_alt->new_len) {
1290                         new_insn = find_insn(file, special_alt->new_sec,
1291                                              special_alt->new_off);
1292                         if (!new_insn) {
1293                                 WARN_FUNC("special: can't find new instruction",
1294                                           special_alt->new_sec,
1295                                           special_alt->new_off);
1296                                 ret = -1;
1297                                 goto out;
1298                         }
1299                 }
1300
1301                 if (special_alt->group) {
1302                         if (!special_alt->orig_len) {
1303                                 WARN_FUNC("empty alternative entry",
1304                                           orig_insn->sec, orig_insn->offset);
1305                                 continue;
1306                         }
1307
1308                         ret = handle_group_alt(file, special_alt, orig_insn,
1309                                                &new_insn);
1310                         if (ret)
1311                                 goto out;
1312                 } else if (special_alt->jump_or_nop) {
1313                         ret = handle_jump_alt(file, special_alt, orig_insn,
1314                                               &new_insn);
1315                         if (ret)
1316                                 goto out;
1317                 }
1318
1319                 alt = malloc(sizeof(*alt));
1320                 if (!alt) {
1321                         WARN("malloc failed");
1322                         ret = -1;
1323                         goto out;
1324                 }
1325
1326                 alt->insn = new_insn;
1327                 alt->skip_orig = special_alt->skip_orig;
1328                 orig_insn->ignore_alts |= special_alt->skip_alt;
1329                 list_add_tail(&alt->list, &orig_insn->alts);
1330
1331                 list_del(&special_alt->list);
1332                 free(special_alt);
1333         }
1334
1335 out:
1336         return ret;
1337 }
1338
1339 static int add_jump_table(struct objtool_file *file, struct instruction *insn,
1340                             struct reloc *table)
1341 {
1342         struct reloc *reloc = table;
1343         struct instruction *dest_insn;
1344         struct alternative *alt;
1345         struct symbol *pfunc = insn->func->pfunc;
1346         unsigned int prev_offset = 0;
1347
1348         /*
1349          * Each @reloc is a switch table relocation which points to the target
1350          * instruction.
1351          */
1352         list_for_each_entry_from(reloc, &table->sec->reloc_list, list) {
1353
1354                 /* Check for the end of the table: */
1355                 if (reloc != table && reloc->jump_table_start)
1356                         break;
1357
1358                 /* Make sure the table entries are consecutive: */
1359                 if (prev_offset && reloc->offset != prev_offset + 8)
1360                         break;
1361
1362                 /* Detect function pointers from contiguous objects: */
1363                 if (reloc->sym->sec == pfunc->sec &&
1364                     reloc->addend == pfunc->offset)
1365                         break;
1366
1367                 dest_insn = find_insn(file, reloc->sym->sec, reloc->addend);
1368                 if (!dest_insn)
1369                         break;
1370
1371                 /* Make sure the destination is in the same function: */
1372                 if (!dest_insn->func || dest_insn->func->pfunc != pfunc)
1373                         break;
1374
1375                 alt = malloc(sizeof(*alt));
1376                 if (!alt) {
1377                         WARN("malloc failed");
1378                         return -1;
1379                 }
1380
1381                 alt->insn = dest_insn;
1382                 list_add_tail(&alt->list, &insn->alts);
1383                 prev_offset = reloc->offset;
1384         }
1385
1386         if (!prev_offset) {
1387                 WARN_FUNC("can't find switch jump table",
1388                           insn->sec, insn->offset);
1389                 return -1;
1390         }
1391
1392         return 0;
1393 }
1394
1395 /*
1396  * find_jump_table() - Given a dynamic jump, find the switch jump table
1397  * associated with it.
1398  */
1399 static struct reloc *find_jump_table(struct objtool_file *file,
1400                                       struct symbol *func,
1401                                       struct instruction *insn)
1402 {
1403         struct reloc *table_reloc;
1404         struct instruction *dest_insn, *orig_insn = insn;
1405
1406         /*
1407          * Backward search using the @first_jump_src links, these help avoid
1408          * much of the 'in between' code. Which avoids us getting confused by
1409          * it.
1410          */
1411         for (;
1412              insn && insn->func && insn->func->pfunc == func;
1413              insn = insn->first_jump_src ?: prev_insn_same_sym(file, insn)) {
1414
1415                 if (insn != orig_insn && insn->type == INSN_JUMP_DYNAMIC)
1416                         break;
1417
1418                 /* allow small jumps within the range */
1419                 if (insn->type == INSN_JUMP_UNCONDITIONAL &&
1420                     insn->jump_dest &&
1421                     (insn->jump_dest->offset <= insn->offset ||
1422                      insn->jump_dest->offset > orig_insn->offset))
1423                     break;
1424
1425                 table_reloc = arch_find_switch_table(file, insn);
1426                 if (!table_reloc)
1427                         continue;
1428                 dest_insn = find_insn(file, table_reloc->sym->sec, table_reloc->addend);
1429                 if (!dest_insn || !dest_insn->func || dest_insn->func->pfunc != func)
1430                         continue;
1431
1432                 return table_reloc;
1433         }
1434
1435         return NULL;
1436 }
1437
1438 /*
1439  * First pass: Mark the head of each jump table so that in the next pass,
1440  * we know when a given jump table ends and the next one starts.
1441  */
1442 static void mark_func_jump_tables(struct objtool_file *file,
1443                                     struct symbol *func)
1444 {
1445         struct instruction *insn, *last = NULL;
1446         struct reloc *reloc;
1447
1448         func_for_each_insn(file, func, insn) {
1449                 if (!last)
1450                         last = insn;
1451
1452                 /*
1453                  * Store back-pointers for unconditional forward jumps such
1454                  * that find_jump_table() can back-track using those and
1455                  * avoid some potentially confusing code.
1456                  */
1457                 if (insn->type == INSN_JUMP_UNCONDITIONAL && insn->jump_dest &&
1458                     insn->offset > last->offset &&
1459                     insn->jump_dest->offset > insn->offset &&
1460                     !insn->jump_dest->first_jump_src) {
1461
1462                         insn->jump_dest->first_jump_src = insn;
1463                         last = insn->jump_dest;
1464                 }
1465
1466                 if (insn->type != INSN_JUMP_DYNAMIC)
1467                         continue;
1468
1469                 reloc = find_jump_table(file, func, insn);
1470                 if (reloc) {
1471                         reloc->jump_table_start = true;
1472                         insn->jump_table = reloc;
1473                 }
1474         }
1475 }
1476
1477 static int add_func_jump_tables(struct objtool_file *file,
1478                                   struct symbol *func)
1479 {
1480         struct instruction *insn;
1481         int ret;
1482
1483         func_for_each_insn(file, func, insn) {
1484                 if (!insn->jump_table)
1485                         continue;
1486
1487                 ret = add_jump_table(file, insn, insn->jump_table);
1488                 if (ret)
1489                         return ret;
1490         }
1491
1492         return 0;
1493 }
1494
1495 /*
1496  * For some switch statements, gcc generates a jump table in the .rodata
1497  * section which contains a list of addresses within the function to jump to.
1498  * This finds these jump tables and adds them to the insn->alts lists.
1499  */
1500 static int add_jump_table_alts(struct objtool_file *file)
1501 {
1502         struct section *sec;
1503         struct symbol *func;
1504         int ret;
1505
1506         if (!file->rodata)
1507                 return 0;
1508
1509         for_each_sec(file, sec) {
1510                 list_for_each_entry(func, &sec->symbol_list, list) {
1511                         if (func->type != STT_FUNC)
1512                                 continue;
1513
1514                         mark_func_jump_tables(file, func);
1515                         ret = add_func_jump_tables(file, func);
1516                         if (ret)
1517                                 return ret;
1518                 }
1519         }
1520
1521         return 0;
1522 }
1523
1524 static void set_func_state(struct cfi_state *state)
1525 {
1526         state->cfa = initial_func_cfi.cfa;
1527         memcpy(&state->regs, &initial_func_cfi.regs,
1528                CFI_NUM_REGS * sizeof(struct cfi_reg));
1529         state->stack_size = initial_func_cfi.cfa.offset;
1530 }
1531
1532 static int read_unwind_hints(struct objtool_file *file)
1533 {
1534         struct section *sec, *relocsec;
1535         struct reloc *reloc;
1536         struct unwind_hint *hint;
1537         struct instruction *insn;
1538         int i;
1539
1540         sec = find_section_by_name(file->elf, ".discard.unwind_hints");
1541         if (!sec)
1542                 return 0;
1543
1544         relocsec = sec->reloc;
1545         if (!relocsec) {
1546                 WARN("missing .rela.discard.unwind_hints section");
1547                 return -1;
1548         }
1549
1550         if (sec->len % sizeof(struct unwind_hint)) {
1551                 WARN("struct unwind_hint size mismatch");
1552                 return -1;
1553         }
1554
1555         file->hints = true;
1556
1557         for (i = 0; i < sec->len / sizeof(struct unwind_hint); i++) {
1558                 hint = (struct unwind_hint *)sec->data->d_buf + i;
1559
1560                 reloc = find_reloc_by_dest(file->elf, sec, i * sizeof(*hint));
1561                 if (!reloc) {
1562                         WARN("can't find reloc for unwind_hints[%d]", i);
1563                         return -1;
1564                 }
1565
1566                 insn = find_insn(file, reloc->sym->sec, reloc->addend);
1567                 if (!insn) {
1568                         WARN("can't find insn for unwind_hints[%d]", i);
1569                         return -1;
1570                 }
1571
1572                 insn->hint = true;
1573
1574                 if (hint->type == UNWIND_HINT_TYPE_FUNC) {
1575                         set_func_state(&insn->cfi);
1576                         continue;
1577                 }
1578
1579                 if (arch_decode_hint_reg(insn, hint->sp_reg)) {
1580                         WARN_FUNC("unsupported unwind_hint sp base reg %d",
1581                                   insn->sec, insn->offset, hint->sp_reg);
1582                         return -1;
1583                 }
1584
1585                 insn->cfi.cfa.offset = bswap_if_needed(hint->sp_offset);
1586                 insn->cfi.type = hint->type;
1587                 insn->cfi.end = hint->end;
1588         }
1589
1590         return 0;
1591 }
1592
1593 static int read_retpoline_hints(struct objtool_file *file)
1594 {
1595         struct section *sec;
1596         struct instruction *insn;
1597         struct reloc *reloc;
1598
1599         sec = find_section_by_name(file->elf, ".rela.discard.retpoline_safe");
1600         if (!sec)
1601                 return 0;
1602
1603         list_for_each_entry(reloc, &sec->reloc_list, list) {
1604                 if (reloc->sym->type != STT_SECTION) {
1605                         WARN("unexpected relocation symbol type in %s", sec->name);
1606                         return -1;
1607                 }
1608
1609                 insn = find_insn(file, reloc->sym->sec, reloc->addend);
1610                 if (!insn) {
1611                         WARN("bad .discard.retpoline_safe entry");
1612                         return -1;
1613                 }
1614
1615                 if (insn->type != INSN_JUMP_DYNAMIC &&
1616                     insn->type != INSN_CALL_DYNAMIC) {
1617                         WARN_FUNC("retpoline_safe hint not an indirect jump/call",
1618                                   insn->sec, insn->offset);
1619                         return -1;
1620                 }
1621
1622                 insn->retpoline_safe = true;
1623         }
1624
1625         return 0;
1626 }
1627
1628 static int read_instr_hints(struct objtool_file *file)
1629 {
1630         struct section *sec;
1631         struct instruction *insn;
1632         struct reloc *reloc;
1633
1634         sec = find_section_by_name(file->elf, ".rela.discard.instr_end");
1635         if (!sec)
1636                 return 0;
1637
1638         list_for_each_entry(reloc, &sec->reloc_list, list) {
1639                 if (reloc->sym->type != STT_SECTION) {
1640                         WARN("unexpected relocation symbol type in %s", sec->name);
1641                         return -1;
1642                 }
1643
1644                 insn = find_insn(file, reloc->sym->sec, reloc->addend);
1645                 if (!insn) {
1646                         WARN("bad .discard.instr_end entry");
1647                         return -1;
1648                 }
1649
1650                 insn->instr--;
1651         }
1652
1653         sec = find_section_by_name(file->elf, ".rela.discard.instr_begin");
1654         if (!sec)
1655                 return 0;
1656
1657         list_for_each_entry(reloc, &sec->reloc_list, list) {
1658                 if (reloc->sym->type != STT_SECTION) {
1659                         WARN("unexpected relocation symbol type in %s", sec->name);
1660                         return -1;
1661                 }
1662
1663                 insn = find_insn(file, reloc->sym->sec, reloc->addend);
1664                 if (!insn) {
1665                         WARN("bad .discard.instr_begin entry");
1666                         return -1;
1667                 }
1668
1669                 insn->instr++;
1670         }
1671
1672         return 0;
1673 }
1674
1675 static int read_intra_function_calls(struct objtool_file *file)
1676 {
1677         struct instruction *insn;
1678         struct section *sec;
1679         struct reloc *reloc;
1680
1681         sec = find_section_by_name(file->elf, ".rela.discard.intra_function_calls");
1682         if (!sec)
1683                 return 0;
1684
1685         list_for_each_entry(reloc, &sec->reloc_list, list) {
1686                 unsigned long dest_off;
1687
1688                 if (reloc->sym->type != STT_SECTION) {
1689                         WARN("unexpected relocation symbol type in %s",
1690                              sec->name);
1691                         return -1;
1692                 }
1693
1694                 insn = find_insn(file, reloc->sym->sec, reloc->addend);
1695                 if (!insn) {
1696                         WARN("bad .discard.intra_function_call entry");
1697                         return -1;
1698                 }
1699
1700                 if (insn->type != INSN_CALL) {
1701                         WARN_FUNC("intra_function_call not a direct call",
1702                                   insn->sec, insn->offset);
1703                         return -1;
1704                 }
1705
1706                 /*
1707                  * Treat intra-function CALLs as JMPs, but with a stack_op.
1708                  * See add_call_destinations(), which strips stack_ops from
1709                  * normal CALLs.
1710                  */
1711                 insn->type = INSN_JUMP_UNCONDITIONAL;
1712
1713                 dest_off = insn->offset + insn->len + insn->immediate;
1714                 insn->jump_dest = find_insn(file, insn->sec, dest_off);
1715                 if (!insn->jump_dest) {
1716                         WARN_FUNC("can't find call dest at %s+0x%lx",
1717                                   insn->sec, insn->offset,
1718                                   insn->sec->name, dest_off);
1719                         return -1;
1720                 }
1721         }
1722
1723         return 0;
1724 }
1725
1726 static int read_static_call_tramps(struct objtool_file *file)
1727 {
1728         struct section *sec;
1729         struct symbol *func;
1730
1731         for_each_sec(file, sec) {
1732                 list_for_each_entry(func, &sec->symbol_list, list) {
1733                         if (func->bind == STB_GLOBAL &&
1734                             !strncmp(func->name, STATIC_CALL_TRAMP_PREFIX_STR,
1735                                      strlen(STATIC_CALL_TRAMP_PREFIX_STR)))
1736                                 func->static_call_tramp = true;
1737                 }
1738         }
1739
1740         return 0;
1741 }
1742
1743 static void mark_rodata(struct objtool_file *file)
1744 {
1745         struct section *sec;
1746         bool found = false;
1747
1748         /*
1749          * Search for the following rodata sections, each of which can
1750          * potentially contain jump tables:
1751          *
1752          * - .rodata: can contain GCC switch tables
1753          * - .rodata.<func>: same, if -fdata-sections is being used
1754          * - .rodata..c_jump_table: contains C annotated jump tables
1755          *
1756          * .rodata.str1.* sections are ignored; they don't contain jump tables.
1757          */
1758         for_each_sec(file, sec) {
1759                 if (!strncmp(sec->name, ".rodata", 7) &&
1760                     !strstr(sec->name, ".str1.")) {
1761                         sec->rodata = true;
1762                         found = true;
1763                 }
1764         }
1765
1766         file->rodata = found;
1767 }
1768
1769 static int decode_sections(struct objtool_file *file)
1770 {
1771         int ret;
1772
1773         mark_rodata(file);
1774
1775         ret = decode_instructions(file);
1776         if (ret)
1777                 return ret;
1778
1779         ret = add_dead_ends(file);
1780         if (ret)
1781                 return ret;
1782
1783         add_ignores(file);
1784         add_uaccess_safe(file);
1785
1786         ret = add_ignore_alternatives(file);
1787         if (ret)
1788                 return ret;
1789
1790         /*
1791          * Must be before add_{jump_call}_destination.
1792          */
1793         ret = read_static_call_tramps(file);
1794         if (ret)
1795                 return ret;
1796
1797         ret = add_jump_destinations(file);
1798         if (ret)
1799                 return ret;
1800
1801         ret = add_special_section_alts(file);
1802         if (ret)
1803                 return ret;
1804
1805         /*
1806          * Must be before add_call_destination(); it changes INSN_CALL to
1807          * INSN_JUMP.
1808          */
1809         ret = read_intra_function_calls(file);
1810         if (ret)
1811                 return ret;
1812
1813         ret = add_call_destinations(file);
1814         if (ret)
1815                 return ret;
1816
1817         ret = add_jump_table_alts(file);
1818         if (ret)
1819                 return ret;
1820
1821         ret = read_unwind_hints(file);
1822         if (ret)
1823                 return ret;
1824
1825         ret = read_retpoline_hints(file);
1826         if (ret)
1827                 return ret;
1828
1829         ret = read_instr_hints(file);
1830         if (ret)
1831                 return ret;
1832
1833         return 0;
1834 }
1835
1836 static bool is_fentry_call(struct instruction *insn)
1837 {
1838         if (insn->type == INSN_CALL && insn->call_dest &&
1839             insn->call_dest->type == STT_NOTYPE &&
1840             !strcmp(insn->call_dest->name, "__fentry__"))
1841                 return true;
1842
1843         return false;
1844 }
1845
1846 static bool has_modified_stack_frame(struct instruction *insn, struct insn_state *state)
1847 {
1848         struct cfi_state *cfi = &state->cfi;
1849         int i;
1850
1851         if (cfi->cfa.base != initial_func_cfi.cfa.base || cfi->drap)
1852                 return true;
1853
1854         if (cfi->cfa.offset != initial_func_cfi.cfa.offset)
1855                 return true;
1856
1857         if (cfi->stack_size != initial_func_cfi.cfa.offset)
1858                 return true;
1859
1860         for (i = 0; i < CFI_NUM_REGS; i++) {
1861                 if (cfi->regs[i].base != initial_func_cfi.regs[i].base ||
1862                     cfi->regs[i].offset != initial_func_cfi.regs[i].offset)
1863                         return true;
1864         }
1865
1866         return false;
1867 }
1868
1869 static bool check_reg_frame_pos(const struct cfi_reg *reg,
1870                                 int expected_offset)
1871 {
1872         return reg->base == CFI_CFA &&
1873                reg->offset == expected_offset;
1874 }
1875
1876 static bool has_valid_stack_frame(struct insn_state *state)
1877 {
1878         struct cfi_state *cfi = &state->cfi;
1879
1880         if (cfi->cfa.base == CFI_BP &&
1881             check_reg_frame_pos(&cfi->regs[CFI_BP], -cfi->cfa.offset) &&
1882             check_reg_frame_pos(&cfi->regs[CFI_RA], -cfi->cfa.offset + 8))
1883                 return true;
1884
1885         if (cfi->drap && cfi->regs[CFI_BP].base == CFI_BP)
1886                 return true;
1887
1888         return false;
1889 }
1890
1891 static int update_cfi_state_regs(struct instruction *insn,
1892                                   struct cfi_state *cfi,
1893                                   struct stack_op *op)
1894 {
1895         struct cfi_reg *cfa = &cfi->cfa;
1896
1897         if (cfa->base != CFI_SP && cfa->base != CFI_SP_INDIRECT)
1898                 return 0;
1899
1900         /* push */
1901         if (op->dest.type == OP_DEST_PUSH || op->dest.type == OP_DEST_PUSHF)
1902                 cfa->offset += 8;
1903
1904         /* pop */
1905         if (op->src.type == OP_SRC_POP || op->src.type == OP_SRC_POPF)
1906                 cfa->offset -= 8;
1907
1908         /* add immediate to sp */
1909         if (op->dest.type == OP_DEST_REG && op->src.type == OP_SRC_ADD &&
1910             op->dest.reg == CFI_SP && op->src.reg == CFI_SP)
1911                 cfa->offset -= op->src.offset;
1912
1913         return 0;
1914 }
1915
1916 static void save_reg(struct cfi_state *cfi, unsigned char reg, int base, int offset)
1917 {
1918         if (arch_callee_saved_reg(reg) &&
1919             cfi->regs[reg].base == CFI_UNDEFINED) {
1920                 cfi->regs[reg].base = base;
1921                 cfi->regs[reg].offset = offset;
1922         }
1923 }
1924
1925 static void restore_reg(struct cfi_state *cfi, unsigned char reg)
1926 {
1927         cfi->regs[reg].base = initial_func_cfi.regs[reg].base;
1928         cfi->regs[reg].offset = initial_func_cfi.regs[reg].offset;
1929 }
1930
1931 /*
1932  * A note about DRAP stack alignment:
1933  *
1934  * GCC has the concept of a DRAP register, which is used to help keep track of
1935  * the stack pointer when aligning the stack.  r10 or r13 is used as the DRAP
1936  * register.  The typical DRAP pattern is:
1937  *
1938  *   4c 8d 54 24 08             lea    0x8(%rsp),%r10
1939  *   48 83 e4 c0                and    $0xffffffffffffffc0,%rsp
1940  *   41 ff 72 f8                pushq  -0x8(%r10)
1941  *   55                         push   %rbp
1942  *   48 89 e5                   mov    %rsp,%rbp
1943  *                              (more pushes)
1944  *   41 52                      push   %r10
1945  *                              ...
1946  *   41 5a                      pop    %r10
1947  *                              (more pops)
1948  *   5d                         pop    %rbp
1949  *   49 8d 62 f8                lea    -0x8(%r10),%rsp
1950  *   c3                         retq
1951  *
1952  * There are some variations in the epilogues, like:
1953  *
1954  *   5b                         pop    %rbx
1955  *   41 5a                      pop    %r10
1956  *   41 5c                      pop    %r12
1957  *   41 5d                      pop    %r13
1958  *   41 5e                      pop    %r14
1959  *   c9                         leaveq
1960  *   49 8d 62 f8                lea    -0x8(%r10),%rsp
1961  *   c3                         retq
1962  *
1963  * and:
1964  *
1965  *   4c 8b 55 e8                mov    -0x18(%rbp),%r10
1966  *   48 8b 5d e0                mov    -0x20(%rbp),%rbx
1967  *   4c 8b 65 f0                mov    -0x10(%rbp),%r12
1968  *   4c 8b 6d f8                mov    -0x8(%rbp),%r13
1969  *   c9                         leaveq
1970  *   49 8d 62 f8                lea    -0x8(%r10),%rsp
1971  *   c3                         retq
1972  *
1973  * Sometimes r13 is used as the DRAP register, in which case it's saved and
1974  * restored beforehand:
1975  *
1976  *   41 55                      push   %r13
1977  *   4c 8d 6c 24 10             lea    0x10(%rsp),%r13
1978  *   48 83 e4 f0                and    $0xfffffffffffffff0,%rsp
1979  *                              ...
1980  *   49 8d 65 f0                lea    -0x10(%r13),%rsp
1981  *   41 5d                      pop    %r13
1982  *   c3                         retq
1983  */
1984 static int update_cfi_state(struct instruction *insn, struct cfi_state *cfi,
1985                              struct stack_op *op)
1986 {
1987         struct cfi_reg *cfa = &cfi->cfa;
1988         struct cfi_reg *regs = cfi->regs;
1989
1990         /* stack operations don't make sense with an undefined CFA */
1991         if (cfa->base == CFI_UNDEFINED) {
1992                 if (insn->func) {
1993                         WARN_FUNC("undefined stack state", insn->sec, insn->offset);
1994                         return -1;
1995                 }
1996                 return 0;
1997         }
1998
1999         if (cfi->type == UNWIND_HINT_TYPE_REGS ||
2000             cfi->type == UNWIND_HINT_TYPE_REGS_PARTIAL)
2001                 return update_cfi_state_regs(insn, cfi, op);
2002
2003         switch (op->dest.type) {
2004
2005         case OP_DEST_REG:
2006                 switch (op->src.type) {
2007
2008                 case OP_SRC_REG:
2009                         if (op->src.reg == CFI_SP && op->dest.reg == CFI_BP &&
2010                             cfa->base == CFI_SP &&
2011                             check_reg_frame_pos(&regs[CFI_BP], -cfa->offset)) {
2012
2013                                 /* mov %rsp, %rbp */
2014                                 cfa->base = op->dest.reg;
2015                                 cfi->bp_scratch = false;
2016                         }
2017
2018                         else if (op->src.reg == CFI_SP &&
2019                                  op->dest.reg == CFI_BP && cfi->drap) {
2020
2021                                 /* drap: mov %rsp, %rbp */
2022                                 regs[CFI_BP].base = CFI_BP;
2023                                 regs[CFI_BP].offset = -cfi->stack_size;
2024                                 cfi->bp_scratch = false;
2025                         }
2026
2027                         else if (op->src.reg == CFI_SP && cfa->base == CFI_SP) {
2028
2029                                 /*
2030                                  * mov %rsp, %reg
2031                                  *
2032                                  * This is needed for the rare case where GCC
2033                                  * does:
2034                                  *
2035                                  *   mov    %rsp, %rax
2036                                  *   ...
2037                                  *   mov    %rax, %rsp
2038                                  */
2039                                 cfi->vals[op->dest.reg].base = CFI_CFA;
2040                                 cfi->vals[op->dest.reg].offset = -cfi->stack_size;
2041                         }
2042
2043                         else if (op->src.reg == CFI_BP && op->dest.reg == CFI_SP &&
2044                                  cfa->base == CFI_BP) {
2045
2046                                 /*
2047                                  * mov %rbp, %rsp
2048                                  *
2049                                  * Restore the original stack pointer (Clang).
2050                                  */
2051                                 cfi->stack_size = -cfi->regs[CFI_BP].offset;
2052                         }
2053
2054                         else if (op->dest.reg == cfa->base) {
2055
2056                                 /* mov %reg, %rsp */
2057                                 if (cfa->base == CFI_SP &&
2058                                     cfi->vals[op->src.reg].base == CFI_CFA) {
2059
2060                                         /*
2061                                          * This is needed for the rare case
2062                                          * where GCC does something dumb like:
2063                                          *
2064                                          *   lea    0x8(%rsp), %rcx
2065                                          *   ...
2066                                          *   mov    %rcx, %rsp
2067                                          */
2068                                         cfa->offset = -cfi->vals[op->src.reg].offset;
2069                                         cfi->stack_size = cfa->offset;
2070
2071                                 } else if (cfa->base == CFI_SP &&
2072                                            cfi->vals[op->src.reg].base == CFI_SP_INDIRECT &&
2073                                            cfi->vals[op->src.reg].offset == cfa->offset) {
2074
2075                                         /*
2076                                          * Stack swizzle:
2077                                          *
2078                                          * 1: mov %rsp, (%[tos])
2079                                          * 2: mov %[tos], %rsp
2080                                          *    ...
2081                                          * 3: pop %rsp
2082                                          *
2083                                          * Where:
2084                                          *
2085                                          * 1 - places a pointer to the previous
2086                                          *     stack at the Top-of-Stack of the
2087                                          *     new stack.
2088                                          *
2089                                          * 2 - switches to the new stack.
2090                                          *
2091                                          * 3 - pops the Top-of-Stack to restore
2092                                          *     the original stack.
2093                                          *
2094                                          * Note: we set base to SP_INDIRECT
2095                                          * here and preserve offset. Therefore
2096                                          * when the unwinder reaches ToS it
2097                                          * will dereference SP and then add the
2098                                          * offset to find the next frame, IOW:
2099                                          * (%rsp) + offset.
2100                                          */
2101                                         cfa->base = CFI_SP_INDIRECT;
2102
2103                                 } else {
2104                                         cfa->base = CFI_UNDEFINED;
2105                                         cfa->offset = 0;
2106                                 }
2107                         }
2108
2109                         else if (op->dest.reg == CFI_SP &&
2110                                  cfi->vals[op->src.reg].base == CFI_SP_INDIRECT &&
2111                                  cfi->vals[op->src.reg].offset == cfa->offset) {
2112
2113                                 /*
2114                                  * The same stack swizzle case 2) as above. But
2115                                  * because we can't change cfa->base, case 3)
2116                                  * will become a regular POP. Pretend we're a
2117                                  * PUSH so things don't go unbalanced.
2118                                  */
2119                                 cfi->stack_size += 8;
2120                         }
2121
2122
2123                         break;
2124
2125                 case OP_SRC_ADD:
2126                         if (op->dest.reg == CFI_SP && op->src.reg == CFI_SP) {
2127
2128                                 /* add imm, %rsp */
2129                                 cfi->stack_size -= op->src.offset;
2130                                 if (cfa->base == CFI_SP)
2131                                         cfa->offset -= op->src.offset;
2132                                 break;
2133                         }
2134
2135                         if (op->dest.reg == CFI_SP && op->src.reg == CFI_BP) {
2136
2137                                 /* lea disp(%rbp), %rsp */
2138                                 cfi->stack_size = -(op->src.offset + regs[CFI_BP].offset);
2139                                 break;
2140                         }
2141
2142                         if (!cfi->drap && op->src.reg == CFI_SP &&
2143                             op->dest.reg == CFI_BP && cfa->base == CFI_SP &&
2144                             check_reg_frame_pos(&regs[CFI_BP], -cfa->offset + op->src.offset)) {
2145
2146                                 /* lea disp(%rsp), %rbp */
2147                                 cfa->base = CFI_BP;
2148                                 cfa->offset -= op->src.offset;
2149                                 cfi->bp_scratch = false;
2150                                 break;
2151                         }
2152
2153                         if (op->src.reg == CFI_SP && cfa->base == CFI_SP) {
2154
2155                                 /* drap: lea disp(%rsp), %drap */
2156                                 cfi->drap_reg = op->dest.reg;
2157
2158                                 /*
2159                                  * lea disp(%rsp), %reg
2160                                  *
2161                                  * This is needed for the rare case where GCC
2162                                  * does something dumb like:
2163                                  *
2164                                  *   lea    0x8(%rsp), %rcx
2165                                  *   ...
2166                                  *   mov    %rcx, %rsp
2167                                  */
2168                                 cfi->vals[op->dest.reg].base = CFI_CFA;
2169                                 cfi->vals[op->dest.reg].offset = \
2170                                         -cfi->stack_size + op->src.offset;
2171
2172                                 break;
2173                         }
2174
2175                         if (cfi->drap && op->dest.reg == CFI_SP &&
2176                             op->src.reg == cfi->drap_reg) {
2177
2178                                  /* drap: lea disp(%drap), %rsp */
2179                                 cfa->base = CFI_SP;
2180                                 cfa->offset = cfi->stack_size = -op->src.offset;
2181                                 cfi->drap_reg = CFI_UNDEFINED;
2182                                 cfi->drap = false;
2183                                 break;
2184                         }
2185
2186                         if (op->dest.reg == cfi->cfa.base) {
2187                                 WARN_FUNC("unsupported stack register modification",
2188                                           insn->sec, insn->offset);
2189                                 return -1;
2190                         }
2191
2192                         break;
2193
2194                 case OP_SRC_AND:
2195                         if (op->dest.reg != CFI_SP ||
2196                             (cfi->drap_reg != CFI_UNDEFINED && cfa->base != CFI_SP) ||
2197                             (cfi->drap_reg == CFI_UNDEFINED && cfa->base != CFI_BP)) {
2198                                 WARN_FUNC("unsupported stack pointer realignment",
2199                                           insn->sec, insn->offset);
2200                                 return -1;
2201                         }
2202
2203                         if (cfi->drap_reg != CFI_UNDEFINED) {
2204                                 /* drap: and imm, %rsp */
2205                                 cfa->base = cfi->drap_reg;
2206                                 cfa->offset = cfi->stack_size = 0;
2207                                 cfi->drap = true;
2208                         }
2209
2210                         /*
2211                          * Older versions of GCC (4.8ish) realign the stack
2212                          * without DRAP, with a frame pointer.
2213                          */
2214
2215                         break;
2216
2217                 case OP_SRC_POP:
2218                 case OP_SRC_POPF:
2219                         if (op->dest.reg == CFI_SP && cfa->base == CFI_SP_INDIRECT) {
2220
2221                                 /* pop %rsp; # restore from a stack swizzle */
2222                                 cfa->base = CFI_SP;
2223                                 break;
2224                         }
2225
2226                         if (!cfi->drap && op->dest.reg == cfa->base) {
2227
2228                                 /* pop %rbp */
2229                                 cfa->base = CFI_SP;
2230                         }
2231
2232                         if (cfi->drap && cfa->base == CFI_BP_INDIRECT &&
2233                             op->dest.reg == cfi->drap_reg &&
2234                             cfi->drap_offset == -cfi->stack_size) {
2235
2236                                 /* drap: pop %drap */
2237                                 cfa->base = cfi->drap_reg;
2238                                 cfa->offset = 0;
2239                                 cfi->drap_offset = -1;
2240
2241                         } else if (regs[op->dest.reg].offset == -cfi->stack_size) {
2242
2243                                 /* pop %reg */
2244                                 restore_reg(cfi, op->dest.reg);
2245                         }
2246
2247                         cfi->stack_size -= 8;
2248                         if (cfa->base == CFI_SP)
2249                                 cfa->offset -= 8;
2250
2251                         break;
2252
2253                 case OP_SRC_REG_INDIRECT:
2254                         if (!cfi->drap && op->dest.reg == cfa->base &&
2255                             op->dest.reg == CFI_BP) {
2256
2257                                 /* mov disp(%rsp), %rbp */
2258                                 cfa->base = CFI_SP;
2259                                 cfa->offset = cfi->stack_size;
2260                         }
2261
2262                         if (cfi->drap && op->src.reg == CFI_BP &&
2263                             op->src.offset == cfi->drap_offset) {
2264
2265                                 /* drap: mov disp(%rbp), %drap */
2266                                 cfa->base = cfi->drap_reg;
2267                                 cfa->offset = 0;
2268                                 cfi->drap_offset = -1;
2269                         }
2270
2271                         if (cfi->drap && op->src.reg == CFI_BP &&
2272                             op->src.offset == regs[op->dest.reg].offset) {
2273
2274                                 /* drap: mov disp(%rbp), %reg */
2275                                 restore_reg(cfi, op->dest.reg);
2276
2277                         } else if (op->src.reg == cfa->base &&
2278                             op->src.offset == regs[op->dest.reg].offset + cfa->offset) {
2279
2280                                 /* mov disp(%rbp), %reg */
2281                                 /* mov disp(%rsp), %reg */
2282                                 restore_reg(cfi, op->dest.reg);
2283
2284                         } else if (op->src.reg == CFI_SP &&
2285                                    op->src.offset == regs[op->dest.reg].offset + cfi->stack_size) {
2286
2287                                 /* mov disp(%rsp), %reg */
2288                                 restore_reg(cfi, op->dest.reg);
2289                         }
2290
2291                         break;
2292
2293                 default:
2294                         WARN_FUNC("unknown stack-related instruction",
2295                                   insn->sec, insn->offset);
2296                         return -1;
2297                 }
2298
2299                 break;
2300
2301         case OP_DEST_PUSH:
2302         case OP_DEST_PUSHF:
2303                 cfi->stack_size += 8;
2304                 if (cfa->base == CFI_SP)
2305                         cfa->offset += 8;
2306
2307                 if (op->src.type != OP_SRC_REG)
2308                         break;
2309
2310                 if (cfi->drap) {
2311                         if (op->src.reg == cfa->base && op->src.reg == cfi->drap_reg) {
2312
2313                                 /* drap: push %drap */
2314                                 cfa->base = CFI_BP_INDIRECT;
2315                                 cfa->offset = -cfi->stack_size;
2316
2317                                 /* save drap so we know when to restore it */
2318                                 cfi->drap_offset = -cfi->stack_size;
2319
2320                         } else if (op->src.reg == CFI_BP && cfa->base == cfi->drap_reg) {
2321
2322                                 /* drap: push %rbp */
2323                                 cfi->stack_size = 0;
2324
2325                         } else {
2326
2327                                 /* drap: push %reg */
2328                                 save_reg(cfi, op->src.reg, CFI_BP, -cfi->stack_size);
2329                         }
2330
2331                 } else {
2332
2333                         /* push %reg */
2334                         save_reg(cfi, op->src.reg, CFI_CFA, -cfi->stack_size);
2335                 }
2336
2337                 /* detect when asm code uses rbp as a scratch register */
2338                 if (!no_fp && insn->func && op->src.reg == CFI_BP &&
2339                     cfa->base != CFI_BP)
2340                         cfi->bp_scratch = true;
2341                 break;
2342
2343         case OP_DEST_REG_INDIRECT:
2344
2345                 if (cfi->drap) {
2346                         if (op->src.reg == cfa->base && op->src.reg == cfi->drap_reg) {
2347
2348                                 /* drap: mov %drap, disp(%rbp) */
2349                                 cfa->base = CFI_BP_INDIRECT;
2350                                 cfa->offset = op->dest.offset;
2351
2352                                 /* save drap offset so we know when to restore it */
2353                                 cfi->drap_offset = op->dest.offset;
2354                         } else {
2355
2356                                 /* drap: mov reg, disp(%rbp) */
2357                                 save_reg(cfi, op->src.reg, CFI_BP, op->dest.offset);
2358                         }
2359
2360                 } else if (op->dest.reg == cfa->base) {
2361
2362                         /* mov reg, disp(%rbp) */
2363                         /* mov reg, disp(%rsp) */
2364                         save_reg(cfi, op->src.reg, CFI_CFA,
2365                                  op->dest.offset - cfi->cfa.offset);
2366
2367                 } else if (op->dest.reg == CFI_SP) {
2368
2369                         /* mov reg, disp(%rsp) */
2370                         save_reg(cfi, op->src.reg, CFI_CFA,
2371                                  op->dest.offset - cfi->stack_size);
2372
2373                 } else if (op->src.reg == CFI_SP && op->dest.offset == 0) {
2374
2375                         /* mov %rsp, (%reg); # setup a stack swizzle. */
2376                         cfi->vals[op->dest.reg].base = CFI_SP_INDIRECT;
2377                         cfi->vals[op->dest.reg].offset = cfa->offset;
2378                 }
2379
2380                 break;
2381
2382         case OP_DEST_LEAVE:
2383                 if ((!cfi->drap && cfa->base != CFI_BP) ||
2384                     (cfi->drap && cfa->base != cfi->drap_reg)) {
2385                         WARN_FUNC("leave instruction with modified stack frame",
2386                                   insn->sec, insn->offset);
2387                         return -1;
2388                 }
2389
2390                 /* leave (mov %rbp, %rsp; pop %rbp) */
2391
2392                 cfi->stack_size = -cfi->regs[CFI_BP].offset - 8;
2393                 restore_reg(cfi, CFI_BP);
2394
2395                 if (!cfi->drap) {
2396                         cfa->base = CFI_SP;
2397                         cfa->offset -= 8;
2398                 }
2399
2400                 break;
2401
2402         case OP_DEST_MEM:
2403                 if (op->src.type != OP_SRC_POP && op->src.type != OP_SRC_POPF) {
2404                         WARN_FUNC("unknown stack-related memory operation",
2405                                   insn->sec, insn->offset);
2406                         return -1;
2407                 }
2408
2409                 /* pop mem */
2410                 cfi->stack_size -= 8;
2411                 if (cfa->base == CFI_SP)
2412                         cfa->offset -= 8;
2413
2414                 break;
2415
2416         default:
2417                 WARN_FUNC("unknown stack-related instruction",
2418                           insn->sec, insn->offset);
2419                 return -1;
2420         }
2421
2422         return 0;
2423 }
2424
2425 /*
2426  * The stack layouts of alternatives instructions can sometimes diverge when
2427  * they have stack modifications.  That's fine as long as the potential stack
2428  * layouts don't conflict at any given potential instruction boundary.
2429  *
2430  * Flatten the CFIs of the different alternative code streams (both original
2431  * and replacement) into a single shared CFI array which can be used to detect
2432  * conflicts and nicely feed a linear array of ORC entries to the unwinder.
2433  */
2434 static int propagate_alt_cfi(struct objtool_file *file, struct instruction *insn)
2435 {
2436         struct cfi_state **alt_cfi;
2437         int group_off;
2438
2439         if (!insn->alt_group)
2440                 return 0;
2441
2442         alt_cfi = insn->alt_group->cfi;
2443         group_off = insn->offset - insn->alt_group->first_insn->offset;
2444
2445         if (!alt_cfi[group_off]) {
2446                 alt_cfi[group_off] = &insn->cfi;
2447         } else {
2448                 if (memcmp(alt_cfi[group_off], &insn->cfi, sizeof(struct cfi_state))) {
2449                         WARN_FUNC("stack layout conflict in alternatives",
2450                                   insn->sec, insn->offset);
2451                         return -1;
2452                 }
2453         }
2454
2455         return 0;
2456 }
2457
2458 static int handle_insn_ops(struct instruction *insn, struct insn_state *state)
2459 {
2460         struct stack_op *op;
2461
2462         list_for_each_entry(op, &insn->stack_ops, list) {
2463
2464                 if (update_cfi_state(insn, &state->cfi, op))
2465                         return 1;
2466
2467                 if (!insn->alt_group)
2468                         continue;
2469
2470                 if (op->dest.type == OP_DEST_PUSHF) {
2471                         if (!state->uaccess_stack) {
2472                                 state->uaccess_stack = 1;
2473                         } else if (state->uaccess_stack >> 31) {
2474                                 WARN_FUNC("PUSHF stack exhausted",
2475                                           insn->sec, insn->offset);
2476                                 return 1;
2477                         }
2478                         state->uaccess_stack <<= 1;
2479                         state->uaccess_stack  |= state->uaccess;
2480                 }
2481
2482                 if (op->src.type == OP_SRC_POPF) {
2483                         if (state->uaccess_stack) {
2484                                 state->uaccess = state->uaccess_stack & 1;
2485                                 state->uaccess_stack >>= 1;
2486                                 if (state->uaccess_stack == 1)
2487                                         state->uaccess_stack = 0;
2488                         }
2489                 }
2490         }
2491
2492         return 0;
2493 }
2494
2495 static bool insn_cfi_match(struct instruction *insn, struct cfi_state *cfi2)
2496 {
2497         struct cfi_state *cfi1 = &insn->cfi;
2498         int i;
2499
2500         if (memcmp(&cfi1->cfa, &cfi2->cfa, sizeof(cfi1->cfa))) {
2501
2502                 WARN_FUNC("stack state mismatch: cfa1=%d%+d cfa2=%d%+d",
2503                           insn->sec, insn->offset,
2504                           cfi1->cfa.base, cfi1->cfa.offset,
2505                           cfi2->cfa.base, cfi2->cfa.offset);
2506
2507         } else if (memcmp(&cfi1->regs, &cfi2->regs, sizeof(cfi1->regs))) {
2508                 for (i = 0; i < CFI_NUM_REGS; i++) {
2509                         if (!memcmp(&cfi1->regs[i], &cfi2->regs[i],
2510                                     sizeof(struct cfi_reg)))
2511                                 continue;
2512
2513                         WARN_FUNC("stack state mismatch: reg1[%d]=%d%+d reg2[%d]=%d%+d",
2514                                   insn->sec, insn->offset,
2515                                   i, cfi1->regs[i].base, cfi1->regs[i].offset,
2516                                   i, cfi2->regs[i].base, cfi2->regs[i].offset);
2517                         break;
2518                 }
2519
2520         } else if (cfi1->type != cfi2->type) {
2521
2522                 WARN_FUNC("stack state mismatch: type1=%d type2=%d",
2523                           insn->sec, insn->offset, cfi1->type, cfi2->type);
2524
2525         } else if (cfi1->drap != cfi2->drap ||
2526                    (cfi1->drap && cfi1->drap_reg != cfi2->drap_reg) ||
2527                    (cfi1->drap && cfi1->drap_offset != cfi2->drap_offset)) {
2528
2529                 WARN_FUNC("stack state mismatch: drap1=%d(%d,%d) drap2=%d(%d,%d)",
2530                           insn->sec, insn->offset,
2531                           cfi1->drap, cfi1->drap_reg, cfi1->drap_offset,
2532                           cfi2->drap, cfi2->drap_reg, cfi2->drap_offset);
2533
2534         } else
2535                 return true;
2536
2537         return false;
2538 }
2539
2540 static inline bool func_uaccess_safe(struct symbol *func)
2541 {
2542         if (func)
2543                 return func->uaccess_safe;
2544
2545         return false;
2546 }
2547
2548 static inline const char *call_dest_name(struct instruction *insn)
2549 {
2550         if (insn->call_dest)
2551                 return insn->call_dest->name;
2552
2553         return "{dynamic}";
2554 }
2555
2556 static inline bool noinstr_call_dest(struct symbol *func)
2557 {
2558         /*
2559          * We can't deal with indirect function calls at present;
2560          * assume they're instrumented.
2561          */
2562         if (!func)
2563                 return false;
2564
2565         /*
2566          * If the symbol is from a noinstr section; we good.
2567          */
2568         if (func->sec->noinstr)
2569                 return true;
2570
2571         /*
2572          * The __ubsan_handle_*() calls are like WARN(), they only happen when
2573          * something 'BAD' happened. At the risk of taking the machine down,
2574          * let them proceed to get the message out.
2575          */
2576         if (!strncmp(func->name, "__ubsan_handle_", 15))
2577                 return true;
2578
2579         return false;
2580 }
2581
2582 static int validate_call(struct instruction *insn, struct insn_state *state)
2583 {
2584         if (state->noinstr && state->instr <= 0 &&
2585             !noinstr_call_dest(insn->call_dest)) {
2586                 WARN_FUNC("call to %s() leaves .noinstr.text section",
2587                                 insn->sec, insn->offset, call_dest_name(insn));
2588                 return 1;
2589         }
2590
2591         if (state->uaccess && !func_uaccess_safe(insn->call_dest)) {
2592                 WARN_FUNC("call to %s() with UACCESS enabled",
2593                                 insn->sec, insn->offset, call_dest_name(insn));
2594                 return 1;
2595         }
2596
2597         if (state->df) {
2598                 WARN_FUNC("call to %s() with DF set",
2599                                 insn->sec, insn->offset, call_dest_name(insn));
2600                 return 1;
2601         }
2602
2603         return 0;
2604 }
2605
2606 static int validate_sibling_call(struct instruction *insn, struct insn_state *state)
2607 {
2608         if (has_modified_stack_frame(insn, state)) {
2609                 WARN_FUNC("sibling call from callable instruction with modified stack frame",
2610                                 insn->sec, insn->offset);
2611                 return 1;
2612         }
2613
2614         return validate_call(insn, state);
2615 }
2616
2617 static int validate_return(struct symbol *func, struct instruction *insn, struct insn_state *state)
2618 {
2619         if (state->noinstr && state->instr > 0) {
2620                 WARN_FUNC("return with instrumentation enabled",
2621                           insn->sec, insn->offset);
2622                 return 1;
2623         }
2624
2625         if (state->uaccess && !func_uaccess_safe(func)) {
2626                 WARN_FUNC("return with UACCESS enabled",
2627                           insn->sec, insn->offset);
2628                 return 1;
2629         }
2630
2631         if (!state->uaccess && func_uaccess_safe(func)) {
2632                 WARN_FUNC("return with UACCESS disabled from a UACCESS-safe function",
2633                           insn->sec, insn->offset);
2634                 return 1;
2635         }
2636
2637         if (state->df) {
2638                 WARN_FUNC("return with DF set",
2639                           insn->sec, insn->offset);
2640                 return 1;
2641         }
2642
2643         if (func && has_modified_stack_frame(insn, state)) {
2644                 WARN_FUNC("return with modified stack frame",
2645                           insn->sec, insn->offset);
2646                 return 1;
2647         }
2648
2649         if (state->cfi.bp_scratch) {
2650                 WARN_FUNC("BP used as a scratch register",
2651                           insn->sec, insn->offset);
2652                 return 1;
2653         }
2654
2655         return 0;
2656 }
2657
2658 static struct instruction *next_insn_to_validate(struct objtool_file *file,
2659                                                  struct instruction *insn)
2660 {
2661         struct alt_group *alt_group = insn->alt_group;
2662
2663         /*
2664          * Simulate the fact that alternatives are patched in-place.  When the
2665          * end of a replacement alt_group is reached, redirect objtool flow to
2666          * the end of the original alt_group.
2667          */
2668         if (alt_group && insn == alt_group->last_insn && alt_group->orig_group)
2669                 return next_insn_same_sec(file, alt_group->orig_group->last_insn);
2670
2671         return next_insn_same_sec(file, insn);
2672 }
2673
2674 /*
2675  * Follow the branch starting at the given instruction, and recursively follow
2676  * any other branches (jumps).  Meanwhile, track the frame pointer state at
2677  * each instruction and validate all the rules described in
2678  * tools/objtool/Documentation/stack-validation.txt.
2679  */
2680 static int validate_branch(struct objtool_file *file, struct symbol *func,
2681                            struct instruction *insn, struct insn_state state)
2682 {
2683         struct alternative *alt;
2684         struct instruction *next_insn;
2685         struct section *sec;
2686         u8 visited;
2687         int ret;
2688
2689         sec = insn->sec;
2690
2691         while (1) {
2692                 next_insn = next_insn_to_validate(file, insn);
2693
2694                 if (file->c_file && func && insn->func && func != insn->func->pfunc) {
2695                         WARN("%s() falls through to next function %s()",
2696                              func->name, insn->func->name);
2697                         return 1;
2698                 }
2699
2700                 if (func && insn->ignore) {
2701                         WARN_FUNC("BUG: why am I validating an ignored function?",
2702                                   sec, insn->offset);
2703                         return 1;
2704                 }
2705
2706                 visited = 1 << state.uaccess;
2707                 if (insn->visited) {
2708                         if (!insn->hint && !insn_cfi_match(insn, &state.cfi))
2709                                 return 1;
2710
2711                         if (insn->visited & visited)
2712                                 return 0;
2713                 }
2714
2715                 if (state.noinstr)
2716                         state.instr += insn->instr;
2717
2718                 if (insn->hint)
2719                         state.cfi = insn->cfi;
2720                 else
2721                         insn->cfi = state.cfi;
2722
2723                 insn->visited |= visited;
2724
2725                 if (propagate_alt_cfi(file, insn))
2726                         return 1;
2727
2728                 if (!insn->ignore_alts && !list_empty(&insn->alts)) {
2729                         bool skip_orig = false;
2730
2731                         list_for_each_entry(alt, &insn->alts, list) {
2732                                 if (alt->skip_orig)
2733                                         skip_orig = true;
2734
2735                                 ret = validate_branch(file, func, alt->insn, state);
2736                                 if (ret) {
2737                                         if (backtrace)
2738                                                 BT_FUNC("(alt)", insn);
2739                                         return ret;
2740                                 }
2741                         }
2742
2743                         if (skip_orig)
2744                                 return 0;
2745                 }
2746
2747                 if (handle_insn_ops(insn, &state))
2748                         return 1;
2749
2750                 switch (insn->type) {
2751
2752                 case INSN_RETURN:
2753                         return validate_return(func, insn, &state);
2754
2755                 case INSN_CALL:
2756                 case INSN_CALL_DYNAMIC:
2757                         ret = validate_call(insn, &state);
2758                         if (ret)
2759                                 return ret;
2760
2761                         if (!no_fp && func && !is_fentry_call(insn) &&
2762                             !has_valid_stack_frame(&state)) {
2763                                 WARN_FUNC("call without frame pointer save/setup",
2764                                           sec, insn->offset);
2765                                 return 1;
2766                         }
2767
2768                         if (dead_end_function(file, insn->call_dest))
2769                                 return 0;
2770
2771                         break;
2772
2773                 case INSN_JUMP_CONDITIONAL:
2774                 case INSN_JUMP_UNCONDITIONAL:
2775                         if (is_sibling_call(insn)) {
2776                                 ret = validate_sibling_call(insn, &state);
2777                                 if (ret)
2778                                         return ret;
2779
2780                         } else if (insn->jump_dest) {
2781                                 ret = validate_branch(file, func,
2782                                                       insn->jump_dest, state);
2783                                 if (ret) {
2784                                         if (backtrace)
2785                                                 BT_FUNC("(branch)", insn);
2786                                         return ret;
2787                                 }
2788                         }
2789
2790                         if (insn->type == INSN_JUMP_UNCONDITIONAL)
2791                                 return 0;
2792
2793                         break;
2794
2795                 case INSN_JUMP_DYNAMIC:
2796                 case INSN_JUMP_DYNAMIC_CONDITIONAL:
2797                         if (is_sibling_call(insn)) {
2798                                 ret = validate_sibling_call(insn, &state);
2799                                 if (ret)
2800                                         return ret;
2801                         }
2802
2803                         if (insn->type == INSN_JUMP_DYNAMIC)
2804                                 return 0;
2805
2806                         break;
2807
2808                 case INSN_CONTEXT_SWITCH:
2809                         if (func && (!next_insn || !next_insn->hint)) {
2810                                 WARN_FUNC("unsupported instruction in callable function",
2811                                           sec, insn->offset);
2812                                 return 1;
2813                         }
2814                         return 0;
2815
2816                 case INSN_STAC:
2817                         if (state.uaccess) {
2818                                 WARN_FUNC("recursive UACCESS enable", sec, insn->offset);
2819                                 return 1;
2820                         }
2821
2822                         state.uaccess = true;
2823                         break;
2824
2825                 case INSN_CLAC:
2826                         if (!state.uaccess && func) {
2827                                 WARN_FUNC("redundant UACCESS disable", sec, insn->offset);
2828                                 return 1;
2829                         }
2830
2831                         if (func_uaccess_safe(func) && !state.uaccess_stack) {
2832                                 WARN_FUNC("UACCESS-safe disables UACCESS", sec, insn->offset);
2833                                 return 1;
2834                         }
2835
2836                         state.uaccess = false;
2837                         break;
2838
2839                 case INSN_STD:
2840                         if (state.df) {
2841                                 WARN_FUNC("recursive STD", sec, insn->offset);
2842                                 return 1;
2843                         }
2844
2845                         state.df = true;
2846                         break;
2847
2848                 case INSN_CLD:
2849                         if (!state.df && func) {
2850                                 WARN_FUNC("redundant CLD", sec, insn->offset);
2851                                 return 1;
2852                         }
2853
2854                         state.df = false;
2855                         break;
2856
2857                 default:
2858                         break;
2859                 }
2860
2861                 if (insn->dead_end)
2862                         return 0;
2863
2864                 if (!next_insn) {
2865                         if (state.cfi.cfa.base == CFI_UNDEFINED)
2866                                 return 0;
2867                         WARN("%s: unexpected end of section", sec->name);
2868                         return 1;
2869                 }
2870
2871                 insn = next_insn;
2872         }
2873
2874         return 0;
2875 }
2876
2877 static int validate_unwind_hints(struct objtool_file *file, struct section *sec)
2878 {
2879         struct instruction *insn;
2880         struct insn_state state;
2881         int ret, warnings = 0;
2882
2883         if (!file->hints)
2884                 return 0;
2885
2886         init_insn_state(&state, sec);
2887
2888         if (sec) {
2889                 insn = find_insn(file, sec, 0);
2890                 if (!insn)
2891                         return 0;
2892         } else {
2893                 insn = list_first_entry(&file->insn_list, typeof(*insn), list);
2894         }
2895
2896         while (&insn->list != &file->insn_list && (!sec || insn->sec == sec)) {
2897                 if (insn->hint && !insn->visited) {
2898                         ret = validate_branch(file, insn->func, insn, state);
2899                         if (ret && backtrace)
2900                                 BT_FUNC("<=== (hint)", insn);
2901                         warnings += ret;
2902                 }
2903
2904                 insn = list_next_entry(insn, list);
2905         }
2906
2907         return warnings;
2908 }
2909
2910 static int validate_retpoline(struct objtool_file *file)
2911 {
2912         struct instruction *insn;
2913         int warnings = 0;
2914
2915         for_each_insn(file, insn) {
2916                 if (insn->type != INSN_JUMP_DYNAMIC &&
2917                     insn->type != INSN_CALL_DYNAMIC)
2918                         continue;
2919
2920                 if (insn->retpoline_safe)
2921                         continue;
2922
2923                 /*
2924                  * .init.text code is ran before userspace and thus doesn't
2925                  * strictly need retpolines, except for modules which are
2926                  * loaded late, they very much do need retpoline in their
2927                  * .init.text
2928                  */
2929                 if (!strcmp(insn->sec->name, ".init.text") && !module)
2930                         continue;
2931
2932                 WARN_FUNC("indirect %s found in RETPOLINE build",
2933                           insn->sec, insn->offset,
2934                           insn->type == INSN_JUMP_DYNAMIC ? "jump" : "call");
2935
2936                 warnings++;
2937         }
2938
2939         return warnings;
2940 }
2941
2942 static bool is_kasan_insn(struct instruction *insn)
2943 {
2944         return (insn->type == INSN_CALL &&
2945                 !strcmp(insn->call_dest->name, "__asan_handle_no_return"));
2946 }
2947
2948 static bool is_ubsan_insn(struct instruction *insn)
2949 {
2950         return (insn->type == INSN_CALL &&
2951                 !strcmp(insn->call_dest->name,
2952                         "__ubsan_handle_builtin_unreachable"));
2953 }
2954
2955 static bool ignore_unreachable_insn(struct objtool_file *file, struct instruction *insn)
2956 {
2957         int i;
2958         struct instruction *prev_insn;
2959
2960         if (insn->ignore || insn->type == INSN_NOP)
2961                 return true;
2962
2963         /*
2964          * Ignore any unused exceptions.  This can happen when a whitelisted
2965          * function has an exception table entry.
2966          *
2967          * Also ignore alternative replacement instructions.  This can happen
2968          * when a whitelisted function uses one of the ALTERNATIVE macros.
2969          */
2970         if (!strcmp(insn->sec->name, ".fixup") ||
2971             !strcmp(insn->sec->name, ".altinstr_replacement") ||
2972             !strcmp(insn->sec->name, ".altinstr_aux"))
2973                 return true;
2974
2975         if (!insn->func)
2976                 return false;
2977
2978         /*
2979          * CONFIG_UBSAN_TRAP inserts a UD2 when it sees
2980          * __builtin_unreachable().  The BUG() macro has an unreachable() after
2981          * the UD2, which causes GCC's undefined trap logic to emit another UD2
2982          * (or occasionally a JMP to UD2).
2983          *
2984          * It may also insert a UD2 after calling a __noreturn function.
2985          */
2986         prev_insn = list_prev_entry(insn, list);
2987         if ((prev_insn->dead_end || dead_end_function(file, prev_insn->call_dest)) &&
2988             (insn->type == INSN_BUG ||
2989              (insn->type == INSN_JUMP_UNCONDITIONAL &&
2990               insn->jump_dest && insn->jump_dest->type == INSN_BUG)))
2991                 return true;
2992
2993         /*
2994          * Check if this (or a subsequent) instruction is related to
2995          * CONFIG_UBSAN or CONFIG_KASAN.
2996          *
2997          * End the search at 5 instructions to avoid going into the weeds.
2998          */
2999         for (i = 0; i < 5; i++) {
3000
3001                 if (is_kasan_insn(insn) || is_ubsan_insn(insn))
3002                         return true;
3003
3004                 if (insn->type == INSN_JUMP_UNCONDITIONAL) {
3005                         if (insn->jump_dest &&
3006                             insn->jump_dest->func == insn->func) {
3007                                 insn = insn->jump_dest;
3008                                 continue;
3009                         }
3010
3011                         break;
3012                 }
3013
3014                 if (insn->offset + insn->len >= insn->func->offset + insn->func->len)
3015                         break;
3016
3017                 insn = list_next_entry(insn, list);
3018         }
3019
3020         return false;
3021 }
3022
3023 static int validate_symbol(struct objtool_file *file, struct section *sec,
3024                            struct symbol *sym, struct insn_state *state)
3025 {
3026         struct instruction *insn;
3027         int ret;
3028
3029         if (!sym->len) {
3030                 WARN("%s() is missing an ELF size annotation", sym->name);
3031                 return 1;
3032         }
3033
3034         if (sym->pfunc != sym || sym->alias != sym)
3035                 return 0;
3036
3037         insn = find_insn(file, sec, sym->offset);
3038         if (!insn || insn->ignore || insn->visited)
3039                 return 0;
3040
3041         state->uaccess = sym->uaccess_safe;
3042
3043         ret = validate_branch(file, insn->func, insn, *state);
3044         if (ret && backtrace)
3045                 BT_FUNC("<=== (sym)", insn);
3046         return ret;
3047 }
3048
3049 static int validate_section(struct objtool_file *file, struct section *sec)
3050 {
3051         struct insn_state state;
3052         struct symbol *func;
3053         int warnings = 0;
3054
3055         list_for_each_entry(func, &sec->symbol_list, list) {
3056                 if (func->type != STT_FUNC)
3057                         continue;
3058
3059                 init_insn_state(&state, sec);
3060                 set_func_state(&state.cfi);
3061
3062                 warnings += validate_symbol(file, sec, func, &state);
3063         }
3064
3065         return warnings;
3066 }
3067
3068 static int validate_vmlinux_functions(struct objtool_file *file)
3069 {
3070         struct section *sec;
3071         int warnings = 0;
3072
3073         sec = find_section_by_name(file->elf, ".noinstr.text");
3074         if (sec) {
3075                 warnings += validate_section(file, sec);
3076                 warnings += validate_unwind_hints(file, sec);
3077         }
3078
3079         sec = find_section_by_name(file->elf, ".entry.text");
3080         if (sec) {
3081                 warnings += validate_section(file, sec);
3082                 warnings += validate_unwind_hints(file, sec);
3083         }
3084
3085         return warnings;
3086 }
3087
3088 static int validate_functions(struct objtool_file *file)
3089 {
3090         struct section *sec;
3091         int warnings = 0;
3092
3093         for_each_sec(file, sec) {
3094                 if (!(sec->sh.sh_flags & SHF_EXECINSTR))
3095                         continue;
3096
3097                 warnings += validate_section(file, sec);
3098         }
3099
3100         return warnings;
3101 }
3102
3103 static int validate_reachable_instructions(struct objtool_file *file)
3104 {
3105         struct instruction *insn;
3106
3107         if (file->ignore_unreachables)
3108                 return 0;
3109
3110         for_each_insn(file, insn) {
3111                 if (insn->visited || ignore_unreachable_insn(file, insn))
3112                         continue;
3113
3114                 WARN_FUNC("unreachable instruction", insn->sec, insn->offset);
3115                 return 1;
3116         }
3117
3118         return 0;
3119 }
3120
3121 int check(struct objtool_file *file)
3122 {
3123         int ret, warnings = 0;
3124
3125         arch_initial_func_cfi_state(&initial_func_cfi);
3126
3127         ret = decode_sections(file);
3128         if (ret < 0)
3129                 goto out;
3130         warnings += ret;
3131
3132         if (list_empty(&file->insn_list))
3133                 goto out;
3134
3135         if (vmlinux && !validate_dup) {
3136                 ret = validate_vmlinux_functions(file);
3137                 if (ret < 0)
3138                         goto out;
3139
3140                 warnings += ret;
3141                 goto out;
3142         }
3143
3144         if (retpoline) {
3145                 ret = validate_retpoline(file);
3146                 if (ret < 0)
3147                         return ret;
3148                 warnings += ret;
3149         }
3150
3151         ret = validate_functions(file);
3152         if (ret < 0)
3153                 goto out;
3154         warnings += ret;
3155
3156         ret = validate_unwind_hints(file, NULL);
3157         if (ret < 0)
3158                 goto out;
3159         warnings += ret;
3160
3161         if (!warnings) {
3162                 ret = validate_reachable_instructions(file);
3163                 if (ret < 0)
3164                         goto out;
3165                 warnings += ret;
3166         }
3167
3168         ret = create_static_call_sections(file);
3169         if (ret < 0)
3170                 goto out;
3171         warnings += ret;
3172
3173         if (mcount) {
3174                 ret = create_mcount_loc_sections(file);
3175                 if (ret < 0)
3176                         goto out;
3177                 warnings += ret;
3178         }
3179
3180 out:
3181         /*
3182          *  For now, don't fail the kernel build on fatal warnings.  These
3183          *  errors are still fairly common due to the growing matrix of
3184          *  supported toolchains and their recent pace of change.
3185          */
3186         return 0;
3187 }