|
| 1 | +/* |
| 2 | + * Copyright (c) 2023 KNS Group LLC (YADRO) |
| 3 | + * Copyright (c) 2020 Yonatan Goldschmidt <[email protected]> |
| 4 | + * |
| 5 | + * SPDX-License-Identifier: Apache-2.0 |
| 6 | + */ |
| 7 | + |
| 8 | +#include <zephyr/kernel.h> |
| 9 | + |
| 10 | +static bool valid_stack(uintptr_t addr, k_tid_t current) |
| 11 | +{ |
| 12 | + return current->stack_info.start <= addr && |
| 13 | + addr < current->stack_info.start + current->stack_info.size; |
| 14 | +} |
| 15 | + |
| 16 | +/* interruption stack frame */ |
| 17 | +struct isf { |
| 18 | + uint32_t ebp; |
| 19 | + uint32_t ecx; |
| 20 | + uint32_t edx; |
| 21 | + uint32_t eax; |
| 22 | + uint32_t eip; |
| 23 | +}; |
| 24 | + |
| 25 | +/* |
| 26 | + * This function use frame pointers to unwind stack and get trace of return addresses. |
| 27 | + * Return addresses are translated in corresponding function's names using .elf file. |
| 28 | + * So we get function call trace |
| 29 | + */ |
| 30 | +size_t arch_perf_current_stack_trace(uintptr_t *buf, size_t size) |
| 31 | +{ |
| 32 | + if (size < 1U) |
| 33 | + return 0; |
| 34 | + |
| 35 | + size_t idx = 0; |
| 36 | + |
| 37 | + const struct isf * const isf = |
| 38 | + *((struct isf **)(((void **)_current_cpu->irq_stack)-1)); |
| 39 | + /* |
| 40 | + * In x86 (arch/x86/core/ia32/intstub.S) %eip and %ebp |
| 41 | + * are saved at the beginning of _interrupt_enter in order, that described |
| 42 | + * in struct esf. Core switch %esp to |
| 43 | + * _current_cpu->irq_stack and push %esp on irq stack |
| 44 | + * |
| 45 | + * The following lines lines do the reverse things to get %eip and %ebp |
| 46 | + * from thread stack |
| 47 | + */ |
| 48 | + void **fp = (void **)isf->ebp; |
| 49 | + |
| 50 | + /* |
| 51 | + * %ebp is frame pointer. |
| 52 | + * |
| 53 | + * stack frame in memory: |
| 54 | + * (addresses growth up) |
| 55 | + * .... |
| 56 | + * ra |
| 57 | + * %ebp (next) <- %ebp (curr) |
| 58 | + * .... |
| 59 | + */ |
| 60 | + |
| 61 | + buf[idx++] = (uintptr_t)isf->eip; |
| 62 | + while (valid_stack((uintptr_t)fp, _current)) { |
| 63 | + if (idx >= size) |
| 64 | + return 0; |
| 65 | + |
| 66 | + buf[idx++] = (uintptr_t)fp[1]; |
| 67 | + void **new_fp = (void **)fp[0]; |
| 68 | + |
| 69 | + /* |
| 70 | + * anti-infinity-loop if |
| 71 | + * new_fp can't be smaller than fp, cause the stack is growing down |
| 72 | + * and trace moves deeper into the stack |
| 73 | + */ |
| 74 | + if (new_fp <= fp) { |
| 75 | + break; |
| 76 | + } |
| 77 | + fp = new_fp; |
| 78 | + } |
| 79 | + |
| 80 | + return idx; |
| 81 | +} |
0 commit comments