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