GNU Linux-libre 5.4.274-gnu1
[releases.git] / arch / x86 / kernel / unwind_orc.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 #include <linux/module.h>
3 #include <linux/sort.h>
4 #include <asm/ptrace.h>
5 #include <asm/stacktrace.h>
6 #include <asm/unwind.h>
7 #include <asm/orc_types.h>
8 #include <asm/orc_lookup.h>
9
10 #define orc_warn(fmt, ...) \
11         printk_deferred_once(KERN_WARNING pr_fmt("WARNING: " fmt), ##__VA_ARGS__)
12
13 extern int __start_orc_unwind_ip[];
14 extern int __stop_orc_unwind_ip[];
15 extern struct orc_entry __start_orc_unwind[];
16 extern struct orc_entry __stop_orc_unwind[];
17
18 static DEFINE_MUTEX(sort_mutex);
19 int *cur_orc_ip_table = __start_orc_unwind_ip;
20 struct orc_entry *cur_orc_table = __start_orc_unwind;
21
22 unsigned int lookup_num_blocks;
23 bool orc_init;
24
25 static inline unsigned long orc_ip(const int *ip)
26 {
27         return (unsigned long)ip + *ip;
28 }
29
30 static struct orc_entry *__orc_find(int *ip_table, struct orc_entry *u_table,
31                                     unsigned int num_entries, unsigned long ip)
32 {
33         int *first = ip_table;
34         int *last = ip_table + num_entries - 1;
35         int *mid = first, *found = first;
36
37         if (!num_entries)
38                 return NULL;
39
40         /*
41          * Do a binary range search to find the rightmost duplicate of a given
42          * starting address.  Some entries are section terminators which are
43          * "weak" entries for ensuring there are no gaps.  They should be
44          * ignored when they conflict with a real entry.
45          */
46         while (first <= last) {
47                 mid = first + ((last - first) / 2);
48
49                 if (orc_ip(mid) <= ip) {
50                         found = mid;
51                         first = mid + 1;
52                 } else
53                         last = mid - 1;
54         }
55
56         return u_table + (found - ip_table);
57 }
58
59 #ifdef CONFIG_MODULES
60 static struct orc_entry *orc_module_find(unsigned long ip)
61 {
62         struct module *mod;
63
64         mod = __module_address(ip);
65         if (!mod || !mod->arch.orc_unwind || !mod->arch.orc_unwind_ip)
66                 return NULL;
67         return __orc_find(mod->arch.orc_unwind_ip, mod->arch.orc_unwind,
68                           mod->arch.num_orcs, ip);
69 }
70 #else
71 static struct orc_entry *orc_module_find(unsigned long ip)
72 {
73         return NULL;
74 }
75 #endif
76
77 #ifdef CONFIG_DYNAMIC_FTRACE
78 static struct orc_entry *orc_find(unsigned long ip);
79
80 /*
81  * Ftrace dynamic trampolines do not have orc entries of their own.
82  * But they are copies of the ftrace entries that are static and
83  * defined in ftrace_*.S, which do have orc entries.
84  *
85  * If the unwinder comes across a ftrace trampoline, then find the
86  * ftrace function that was used to create it, and use that ftrace
87  * function's orc entry, as the placement of the return code in
88  * the stack will be identical.
89  */
90 static struct orc_entry *orc_ftrace_find(unsigned long ip)
91 {
92         struct ftrace_ops *ops;
93         unsigned long tramp_addr, offset;
94
95         ops = ftrace_ops_trampoline(ip);
96         if (!ops)
97                 return NULL;
98
99         /* Set tramp_addr to the start of the code copied by the trampoline */
100         if (ops->flags & FTRACE_OPS_FL_SAVE_REGS)
101                 tramp_addr = (unsigned long)ftrace_regs_caller;
102         else
103                 tramp_addr = (unsigned long)ftrace_caller;
104
105         /* Now place tramp_addr to the location within the trampoline ip is at */
106         offset = ip - ops->trampoline;
107         tramp_addr += offset;
108
109         /* Prevent unlikely recursion */
110         if (ip == tramp_addr)
111                 return NULL;
112
113         return orc_find(tramp_addr);
114 }
115 #else
116 static struct orc_entry *orc_ftrace_find(unsigned long ip)
117 {
118         return NULL;
119 }
120 #endif
121
122 /*
123  * If we crash with IP==0, the last successfully executed instruction
124  * was probably an indirect function call with a NULL function pointer,
125  * and we don't have unwind information for NULL.
126  * This hardcoded ORC entry for IP==0 allows us to unwind from a NULL function
127  * pointer into its parent and then continue normally from there.
128  */
129 static struct orc_entry null_orc_entry = {
130         .sp_offset = sizeof(long),
131         .sp_reg = ORC_REG_SP,
132         .bp_reg = ORC_REG_UNDEFINED,
133         .type = ORC_TYPE_CALL
134 };
135
136 /* Fake frame pointer entry -- used as a fallback for generated code */
137 static struct orc_entry orc_fp_entry = {
138         .type           = ORC_TYPE_CALL,
139         .sp_reg         = ORC_REG_BP,
140         .sp_offset      = 16,
141         .bp_reg         = ORC_REG_PREV_SP,
142         .bp_offset      = -16,
143         .end            = 0,
144 };
145
146 static struct orc_entry *orc_find(unsigned long ip)
147 {
148         static struct orc_entry *orc;
149
150         if (ip == 0)
151                 return &null_orc_entry;
152
153         /* For non-init vmlinux addresses, use the fast lookup table: */
154         if (ip >= LOOKUP_START_IP && ip < LOOKUP_STOP_IP) {
155                 unsigned int idx, start, stop;
156
157                 idx = (ip - LOOKUP_START_IP) / LOOKUP_BLOCK_SIZE;
158
159                 if (unlikely((idx >= lookup_num_blocks-1))) {
160                         orc_warn("WARNING: bad lookup idx: idx=%u num=%u ip=%pB\n",
161                                  idx, lookup_num_blocks, (void *)ip);
162                         return NULL;
163                 }
164
165                 start = orc_lookup[idx];
166                 stop = orc_lookup[idx + 1] + 1;
167
168                 if (unlikely((__start_orc_unwind + start >= __stop_orc_unwind) ||
169                              (__start_orc_unwind + stop > __stop_orc_unwind))) {
170                         orc_warn("WARNING: bad lookup value: idx=%u num=%u start=%u stop=%u ip=%pB\n",
171                                  idx, lookup_num_blocks, start, stop, (void *)ip);
172                         return NULL;
173                 }
174
175                 return __orc_find(__start_orc_unwind_ip + start,
176                                   __start_orc_unwind + start, stop - start, ip);
177         }
178
179         /* vmlinux .init slow lookup: */
180         if (init_kernel_text(ip))
181                 return __orc_find(__start_orc_unwind_ip, __start_orc_unwind,
182                                   __stop_orc_unwind_ip - __start_orc_unwind_ip, ip);
183
184         /* Module lookup: */
185         orc = orc_module_find(ip);
186         if (orc)
187                 return orc;
188
189         return orc_ftrace_find(ip);
190 }
191
192 static void orc_sort_swap(void *_a, void *_b, int size)
193 {
194         struct orc_entry *orc_a, *orc_b;
195         struct orc_entry orc_tmp;
196         int *a = _a, *b = _b, tmp;
197         int delta = _b - _a;
198
199         /* Swap the .orc_unwind_ip entries: */
200         tmp = *a;
201         *a = *b + delta;
202         *b = tmp - delta;
203
204         /* Swap the corresponding .orc_unwind entries: */
205         orc_a = cur_orc_table + (a - cur_orc_ip_table);
206         orc_b = cur_orc_table + (b - cur_orc_ip_table);
207         orc_tmp = *orc_a;
208         *orc_a = *orc_b;
209         *orc_b = orc_tmp;
210 }
211
212 static int orc_sort_cmp(const void *_a, const void *_b)
213 {
214         struct orc_entry *orc_a;
215         const int *a = _a, *b = _b;
216         unsigned long a_val = orc_ip(a);
217         unsigned long b_val = orc_ip(b);
218
219         if (a_val > b_val)
220                 return 1;
221         if (a_val < b_val)
222                 return -1;
223
224         /*
225          * The "weak" section terminator entries need to always be on the left
226          * to ensure the lookup code skips them in favor of real entries.
227          * These terminator entries exist to handle any gaps created by
228          * whitelisted .o files which didn't get objtool generation.
229          */
230         orc_a = cur_orc_table + (a - cur_orc_ip_table);
231         return orc_a->sp_reg == ORC_REG_UNDEFINED && !orc_a->end ? -1 : 1;
232 }
233
234 #ifdef CONFIG_MODULES
235 void unwind_module_init(struct module *mod, void *_orc_ip, size_t orc_ip_size,
236                         void *_orc, size_t orc_size)
237 {
238         int *orc_ip = _orc_ip;
239         struct orc_entry *orc = _orc;
240         unsigned int num_entries = orc_ip_size / sizeof(int);
241
242         WARN_ON_ONCE(orc_ip_size % sizeof(int) != 0 ||
243                      orc_size % sizeof(*orc) != 0 ||
244                      num_entries != orc_size / sizeof(*orc));
245
246         /*
247          * The 'cur_orc_*' globals allow the orc_sort_swap() callback to
248          * associate an .orc_unwind_ip table entry with its corresponding
249          * .orc_unwind entry so they can both be swapped.
250          */
251         mutex_lock(&sort_mutex);
252         cur_orc_ip_table = orc_ip;
253         cur_orc_table = orc;
254         sort(orc_ip, num_entries, sizeof(int), orc_sort_cmp, orc_sort_swap);
255         mutex_unlock(&sort_mutex);
256
257         mod->arch.orc_unwind_ip = orc_ip;
258         mod->arch.orc_unwind = orc;
259         mod->arch.num_orcs = num_entries;
260 }
261 #endif
262
263 void __init unwind_init(void)
264 {
265         size_t orc_ip_size = (void *)__stop_orc_unwind_ip - (void *)__start_orc_unwind_ip;
266         size_t orc_size = (void *)__stop_orc_unwind - (void *)__start_orc_unwind;
267         size_t num_entries = orc_ip_size / sizeof(int);
268         struct orc_entry *orc;
269         int i;
270
271         if (!num_entries || orc_ip_size % sizeof(int) != 0 ||
272             orc_size % sizeof(struct orc_entry) != 0 ||
273             num_entries != orc_size / sizeof(struct orc_entry)) {
274                 orc_warn("WARNING: Bad or missing .orc_unwind table.  Disabling unwinder.\n");
275                 return;
276         }
277
278         /* Sort the .orc_unwind and .orc_unwind_ip tables: */
279         sort(__start_orc_unwind_ip, num_entries, sizeof(int), orc_sort_cmp,
280              orc_sort_swap);
281
282         /* Initialize the fast lookup table: */
283         lookup_num_blocks = orc_lookup_end - orc_lookup;
284         for (i = 0; i < lookup_num_blocks-1; i++) {
285                 orc = __orc_find(__start_orc_unwind_ip, __start_orc_unwind,
286                                  num_entries,
287                                  LOOKUP_START_IP + (LOOKUP_BLOCK_SIZE * i));
288                 if (!orc) {
289                         orc_warn("WARNING: Corrupt .orc_unwind table.  Disabling unwinder.\n");
290                         return;
291                 }
292
293                 orc_lookup[i] = orc - __start_orc_unwind;
294         }
295
296         /* Initialize the ending block: */
297         orc = __orc_find(__start_orc_unwind_ip, __start_orc_unwind, num_entries,
298                          LOOKUP_STOP_IP);
299         if (!orc) {
300                 orc_warn("WARNING: Corrupt .orc_unwind table.  Disabling unwinder.\n");
301                 return;
302         }
303         orc_lookup[lookup_num_blocks-1] = orc - __start_orc_unwind;
304
305         orc_init = true;
306 }
307
308 unsigned long unwind_get_return_address(struct unwind_state *state)
309 {
310         if (unwind_done(state))
311                 return 0;
312
313         return __kernel_text_address(state->ip) ? state->ip : 0;
314 }
315 EXPORT_SYMBOL_GPL(unwind_get_return_address);
316
317 unsigned long *unwind_get_return_address_ptr(struct unwind_state *state)
318 {
319         if (unwind_done(state))
320                 return NULL;
321
322         if (state->regs)
323                 return &state->regs->ip;
324
325         if (state->sp)
326                 return (unsigned long *)state->sp - 1;
327
328         return NULL;
329 }
330
331 static bool stack_access_ok(struct unwind_state *state, unsigned long _addr,
332                             size_t len)
333 {
334         struct stack_info *info = &state->stack_info;
335         void *addr = (void *)_addr;
336
337         if (!on_stack(info, addr, len) &&
338             (get_stack_info(addr, state->task, info, &state->stack_mask)))
339                 return false;
340
341         return true;
342 }
343
344 static bool deref_stack_reg(struct unwind_state *state, unsigned long addr,
345                             unsigned long *val)
346 {
347         if (!stack_access_ok(state, addr, sizeof(long)))
348                 return false;
349
350         *val = READ_ONCE_NOCHECK(*(unsigned long *)addr);
351         return true;
352 }
353
354 static bool deref_stack_regs(struct unwind_state *state, unsigned long addr,
355                              unsigned long *ip, unsigned long *sp)
356 {
357         struct pt_regs *regs = (struct pt_regs *)addr;
358
359         /* x86-32 support will be more complicated due to the &regs->sp hack */
360         BUILD_BUG_ON(IS_ENABLED(CONFIG_X86_32));
361
362         if (!stack_access_ok(state, addr, sizeof(struct pt_regs)))
363                 return false;
364
365         *ip = READ_ONCE_NOCHECK(regs->ip);
366         *sp = READ_ONCE_NOCHECK(regs->sp);
367         return true;
368 }
369
370 static bool deref_stack_iret_regs(struct unwind_state *state, unsigned long addr,
371                                   unsigned long *ip, unsigned long *sp)
372 {
373         struct pt_regs *regs = (void *)addr - IRET_FRAME_OFFSET;
374
375         if (!stack_access_ok(state, addr, IRET_FRAME_SIZE))
376                 return false;
377
378         *ip = READ_ONCE_NOCHECK(regs->ip);
379         *sp = READ_ONCE_NOCHECK(regs->sp);
380         return true;
381 }
382
383 /*
384  * If state->regs is non-NULL, and points to a full pt_regs, just get the reg
385  * value from state->regs.
386  *
387  * Otherwise, if state->regs just points to IRET regs, and the previous frame
388  * had full regs, it's safe to get the value from the previous regs.  This can
389  * happen when early/late IRQ entry code gets interrupted by an NMI.
390  */
391 static bool get_reg(struct unwind_state *state, unsigned int reg_off,
392                     unsigned long *val)
393 {
394         unsigned int reg = reg_off/8;
395
396         if (!state->regs)
397                 return false;
398
399         if (state->full_regs) {
400                 *val = READ_ONCE_NOCHECK(((unsigned long *)state->regs)[reg]);
401                 return true;
402         }
403
404         if (state->prev_regs) {
405                 *val = READ_ONCE_NOCHECK(((unsigned long *)state->prev_regs)[reg]);
406                 return true;
407         }
408
409         return false;
410 }
411
412 bool unwind_next_frame(struct unwind_state *state)
413 {
414         unsigned long ip_p, sp, tmp, orig_ip = state->ip, prev_sp = state->sp;
415         enum stack_type prev_type = state->stack_info.type;
416         struct orc_entry *orc;
417         bool indirect = false;
418
419         if (unwind_done(state))
420                 return false;
421
422         /* Don't let modules unload while we're reading their ORC data. */
423         preempt_disable();
424
425         /* End-of-stack check for user tasks: */
426         if (state->regs && user_mode(state->regs))
427                 goto the_end;
428
429         /*
430          * Find the orc_entry associated with the text address.
431          *
432          * For a call frame (as opposed to a signal frame), state->ip points to
433          * the instruction after the call.  That instruction's stack layout
434          * could be different from the call instruction's layout, for example
435          * if the call was to a noreturn function.  So get the ORC data for the
436          * call instruction itself.
437          */
438         orc = orc_find(state->signal ? state->ip : state->ip - 1);
439         if (!orc) {
440                 /*
441                  * As a fallback, try to assume this code uses a frame pointer.
442                  * This is useful for generated code, like BPF, which ORC
443                  * doesn't know about.  This is just a guess, so the rest of
444                  * the unwind is no longer considered reliable.
445                  */
446                 orc = &orc_fp_entry;
447                 state->error = true;
448         }
449
450         /* End-of-stack check for kernel threads: */
451         if (orc->sp_reg == ORC_REG_UNDEFINED) {
452                 if (!orc->end)
453                         goto err;
454
455                 goto the_end;
456         }
457
458         /* Find the previous frame's stack: */
459         switch (orc->sp_reg) {
460         case ORC_REG_SP:
461                 sp = state->sp + orc->sp_offset;
462                 break;
463
464         case ORC_REG_BP:
465                 sp = state->bp + orc->sp_offset;
466                 break;
467
468         case ORC_REG_SP_INDIRECT:
469                 sp = state->sp + orc->sp_offset;
470                 indirect = true;
471                 break;
472
473         case ORC_REG_BP_INDIRECT:
474                 sp = state->bp + orc->sp_offset;
475                 indirect = true;
476                 break;
477
478         case ORC_REG_R10:
479                 if (!get_reg(state, offsetof(struct pt_regs, r10), &sp)) {
480                         orc_warn("missing regs for base reg R10 at ip %pB\n",
481                                  (void *)state->ip);
482                         goto err;
483                 }
484                 break;
485
486         case ORC_REG_R13:
487                 if (!get_reg(state, offsetof(struct pt_regs, r13), &sp)) {
488                         orc_warn("missing regs for base reg R13 at ip %pB\n",
489                                  (void *)state->ip);
490                         goto err;
491                 }
492                 break;
493
494         case ORC_REG_DI:
495                 if (!get_reg(state, offsetof(struct pt_regs, di), &sp)) {
496                         orc_warn("missing regs for base reg DI at ip %pB\n",
497                                  (void *)state->ip);
498                         goto err;
499                 }
500                 break;
501
502         case ORC_REG_DX:
503                 if (!get_reg(state, offsetof(struct pt_regs, dx), &sp)) {
504                         orc_warn("missing regs for base reg DX at ip %pB\n",
505                                  (void *)state->ip);
506                         goto err;
507                 }
508                 break;
509
510         default:
511                 orc_warn("unknown SP base reg %d for ip %pB\n",
512                          orc->sp_reg, (void *)state->ip);
513                 goto err;
514         }
515
516         if (indirect) {
517                 if (!deref_stack_reg(state, sp, &sp))
518                         goto err;
519         }
520
521         /* Find IP, SP and possibly regs: */
522         switch (orc->type) {
523         case ORC_TYPE_CALL:
524                 ip_p = sp - sizeof(long);
525
526                 if (!deref_stack_reg(state, ip_p, &state->ip))
527                         goto err;
528
529                 state->ip = ftrace_graph_ret_addr(state->task, &state->graph_idx,
530                                                   state->ip, (void *)ip_p);
531
532                 state->sp = sp;
533                 state->regs = NULL;
534                 state->prev_regs = NULL;
535                 state->signal = false;
536                 break;
537
538         case ORC_TYPE_REGS:
539                 if (!deref_stack_regs(state, sp, &state->ip, &state->sp)) {
540                         orc_warn("can't dereference registers at %p for ip %pB\n",
541                                  (void *)sp, (void *)orig_ip);
542                         goto err;
543                 }
544
545                 state->regs = (struct pt_regs *)sp;
546                 state->prev_regs = NULL;
547                 state->full_regs = true;
548                 state->signal = true;
549                 break;
550
551         case ORC_TYPE_REGS_IRET:
552                 if (!deref_stack_iret_regs(state, sp, &state->ip, &state->sp)) {
553                         orc_warn("can't dereference iret registers at %p for ip %pB\n",
554                                  (void *)sp, (void *)orig_ip);
555                         goto err;
556                 }
557
558                 if (state->full_regs)
559                         state->prev_regs = state->regs;
560                 state->regs = (void *)sp - IRET_FRAME_OFFSET;
561                 state->full_regs = false;
562                 state->signal = true;
563                 break;
564
565         default:
566                 orc_warn("unknown .orc_unwind entry type %d for ip %pB\n",
567                          orc->type, (void *)orig_ip);
568                 goto err;
569         }
570
571         /* Find BP: */
572         switch (orc->bp_reg) {
573         case ORC_REG_UNDEFINED:
574                 if (get_reg(state, offsetof(struct pt_regs, bp), &tmp))
575                         state->bp = tmp;
576                 break;
577
578         case ORC_REG_PREV_SP:
579                 if (!deref_stack_reg(state, sp + orc->bp_offset, &state->bp))
580                         goto err;
581                 break;
582
583         case ORC_REG_BP:
584                 if (!deref_stack_reg(state, state->bp + orc->bp_offset, &state->bp))
585                         goto err;
586                 break;
587
588         default:
589                 orc_warn("unknown BP base reg %d for ip %pB\n",
590                          orc->bp_reg, (void *)orig_ip);
591                 goto err;
592         }
593
594         /* Prevent a recursive loop due to bad ORC data: */
595         if (state->stack_info.type == prev_type &&
596             on_stack(&state->stack_info, (void *)state->sp, sizeof(long)) &&
597             state->sp <= prev_sp) {
598                 orc_warn("stack going in the wrong direction? ip=%pB\n",
599                          (void *)orig_ip);
600                 goto err;
601         }
602
603         preempt_enable();
604         return true;
605
606 err:
607         state->error = true;
608
609 the_end:
610         preempt_enable();
611         state->stack_info.type = STACK_TYPE_UNKNOWN;
612         return false;
613 }
614 EXPORT_SYMBOL_GPL(unwind_next_frame);
615
616 void __unwind_start(struct unwind_state *state, struct task_struct *task,
617                     struct pt_regs *regs, unsigned long *first_frame)
618 {
619         memset(state, 0, sizeof(*state));
620         state->task = task;
621
622         if (!orc_init)
623                 goto err;
624
625         /*
626          * Refuse to unwind the stack of a task while it's executing on another
627          * CPU.  This check is racy, but that's ok: the unwinder has other
628          * checks to prevent it from going off the rails.
629          */
630         if (task_on_another_cpu(task))
631                 goto err;
632
633         if (regs) {
634                 if (user_mode(regs))
635                         goto the_end;
636
637                 state->ip = regs->ip;
638                 state->sp = regs->sp;
639                 state->bp = regs->bp;
640                 state->regs = regs;
641                 state->full_regs = true;
642                 state->signal = true;
643
644         } else if (task == current) {
645                 asm volatile("lea (%%rip), %0\n\t"
646                              "mov %%rsp, %1\n\t"
647                              "mov %%rbp, %2\n\t"
648                              : "=r" (state->ip), "=r" (state->sp),
649                                "=r" (state->bp));
650
651         } else {
652                 struct inactive_task_frame *frame = (void *)task->thread.sp;
653
654                 state->sp = task->thread.sp + sizeof(*frame);
655                 state->bp = READ_ONCE_NOCHECK(frame->bp);
656                 state->ip = READ_ONCE_NOCHECK(frame->ret_addr);
657                 state->signal = (void *)state->ip == ret_from_fork;
658         }
659
660         if (get_stack_info((unsigned long *)state->sp, state->task,
661                            &state->stack_info, &state->stack_mask)) {
662                 /*
663                  * We weren't on a valid stack.  It's possible that
664                  * we overflowed a valid stack into a guard page.
665                  * See if the next page up is valid so that we can
666                  * generate some kind of backtrace if this happens.
667                  */
668                 void *next_page = (void *)PAGE_ALIGN((unsigned long)state->sp);
669                 state->error = true;
670                 if (get_stack_info(next_page, state->task, &state->stack_info,
671                                    &state->stack_mask))
672                         return;
673         }
674
675         /*
676          * The caller can provide the address of the first frame directly
677          * (first_frame) or indirectly (regs->sp) to indicate which stack frame
678          * to start unwinding at.  Skip ahead until we reach it.
679          */
680
681         /* When starting from regs, skip the regs frame: */
682         if (regs) {
683                 unwind_next_frame(state);
684                 return;
685         }
686
687         /* Otherwise, skip ahead to the user-specified starting frame: */
688         while (!unwind_done(state) &&
689                (!on_stack(&state->stack_info, first_frame, sizeof(long)) ||
690                         state->sp <= (unsigned long)first_frame))
691                 unwind_next_frame(state);
692
693         return;
694
695 err:
696         state->error = true;
697 the_end:
698         state->stack_info.type = STACK_TYPE_UNKNOWN;
699 }
700 EXPORT_SYMBOL_GPL(__unwind_start);