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