1 // SPDX-License-Identifier: GPL-2.0
2 #include "util/debug.h"
3 #include "util/event.h"
4 #include <subcmd/parse-options.h>
5 #include "util/parse-branch-options.h"
6 #include <stdlib.h>
7 #include <string.h>
8 
9 #define BRANCH_OPT(n, m) \
10 	{ .name = n, .mode = (m) }
11 
12 #define BRANCH_END { .name = NULL }
13 
14 struct branch_mode {
15 	const char *name;
16 	int mode;
17 };
18 
19 static const struct branch_mode branch_modes[] = {
20 	BRANCH_OPT("u", PERF_SAMPLE_BRANCH_USER),
21 	BRANCH_OPT("k", PERF_SAMPLE_BRANCH_KERNEL),
22 	BRANCH_OPT("hv", PERF_SAMPLE_BRANCH_HV),
23 	BRANCH_OPT("any", PERF_SAMPLE_BRANCH_ANY),
24 	BRANCH_OPT("any_call", PERF_SAMPLE_BRANCH_ANY_CALL),
25 	BRANCH_OPT("any_ret", PERF_SAMPLE_BRANCH_ANY_RETURN),
26 	BRANCH_OPT("ind_call", PERF_SAMPLE_BRANCH_IND_CALL),
27 	BRANCH_OPT("abort_tx", PERF_SAMPLE_BRANCH_ABORT_TX),
28 	BRANCH_OPT("in_tx", PERF_SAMPLE_BRANCH_IN_TX),
29 	BRANCH_OPT("no_tx", PERF_SAMPLE_BRANCH_NO_TX),
30 	BRANCH_OPT("cond", PERF_SAMPLE_BRANCH_COND),
31 	BRANCH_OPT("ind_jmp", PERF_SAMPLE_BRANCH_IND_JUMP),
32 	BRANCH_OPT("call", PERF_SAMPLE_BRANCH_CALL),
33 	BRANCH_OPT("save_type", PERF_SAMPLE_BRANCH_TYPE_SAVE),
34 	BRANCH_OPT("stack", PERF_SAMPLE_BRANCH_CALL_STACK),
35 	BRANCH_OPT("priv", PERF_SAMPLE_BRANCH_PRIV_SAVE),
36 	BRANCH_END
37 };
38 
39 int parse_branch_str(const char *str, __u64 *mode)
40 {
41 #define ONLY_PLM \
42 	(PERF_SAMPLE_BRANCH_USER	|\
43 	 PERF_SAMPLE_BRANCH_KERNEL	|\
44 	 PERF_SAMPLE_BRANCH_HV)
45 
46 	int ret = 0;
47 	char *p, *s;
48 	char *os = NULL;
49 	const struct branch_mode *br;
50 
51 	if (str == NULL) {
52 		*mode = PERF_SAMPLE_BRANCH_ANY;
53 		return 0;
54 	}
55 
56 	/* because str is read-only */
57 	s = os = strdup(str);
58 	if (!s)
59 		return -1;
60 
61 	for (;;) {
62 		p = strchr(s, ',');
63 		if (p)
64 			*p = '\0';
65 
66 		for (br = branch_modes; br->name; br++) {
67 			if (!strcasecmp(s, br->name))
68 				break;
69 		}
70 		if (!br->name) {
71 			ret = -1;
72 			pr_warning("unknown branch filter %s,"
73 				    " check man page\n", s);
74 			goto error;
75 		}
76 
77 		*mode |= br->mode;
78 
79 		if (!p)
80 			break;
81 
82 		s = p + 1;
83 	}
84 
85 	/* default to any branch */
86 	if ((*mode & ~ONLY_PLM) == 0) {
87 		*mode = PERF_SAMPLE_BRANCH_ANY;
88 	}
89 error:
90 	free(os);
91 	return ret;
92 }
93 
94 int
95 parse_branch_stack(const struct option *opt, const char *str, int unset)
96 {
97 	__u64 *mode = (__u64 *)opt->value;
98 
99 	if (unset)
100 		return 0;
101 
102 	/*
103 	 * cannot set it twice, -b + --branch-filter for instance
104 	 */
105 	if (*mode) {
106 		pr_err("Error: Can't use --branch-any (-b) with --branch-filter (-j).\n");
107 		return -1;
108 	}
109 
110 	return parse_branch_str(str, mode);
111 }
112