xref: /linux/tools/perf/util/arm64-frame-pointer-unwind-support.c (revision 1620ddc0dcefc6ffb85f4718086e880335d1a7f5)
1 // SPDX-License-Identifier: GPL-2.0
2 #include "arm64-frame-pointer-unwind-support.h"
3 #include "callchain.h"
4 #include "event.h"
5 #include "record.h"
6 #include "unwind.h"
7 #include <string.h>
8 
9 #define perf_event_arm_regs perf_event_arm64_regs
10 #include "../../arch/arm64/include/uapi/asm/perf_regs.h"
11 #undef perf_event_arm_regs
12 
13 struct entries {
14 	u64 stack[2];
15 	size_t length;
16 };
17 
18 #define SMPL_REG_MASK(b) (1ULL << (b))
19 
20 void add_leaf_frame_caller_opts_aarch64(struct record_opts *opts)
21 {
22 	opts->sample_user_regs |= SMPL_REG_MASK(PERF_REG_ARM64_LR);
23 }
24 
25 static bool get_leaf_frame_caller_enabled(struct perf_sample *sample)
26 {
27 	struct regs_dump *regs;
28 
29 	if (callchain_param.record_mode != CALLCHAIN_FP)
30 		return false;
31 
32 	regs = perf_sample__user_regs(sample);
33 	return  regs->regs && regs->mask & SMPL_REG_MASK(PERF_REG_ARM64_LR);
34 }
35 
36 static int add_entry(struct unwind_entry *entry, void *arg)
37 {
38 	struct entries *entries = arg;
39 
40 	entries->stack[entries->length++] = entry->ip;
41 	return 0;
42 }
43 
44 u64 get_leaf_frame_caller_aarch64(struct perf_sample *sample, struct thread *thread, int usr_idx)
45 {
46 	int ret;
47 	struct entries entries = {};
48 	struct regs_dump old_regs, *regs;
49 
50 	if (!get_leaf_frame_caller_enabled(sample))
51 		return 0;
52 
53 	/*
54 	 * If PC and SP are not recorded, get the value of PC from the stack
55 	 * and set its mask. SP is not used when doing the unwinding but it
56 	 * still needs to be set to prevent failures.
57 	 */
58 	regs = perf_sample__user_regs(sample);
59 	memcpy(&old_regs, regs, sizeof(*regs));
60 	if (!(regs->mask & SMPL_REG_MASK(PERF_REG_ARM64_PC))) {
61 		regs->cache_mask |= SMPL_REG_MASK(PERF_REG_ARM64_PC);
62 		regs->cache_regs[PERF_REG_ARM64_PC] = sample->callchain->ips[usr_idx+1];
63 	}
64 
65 	if (!(regs->mask & SMPL_REG_MASK(PERF_REG_ARM64_SP))) {
66 		regs->cache_mask |= SMPL_REG_MASK(PERF_REG_ARM64_SP);
67 		regs->cache_regs[PERF_REG_ARM64_SP] = 0;
68 	}
69 
70 	ret = unwind__get_entries(add_entry, &entries, thread, sample, 2, true);
71 	memcpy(regs, &old_regs, sizeof(*regs));
72 
73 	if (ret || entries.length != 2)
74 		return ret;
75 
76 	return callchain_param.order == ORDER_CALLER ? entries.stack[0] : entries.stack[1];
77 }
78