1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/hw_breakpoint.h>
3 #include <linux/err.h>
4 #include <linux/list_sort.h>
5 #include <linux/zalloc.h>
6 #include <dirent.h>
7 #include <errno.h>
8 #include <sys/ioctl.h>
9 #include <sys/param.h>
10 #include "term.h"
11 #include "evlist.h"
12 #include "evsel.h"
13 #include <subcmd/parse-options.h>
14 #include "parse-events.h"
15 #include "string2.h"
16 #include "strbuf.h"
17 #include "debug.h"
18 #include <api/fs/tracing_path.h>
19 #include <perf/cpumap.h>
20 #include <util/parse-events-bison.h>
21 #include <util/parse-events-flex.h>
22 #include "pmu.h"
23 #include "pmus.h"
24 #include "asm/bug.h"
25 #include "util/parse-branch-options.h"
26 #include "util/evsel_config.h"
27 #include "util/event.h"
28 #include "util/bpf-filter.h"
29 #include "util/util.h"
30 #include "tracepoint.h"
31 
32 #define MAX_NAME_LEN 100
33 
34 #ifdef PARSER_DEBUG
35 extern int parse_events_debug;
36 #endif
37 static int get_config_terms(struct list_head *head_config,
38 			    struct list_head *head_terms __maybe_unused);
39 
40 struct event_symbol event_symbols_hw[PERF_COUNT_HW_MAX] = {
41 	[PERF_COUNT_HW_CPU_CYCLES] = {
42 		.symbol = "cpu-cycles",
43 		.alias  = "cycles",
44 	},
45 	[PERF_COUNT_HW_INSTRUCTIONS] = {
46 		.symbol = "instructions",
47 		.alias  = "",
48 	},
49 	[PERF_COUNT_HW_CACHE_REFERENCES] = {
50 		.symbol = "cache-references",
51 		.alias  = "",
52 	},
53 	[PERF_COUNT_HW_CACHE_MISSES] = {
54 		.symbol = "cache-misses",
55 		.alias  = "",
56 	},
57 	[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = {
58 		.symbol = "branch-instructions",
59 		.alias  = "branches",
60 	},
61 	[PERF_COUNT_HW_BRANCH_MISSES] = {
62 		.symbol = "branch-misses",
63 		.alias  = "",
64 	},
65 	[PERF_COUNT_HW_BUS_CYCLES] = {
66 		.symbol = "bus-cycles",
67 		.alias  = "",
68 	},
69 	[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = {
70 		.symbol = "stalled-cycles-frontend",
71 		.alias  = "idle-cycles-frontend",
72 	},
73 	[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = {
74 		.symbol = "stalled-cycles-backend",
75 		.alias  = "idle-cycles-backend",
76 	},
77 	[PERF_COUNT_HW_REF_CPU_CYCLES] = {
78 		.symbol = "ref-cycles",
79 		.alias  = "",
80 	},
81 };
82 
83 struct event_symbol event_symbols_sw[PERF_COUNT_SW_MAX] = {
84 	[PERF_COUNT_SW_CPU_CLOCK] = {
85 		.symbol = "cpu-clock",
86 		.alias  = "",
87 	},
88 	[PERF_COUNT_SW_TASK_CLOCK] = {
89 		.symbol = "task-clock",
90 		.alias  = "",
91 	},
92 	[PERF_COUNT_SW_PAGE_FAULTS] = {
93 		.symbol = "page-faults",
94 		.alias  = "faults",
95 	},
96 	[PERF_COUNT_SW_CONTEXT_SWITCHES] = {
97 		.symbol = "context-switches",
98 		.alias  = "cs",
99 	},
100 	[PERF_COUNT_SW_CPU_MIGRATIONS] = {
101 		.symbol = "cpu-migrations",
102 		.alias  = "migrations",
103 	},
104 	[PERF_COUNT_SW_PAGE_FAULTS_MIN] = {
105 		.symbol = "minor-faults",
106 		.alias  = "",
107 	},
108 	[PERF_COUNT_SW_PAGE_FAULTS_MAJ] = {
109 		.symbol = "major-faults",
110 		.alias  = "",
111 	},
112 	[PERF_COUNT_SW_ALIGNMENT_FAULTS] = {
113 		.symbol = "alignment-faults",
114 		.alias  = "",
115 	},
116 	[PERF_COUNT_SW_EMULATION_FAULTS] = {
117 		.symbol = "emulation-faults",
118 		.alias  = "",
119 	},
120 	[PERF_COUNT_SW_DUMMY] = {
121 		.symbol = "dummy",
122 		.alias  = "",
123 	},
124 	[PERF_COUNT_SW_BPF_OUTPUT] = {
125 		.symbol = "bpf-output",
126 		.alias  = "",
127 	},
128 	[PERF_COUNT_SW_CGROUP_SWITCHES] = {
129 		.symbol = "cgroup-switches",
130 		.alias  = "",
131 	},
132 };
133 
event_type(int type)134 const char *event_type(int type)
135 {
136 	switch (type) {
137 	case PERF_TYPE_HARDWARE:
138 		return "hardware";
139 
140 	case PERF_TYPE_SOFTWARE:
141 		return "software";
142 
143 	case PERF_TYPE_TRACEPOINT:
144 		return "tracepoint";
145 
146 	case PERF_TYPE_HW_CACHE:
147 		return "hardware-cache";
148 
149 	default:
150 		break;
151 	}
152 
153 	return "unknown";
154 }
155 
get_config_str(struct list_head * head_terms,enum parse_events__term_type type_term)156 static char *get_config_str(struct list_head *head_terms, enum parse_events__term_type type_term)
157 {
158 	struct parse_events_term *term;
159 
160 	if (!head_terms)
161 		return NULL;
162 
163 	list_for_each_entry(term, head_terms, list)
164 		if (term->type_term == type_term)
165 			return term->val.str;
166 
167 	return NULL;
168 }
169 
get_config_metric_id(struct list_head * head_terms)170 static char *get_config_metric_id(struct list_head *head_terms)
171 {
172 	return get_config_str(head_terms, PARSE_EVENTS__TERM_TYPE_METRIC_ID);
173 }
174 
get_config_name(struct list_head * head_terms)175 static char *get_config_name(struct list_head *head_terms)
176 {
177 	return get_config_str(head_terms, PARSE_EVENTS__TERM_TYPE_NAME);
178 }
179 
180 /**
181  * fix_raw - For each raw term see if there is an event (aka alias) in pmu that
182  *           matches the raw's string value. If the string value matches an
183  *           event then change the term to be an event, if not then change it to
184  *           be a config term. For example, "read" may be an event of the PMU or
185  *           a raw hex encoding of 0xead. The fix-up is done late so the PMU of
186  *           the event can be determined and we don't need to scan all PMUs
187  *           ahead-of-time.
188  * @config_terms: the list of terms that may contain a raw term.
189  * @pmu: the PMU to scan for events from.
190  */
fix_raw(struct list_head * config_terms,struct perf_pmu * pmu)191 static void fix_raw(struct list_head *config_terms, struct perf_pmu *pmu)
192 {
193 	struct parse_events_term *term;
194 
195 	list_for_each_entry(term, config_terms, list) {
196 		u64 num;
197 
198 		if (term->type_term != PARSE_EVENTS__TERM_TYPE_RAW)
199 			continue;
200 
201 		if (perf_pmu__have_event(pmu, term->val.str)) {
202 			zfree(&term->config);
203 			term->config = term->val.str;
204 			term->type_val = PARSE_EVENTS__TERM_TYPE_NUM;
205 			term->type_term = PARSE_EVENTS__TERM_TYPE_USER;
206 			term->val.num = 1;
207 			term->no_value = true;
208 			continue;
209 		}
210 
211 		zfree(&term->config);
212 		term->config = strdup("config");
213 		errno = 0;
214 		num = strtoull(term->val.str + 1, NULL, 16);
215 		assert(errno == 0);
216 		free(term->val.str);
217 		term->type_val = PARSE_EVENTS__TERM_TYPE_NUM;
218 		term->type_term = PARSE_EVENTS__TERM_TYPE_CONFIG;
219 		term->val.num = num;
220 		term->no_value = false;
221 	}
222 }
223 
224 static struct evsel *
__add_event(struct list_head * list,int * idx,struct perf_event_attr * attr,bool init_attr,const char * name,const char * metric_id,struct perf_pmu * pmu,struct list_head * config_terms,bool auto_merge_stats,const char * cpu_list)225 __add_event(struct list_head *list, int *idx,
226 	    struct perf_event_attr *attr,
227 	    bool init_attr,
228 	    const char *name, const char *metric_id, struct perf_pmu *pmu,
229 	    struct list_head *config_terms, bool auto_merge_stats,
230 	    const char *cpu_list)
231 {
232 	struct evsel *evsel;
233 	struct perf_cpu_map *cpus = pmu ? perf_cpu_map__get(pmu->cpus) :
234 			       cpu_list ? perf_cpu_map__new(cpu_list) : NULL;
235 
236 	if (pmu)
237 		perf_pmu__warn_invalid_formats(pmu);
238 
239 	if (pmu && (attr->type == PERF_TYPE_RAW || attr->type >= PERF_TYPE_MAX)) {
240 		perf_pmu__warn_invalid_config(pmu, attr->config, name,
241 					      PERF_PMU_FORMAT_VALUE_CONFIG, "config");
242 		perf_pmu__warn_invalid_config(pmu, attr->config1, name,
243 					      PERF_PMU_FORMAT_VALUE_CONFIG1, "config1");
244 		perf_pmu__warn_invalid_config(pmu, attr->config2, name,
245 					      PERF_PMU_FORMAT_VALUE_CONFIG2, "config2");
246 		perf_pmu__warn_invalid_config(pmu, attr->config3, name,
247 					      PERF_PMU_FORMAT_VALUE_CONFIG3, "config3");
248 	}
249 	if (init_attr)
250 		event_attr_init(attr);
251 
252 	evsel = evsel__new_idx(attr, *idx);
253 	if (!evsel) {
254 		perf_cpu_map__put(cpus);
255 		return NULL;
256 	}
257 
258 	(*idx)++;
259 	evsel->core.cpus = cpus;
260 	evsel->core.own_cpus = perf_cpu_map__get(cpus);
261 	evsel->core.requires_cpu = pmu ? pmu->is_uncore : false;
262 	evsel->core.is_pmu_core = pmu ? pmu->is_core : false;
263 	evsel->auto_merge_stats = auto_merge_stats;
264 	evsel->pmu = pmu;
265 	evsel->pmu_name = pmu ? strdup(pmu->name) : NULL;
266 
267 	if (name)
268 		evsel->name = strdup(name);
269 
270 	if (metric_id)
271 		evsel->metric_id = strdup(metric_id);
272 
273 	if (config_terms)
274 		list_splice_init(config_terms, &evsel->config_terms);
275 
276 	if (list)
277 		list_add_tail(&evsel->core.node, list);
278 
279 	return evsel;
280 }
281 
parse_events__add_event(int idx,struct perf_event_attr * attr,const char * name,const char * metric_id,struct perf_pmu * pmu)282 struct evsel *parse_events__add_event(int idx, struct perf_event_attr *attr,
283 				      const char *name, const char *metric_id,
284 				      struct perf_pmu *pmu)
285 {
286 	return __add_event(/*list=*/NULL, &idx, attr, /*init_attr=*/false, name,
287 			   metric_id, pmu, /*config_terms=*/NULL,
288 			   /*auto_merge_stats=*/false, /*cpu_list=*/NULL);
289 }
290 
add_event(struct list_head * list,int * idx,struct perf_event_attr * attr,const char * name,const char * metric_id,struct list_head * config_terms)291 static int add_event(struct list_head *list, int *idx,
292 		     struct perf_event_attr *attr, const char *name,
293 		     const char *metric_id, struct list_head *config_terms)
294 {
295 	return __add_event(list, idx, attr, /*init_attr*/true, name, metric_id,
296 			   /*pmu=*/NULL, config_terms,
297 			   /*auto_merge_stats=*/false, /*cpu_list=*/NULL) ? 0 : -ENOMEM;
298 }
299 
add_event_tool(struct list_head * list,int * idx,enum perf_tool_event tool_event)300 static int add_event_tool(struct list_head *list, int *idx,
301 			  enum perf_tool_event tool_event)
302 {
303 	struct evsel *evsel;
304 	struct perf_event_attr attr = {
305 		.type = PERF_TYPE_SOFTWARE,
306 		.config = PERF_COUNT_SW_DUMMY,
307 	};
308 
309 	evsel = __add_event(list, idx, &attr, /*init_attr=*/true, /*name=*/NULL,
310 			    /*metric_id=*/NULL, /*pmu=*/NULL,
311 			    /*config_terms=*/NULL, /*auto_merge_stats=*/false,
312 			    /*cpu_list=*/"0");
313 	if (!evsel)
314 		return -ENOMEM;
315 	evsel->tool_event = tool_event;
316 	if (tool_event == PERF_TOOL_DURATION_TIME
317 	    || tool_event == PERF_TOOL_USER_TIME
318 	    || tool_event == PERF_TOOL_SYSTEM_TIME) {
319 		free((char *)evsel->unit);
320 		evsel->unit = strdup("ns");
321 	}
322 	return 0;
323 }
324 
325 /**
326  * parse_aliases - search names for entries beginning or equalling str ignoring
327  *                 case. If mutliple entries in names match str then the longest
328  *                 is chosen.
329  * @str: The needle to look for.
330  * @names: The haystack to search.
331  * @size: The size of the haystack.
332  * @longest: Out argument giving the length of the matching entry.
333  */
parse_aliases(const char * str,const char * const names[][EVSEL__MAX_ALIASES],int size,int * longest)334 static int parse_aliases(const char *str, const char *const names[][EVSEL__MAX_ALIASES], int size,
335 			 int *longest)
336 {
337 	*longest = -1;
338 	for (int i = 0; i < size; i++) {
339 		for (int j = 0; j < EVSEL__MAX_ALIASES && names[i][j]; j++) {
340 			int n = strlen(names[i][j]);
341 
342 			if (n > *longest && !strncasecmp(str, names[i][j], n))
343 				*longest = n;
344 		}
345 		if (*longest > 0)
346 			return i;
347 	}
348 
349 	return -1;
350 }
351 
352 typedef int config_term_func_t(struct perf_event_attr *attr,
353 			       struct parse_events_term *term,
354 			       struct parse_events_error *err);
355 static int config_term_common(struct perf_event_attr *attr,
356 			      struct parse_events_term *term,
357 			      struct parse_events_error *err);
358 static int config_attr(struct perf_event_attr *attr,
359 		       struct list_head *head,
360 		       struct parse_events_error *err,
361 		       config_term_func_t config_term);
362 
363 /**
364  * parse_events__decode_legacy_cache - Search name for the legacy cache event
365  *                                     name composed of 1, 2 or 3 hyphen
366  *                                     separated sections. The first section is
367  *                                     the cache type while the others are the
368  *                                     optional op and optional result. To make
369  *                                     life hard the names in the table also
370  *                                     contain hyphens and the longest name
371  *                                     should always be selected.
372  */
parse_events__decode_legacy_cache(const char * name,int extended_pmu_type,__u64 * config)373 int parse_events__decode_legacy_cache(const char *name, int extended_pmu_type, __u64 *config)
374 {
375 	int len, cache_type = -1, cache_op = -1, cache_result = -1;
376 	const char *name_end = &name[strlen(name) + 1];
377 	const char *str = name;
378 
379 	cache_type = parse_aliases(str, evsel__hw_cache, PERF_COUNT_HW_CACHE_MAX, &len);
380 	if (cache_type == -1)
381 		return -EINVAL;
382 	str += len + 1;
383 
384 	if (str < name_end) {
385 		cache_op = parse_aliases(str, evsel__hw_cache_op,
386 					PERF_COUNT_HW_CACHE_OP_MAX, &len);
387 		if (cache_op >= 0) {
388 			if (!evsel__is_cache_op_valid(cache_type, cache_op))
389 				return -EINVAL;
390 			str += len + 1;
391 		} else {
392 			cache_result = parse_aliases(str, evsel__hw_cache_result,
393 						PERF_COUNT_HW_CACHE_RESULT_MAX, &len);
394 			if (cache_result >= 0)
395 				str += len + 1;
396 		}
397 	}
398 	if (str < name_end) {
399 		if (cache_op < 0) {
400 			cache_op = parse_aliases(str, evsel__hw_cache_op,
401 						PERF_COUNT_HW_CACHE_OP_MAX, &len);
402 			if (cache_op >= 0) {
403 				if (!evsel__is_cache_op_valid(cache_type, cache_op))
404 					return -EINVAL;
405 			}
406 		} else if (cache_result < 0) {
407 			cache_result = parse_aliases(str, evsel__hw_cache_result,
408 						PERF_COUNT_HW_CACHE_RESULT_MAX, &len);
409 		}
410 	}
411 
412 	/*
413 	 * Fall back to reads:
414 	 */
415 	if (cache_op == -1)
416 		cache_op = PERF_COUNT_HW_CACHE_OP_READ;
417 
418 	/*
419 	 * Fall back to accesses:
420 	 */
421 	if (cache_result == -1)
422 		cache_result = PERF_COUNT_HW_CACHE_RESULT_ACCESS;
423 
424 	*config = cache_type | (cache_op << 8) | (cache_result << 16);
425 	if (perf_pmus__supports_extended_type())
426 		*config |= (__u64)extended_pmu_type << PERF_PMU_TYPE_SHIFT;
427 	return 0;
428 }
429 
430 /**
431  * parse_events__filter_pmu - returns false if a wildcard PMU should be
432  *                            considered, true if it should be filtered.
433  */
parse_events__filter_pmu(const struct parse_events_state * parse_state,const struct perf_pmu * pmu)434 bool parse_events__filter_pmu(const struct parse_events_state *parse_state,
435 			      const struct perf_pmu *pmu)
436 {
437 	if (parse_state->pmu_filter == NULL)
438 		return false;
439 
440 	return strcmp(parse_state->pmu_filter, pmu->name) != 0;
441 }
442 
parse_events_add_cache(struct list_head * list,int * idx,const char * name,struct parse_events_state * parse_state,struct list_head * head_config)443 int parse_events_add_cache(struct list_head *list, int *idx, const char *name,
444 			   struct parse_events_state *parse_state,
445 			   struct list_head *head_config)
446 {
447 	struct perf_pmu *pmu = NULL;
448 	bool found_supported = false;
449 	const char *config_name = get_config_name(head_config);
450 	const char *metric_id = get_config_metric_id(head_config);
451 
452 	/* Legacy cache events are only supported by core PMUs. */
453 	while ((pmu = perf_pmus__scan_core(pmu)) != NULL) {
454 		LIST_HEAD(config_terms);
455 		struct perf_event_attr attr;
456 		int ret;
457 
458 		if (parse_events__filter_pmu(parse_state, pmu))
459 			continue;
460 
461 		memset(&attr, 0, sizeof(attr));
462 		attr.type = PERF_TYPE_HW_CACHE;
463 
464 		ret = parse_events__decode_legacy_cache(name, pmu->type, &attr.config);
465 		if (ret)
466 			return ret;
467 
468 		found_supported = true;
469 
470 		if (head_config) {
471 			if (config_attr(&attr, head_config, parse_state->error, config_term_common))
472 				return -EINVAL;
473 
474 			if (get_config_terms(head_config, &config_terms))
475 				return -ENOMEM;
476 		}
477 
478 		if (__add_event(list, idx, &attr, /*init_attr*/true, config_name ?: name,
479 				metric_id, pmu, &config_terms, /*auto_merge_stats=*/false,
480 				/*cpu_list=*/NULL) == NULL)
481 			return -ENOMEM;
482 
483 		free_config_terms(&config_terms);
484 	}
485 	return found_supported ? 0 : -EINVAL;
486 }
487 
488 #ifdef HAVE_LIBTRACEEVENT
tracepoint_error(struct parse_events_error * e,int err,const char * sys,const char * name,int column)489 static void tracepoint_error(struct parse_events_error *e, int err,
490 			     const char *sys, const char *name, int column)
491 {
492 	const char *str;
493 	char help[BUFSIZ];
494 
495 	if (!e)
496 		return;
497 
498 	/*
499 	 * We get error directly from syscall errno ( > 0),
500 	 * or from encoded pointer's error ( < 0).
501 	 */
502 	err = abs(err);
503 
504 	switch (err) {
505 	case EACCES:
506 		str = "can't access trace events";
507 		break;
508 	case ENOENT:
509 		str = "unknown tracepoint";
510 		break;
511 	default:
512 		str = "failed to add tracepoint";
513 		break;
514 	}
515 
516 	tracing_path__strerror_open_tp(err, help, sizeof(help), sys, name);
517 	parse_events_error__handle(e, column, strdup(str), strdup(help));
518 }
519 
add_tracepoint(struct list_head * list,int * idx,const char * sys_name,const char * evt_name,struct parse_events_error * err,struct list_head * head_config,void * loc_)520 static int add_tracepoint(struct list_head *list, int *idx,
521 			  const char *sys_name, const char *evt_name,
522 			  struct parse_events_error *err,
523 			  struct list_head *head_config, void *loc_)
524 {
525 	YYLTYPE *loc = loc_;
526 	struct evsel *evsel = evsel__newtp_idx(sys_name, evt_name, (*idx)++);
527 
528 	if (IS_ERR(evsel)) {
529 		tracepoint_error(err, PTR_ERR(evsel), sys_name, evt_name, loc->first_column);
530 		return PTR_ERR(evsel);
531 	}
532 
533 	if (head_config) {
534 		LIST_HEAD(config_terms);
535 
536 		if (get_config_terms(head_config, &config_terms))
537 			return -ENOMEM;
538 		list_splice(&config_terms, &evsel->config_terms);
539 	}
540 
541 	list_add_tail(&evsel->core.node, list);
542 	return 0;
543 }
544 
add_tracepoint_multi_event(struct list_head * list,int * idx,const char * sys_name,const char * evt_name,struct parse_events_error * err,struct list_head * head_config,YYLTYPE * loc)545 static int add_tracepoint_multi_event(struct list_head *list, int *idx,
546 				      const char *sys_name, const char *evt_name,
547 				      struct parse_events_error *err,
548 				      struct list_head *head_config, YYLTYPE *loc)
549 {
550 	char *evt_path;
551 	struct dirent *evt_ent;
552 	DIR *evt_dir;
553 	int ret = 0, found = 0;
554 
555 	evt_path = get_events_file(sys_name);
556 	if (!evt_path) {
557 		tracepoint_error(err, errno, sys_name, evt_name, loc->first_column);
558 		return -1;
559 	}
560 	evt_dir = opendir(evt_path);
561 	if (!evt_dir) {
562 		put_events_file(evt_path);
563 		tracepoint_error(err, errno, sys_name, evt_name, loc->first_column);
564 		return -1;
565 	}
566 
567 	while (!ret && (evt_ent = readdir(evt_dir))) {
568 		if (!strcmp(evt_ent->d_name, ".")
569 		    || !strcmp(evt_ent->d_name, "..")
570 		    || !strcmp(evt_ent->d_name, "enable")
571 		    || !strcmp(evt_ent->d_name, "filter"))
572 			continue;
573 
574 		if (!strglobmatch(evt_ent->d_name, evt_name))
575 			continue;
576 
577 		found++;
578 
579 		ret = add_tracepoint(list, idx, sys_name, evt_ent->d_name,
580 				     err, head_config, loc);
581 	}
582 
583 	if (!found) {
584 		tracepoint_error(err, ENOENT, sys_name, evt_name, loc->first_column);
585 		ret = -1;
586 	}
587 
588 	put_events_file(evt_path);
589 	closedir(evt_dir);
590 	return ret;
591 }
592 
add_tracepoint_event(struct list_head * list,int * idx,const char * sys_name,const char * evt_name,struct parse_events_error * err,struct list_head * head_config,YYLTYPE * loc)593 static int add_tracepoint_event(struct list_head *list, int *idx,
594 				const char *sys_name, const char *evt_name,
595 				struct parse_events_error *err,
596 				struct list_head *head_config, YYLTYPE *loc)
597 {
598 	return strpbrk(evt_name, "*?") ?
599 		add_tracepoint_multi_event(list, idx, sys_name, evt_name,
600 					   err, head_config, loc) :
601 		add_tracepoint(list, idx, sys_name, evt_name,
602 			       err, head_config, loc);
603 }
604 
add_tracepoint_multi_sys(struct list_head * list,int * idx,const char * sys_name,const char * evt_name,struct parse_events_error * err,struct list_head * head_config,YYLTYPE * loc)605 static int add_tracepoint_multi_sys(struct list_head *list, int *idx,
606 				    const char *sys_name, const char *evt_name,
607 				    struct parse_events_error *err,
608 				    struct list_head *head_config, YYLTYPE *loc)
609 {
610 	struct dirent *events_ent;
611 	DIR *events_dir;
612 	int ret = 0;
613 
614 	events_dir = tracing_events__opendir();
615 	if (!events_dir) {
616 		tracepoint_error(err, errno, sys_name, evt_name, loc->first_column);
617 		return -1;
618 	}
619 
620 	while (!ret && (events_ent = readdir(events_dir))) {
621 		if (!strcmp(events_ent->d_name, ".")
622 		    || !strcmp(events_ent->d_name, "..")
623 		    || !strcmp(events_ent->d_name, "enable")
624 		    || !strcmp(events_ent->d_name, "header_event")
625 		    || !strcmp(events_ent->d_name, "header_page"))
626 			continue;
627 
628 		if (!strglobmatch(events_ent->d_name, sys_name))
629 			continue;
630 
631 		ret = add_tracepoint_event(list, idx, events_ent->d_name,
632 					   evt_name, err, head_config, loc);
633 	}
634 
635 	closedir(events_dir);
636 	return ret;
637 }
638 #endif /* HAVE_LIBTRACEEVENT */
639 
640 static int
parse_breakpoint_type(const char * type,struct perf_event_attr * attr)641 parse_breakpoint_type(const char *type, struct perf_event_attr *attr)
642 {
643 	int i;
644 
645 	for (i = 0; i < 3; i++) {
646 		if (!type || !type[i])
647 			break;
648 
649 #define CHECK_SET_TYPE(bit)		\
650 do {					\
651 	if (attr->bp_type & bit)	\
652 		return -EINVAL;		\
653 	else				\
654 		attr->bp_type |= bit;	\
655 } while (0)
656 
657 		switch (type[i]) {
658 		case 'r':
659 			CHECK_SET_TYPE(HW_BREAKPOINT_R);
660 			break;
661 		case 'w':
662 			CHECK_SET_TYPE(HW_BREAKPOINT_W);
663 			break;
664 		case 'x':
665 			CHECK_SET_TYPE(HW_BREAKPOINT_X);
666 			break;
667 		default:
668 			return -EINVAL;
669 		}
670 	}
671 
672 #undef CHECK_SET_TYPE
673 
674 	if (!attr->bp_type) /* Default */
675 		attr->bp_type = HW_BREAKPOINT_R | HW_BREAKPOINT_W;
676 
677 	return 0;
678 }
679 
parse_events_add_breakpoint(struct parse_events_state * parse_state,struct list_head * list,u64 addr,char * type,u64 len,struct list_head * head_config __maybe_unused)680 int parse_events_add_breakpoint(struct parse_events_state *parse_state,
681 				struct list_head *list,
682 				u64 addr, char *type, u64 len,
683 				struct list_head *head_config __maybe_unused)
684 {
685 	struct perf_event_attr attr;
686 	LIST_HEAD(config_terms);
687 	const char *name;
688 
689 	memset(&attr, 0, sizeof(attr));
690 	attr.bp_addr = addr;
691 
692 	if (parse_breakpoint_type(type, &attr))
693 		return -EINVAL;
694 
695 	/* Provide some defaults if len is not specified */
696 	if (!len) {
697 		if (attr.bp_type == HW_BREAKPOINT_X)
698 			len = sizeof(long);
699 		else
700 			len = HW_BREAKPOINT_LEN_4;
701 	}
702 
703 	attr.bp_len = len;
704 
705 	attr.type = PERF_TYPE_BREAKPOINT;
706 	attr.sample_period = 1;
707 
708 	if (head_config) {
709 		if (config_attr(&attr, head_config, parse_state->error,
710 				config_term_common))
711 			return -EINVAL;
712 
713 		if (get_config_terms(head_config, &config_terms))
714 			return -ENOMEM;
715 	}
716 
717 	name = get_config_name(head_config);
718 
719 	return add_event(list, &parse_state->idx, &attr, name, /*mertic_id=*/NULL,
720 			 &config_terms);
721 }
722 
check_type_val(struct parse_events_term * term,struct parse_events_error * err,enum parse_events__term_val_type type)723 static int check_type_val(struct parse_events_term *term,
724 			  struct parse_events_error *err,
725 			  enum parse_events__term_val_type type)
726 {
727 	if (type == term->type_val)
728 		return 0;
729 
730 	if (err) {
731 		parse_events_error__handle(err, term->err_val,
732 					type == PARSE_EVENTS__TERM_TYPE_NUM
733 					? strdup("expected numeric value")
734 					: strdup("expected string value"),
735 					NULL);
736 	}
737 	return -EINVAL;
738 }
739 
740 static bool config_term_shrinked;
741 
config_term_name(enum parse_events__term_type term_type)742 static const char *config_term_name(enum parse_events__term_type term_type)
743 {
744 	/*
745 	 * Update according to parse-events.l
746 	 */
747 	static const char *config_term_names[__PARSE_EVENTS__TERM_TYPE_NR] = {
748 		[PARSE_EVENTS__TERM_TYPE_USER]			= "<sysfs term>",
749 		[PARSE_EVENTS__TERM_TYPE_CONFIG]		= "config",
750 		[PARSE_EVENTS__TERM_TYPE_CONFIG1]		= "config1",
751 		[PARSE_EVENTS__TERM_TYPE_CONFIG2]		= "config2",
752 		[PARSE_EVENTS__TERM_TYPE_CONFIG3]		= "config3",
753 		[PARSE_EVENTS__TERM_TYPE_NAME]			= "name",
754 		[PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD]		= "period",
755 		[PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ]		= "freq",
756 		[PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE]	= "branch_type",
757 		[PARSE_EVENTS__TERM_TYPE_TIME]			= "time",
758 		[PARSE_EVENTS__TERM_TYPE_CALLGRAPH]		= "call-graph",
759 		[PARSE_EVENTS__TERM_TYPE_STACKSIZE]		= "stack-size",
760 		[PARSE_EVENTS__TERM_TYPE_NOINHERIT]		= "no-inherit",
761 		[PARSE_EVENTS__TERM_TYPE_INHERIT]		= "inherit",
762 		[PARSE_EVENTS__TERM_TYPE_MAX_STACK]		= "max-stack",
763 		[PARSE_EVENTS__TERM_TYPE_MAX_EVENTS]		= "nr",
764 		[PARSE_EVENTS__TERM_TYPE_OVERWRITE]		= "overwrite",
765 		[PARSE_EVENTS__TERM_TYPE_NOOVERWRITE]		= "no-overwrite",
766 		[PARSE_EVENTS__TERM_TYPE_DRV_CFG]		= "driver-config",
767 		[PARSE_EVENTS__TERM_TYPE_PERCORE]		= "percore",
768 		[PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT]		= "aux-output",
769 		[PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE]	= "aux-sample-size",
770 		[PARSE_EVENTS__TERM_TYPE_METRIC_ID]		= "metric-id",
771 		[PARSE_EVENTS__TERM_TYPE_RAW]                   = "raw",
772 		[PARSE_EVENTS__TERM_TYPE_LEGACY_CACHE]          = "legacy-cache",
773 		[PARSE_EVENTS__TERM_TYPE_HARDWARE]              = "hardware",
774 	};
775 	if ((unsigned int)term_type >= __PARSE_EVENTS__TERM_TYPE_NR)
776 		return "unknown term";
777 
778 	return config_term_names[term_type];
779 }
780 
781 static bool
config_term_avail(enum parse_events__term_type term_type,struct parse_events_error * err)782 config_term_avail(enum parse_events__term_type term_type, struct parse_events_error *err)
783 {
784 	char *err_str;
785 
786 	if (term_type < 0 || term_type >= __PARSE_EVENTS__TERM_TYPE_NR) {
787 		parse_events_error__handle(err, -1,
788 					strdup("Invalid term_type"), NULL);
789 		return false;
790 	}
791 	if (!config_term_shrinked)
792 		return true;
793 
794 	switch (term_type) {
795 	case PARSE_EVENTS__TERM_TYPE_CONFIG:
796 	case PARSE_EVENTS__TERM_TYPE_CONFIG1:
797 	case PARSE_EVENTS__TERM_TYPE_CONFIG2:
798 	case PARSE_EVENTS__TERM_TYPE_CONFIG3:
799 	case PARSE_EVENTS__TERM_TYPE_NAME:
800 	case PARSE_EVENTS__TERM_TYPE_METRIC_ID:
801 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
802 	case PARSE_EVENTS__TERM_TYPE_PERCORE:
803 		return true;
804 	case PARSE_EVENTS__TERM_TYPE_USER:
805 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
806 	case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
807 	case PARSE_EVENTS__TERM_TYPE_TIME:
808 	case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
809 	case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
810 	case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
811 	case PARSE_EVENTS__TERM_TYPE_INHERIT:
812 	case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
813 	case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
814 	case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
815 	case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
816 	case PARSE_EVENTS__TERM_TYPE_DRV_CFG:
817 	case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
818 	case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
819 	case PARSE_EVENTS__TERM_TYPE_RAW:
820 	case PARSE_EVENTS__TERM_TYPE_LEGACY_CACHE:
821 	case PARSE_EVENTS__TERM_TYPE_HARDWARE:
822 	default:
823 		if (!err)
824 			return false;
825 
826 		/* term_type is validated so indexing is safe */
827 		if (asprintf(&err_str, "'%s' is not usable in 'perf stat'",
828 			     config_term_name(term_type)) >= 0)
829 			parse_events_error__handle(err, -1, err_str, NULL);
830 		return false;
831 	}
832 }
833 
parse_events__shrink_config_terms(void)834 void parse_events__shrink_config_terms(void)
835 {
836 	config_term_shrinked = true;
837 }
838 
config_term_common(struct perf_event_attr * attr,struct parse_events_term * term,struct parse_events_error * err)839 static int config_term_common(struct perf_event_attr *attr,
840 			      struct parse_events_term *term,
841 			      struct parse_events_error *err)
842 {
843 #define CHECK_TYPE_VAL(type)						   \
844 do {									   \
845 	if (check_type_val(term, err, PARSE_EVENTS__TERM_TYPE_ ## type)) \
846 		return -EINVAL;						   \
847 } while (0)
848 
849 	switch (term->type_term) {
850 	case PARSE_EVENTS__TERM_TYPE_CONFIG:
851 		CHECK_TYPE_VAL(NUM);
852 		attr->config = term->val.num;
853 		break;
854 	case PARSE_EVENTS__TERM_TYPE_CONFIG1:
855 		CHECK_TYPE_VAL(NUM);
856 		attr->config1 = term->val.num;
857 		break;
858 	case PARSE_EVENTS__TERM_TYPE_CONFIG2:
859 		CHECK_TYPE_VAL(NUM);
860 		attr->config2 = term->val.num;
861 		break;
862 	case PARSE_EVENTS__TERM_TYPE_CONFIG3:
863 		CHECK_TYPE_VAL(NUM);
864 		attr->config3 = term->val.num;
865 		break;
866 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
867 		CHECK_TYPE_VAL(NUM);
868 		break;
869 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
870 		CHECK_TYPE_VAL(NUM);
871 		break;
872 	case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
873 		CHECK_TYPE_VAL(STR);
874 		if (strcmp(term->val.str, "no") &&
875 		    parse_branch_str(term->val.str,
876 				    &attr->branch_sample_type)) {
877 			parse_events_error__handle(err, term->err_val,
878 					strdup("invalid branch sample type"),
879 					NULL);
880 			return -EINVAL;
881 		}
882 		break;
883 	case PARSE_EVENTS__TERM_TYPE_TIME:
884 		CHECK_TYPE_VAL(NUM);
885 		if (term->val.num > 1) {
886 			parse_events_error__handle(err, term->err_val,
887 						strdup("expected 0 or 1"),
888 						NULL);
889 			return -EINVAL;
890 		}
891 		break;
892 	case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
893 		CHECK_TYPE_VAL(STR);
894 		break;
895 	case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
896 		CHECK_TYPE_VAL(NUM);
897 		break;
898 	case PARSE_EVENTS__TERM_TYPE_INHERIT:
899 		CHECK_TYPE_VAL(NUM);
900 		break;
901 	case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
902 		CHECK_TYPE_VAL(NUM);
903 		break;
904 	case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
905 		CHECK_TYPE_VAL(NUM);
906 		break;
907 	case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
908 		CHECK_TYPE_VAL(NUM);
909 		break;
910 	case PARSE_EVENTS__TERM_TYPE_NAME:
911 		CHECK_TYPE_VAL(STR);
912 		break;
913 	case PARSE_EVENTS__TERM_TYPE_METRIC_ID:
914 		CHECK_TYPE_VAL(STR);
915 		break;
916 	case PARSE_EVENTS__TERM_TYPE_RAW:
917 		CHECK_TYPE_VAL(STR);
918 		break;
919 	case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
920 		CHECK_TYPE_VAL(NUM);
921 		break;
922 	case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
923 		CHECK_TYPE_VAL(NUM);
924 		break;
925 	case PARSE_EVENTS__TERM_TYPE_PERCORE:
926 		CHECK_TYPE_VAL(NUM);
927 		if ((unsigned int)term->val.num > 1) {
928 			parse_events_error__handle(err, term->err_val,
929 						strdup("expected 0 or 1"),
930 						NULL);
931 			return -EINVAL;
932 		}
933 		break;
934 	case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
935 		CHECK_TYPE_VAL(NUM);
936 		break;
937 	case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
938 		CHECK_TYPE_VAL(NUM);
939 		if (term->val.num > UINT_MAX) {
940 			parse_events_error__handle(err, term->err_val,
941 						strdup("too big"),
942 						NULL);
943 			return -EINVAL;
944 		}
945 		break;
946 	case PARSE_EVENTS__TERM_TYPE_DRV_CFG:
947 	case PARSE_EVENTS__TERM_TYPE_USER:
948 	case PARSE_EVENTS__TERM_TYPE_LEGACY_CACHE:
949 	case PARSE_EVENTS__TERM_TYPE_HARDWARE:
950 	default:
951 		parse_events_error__handle(err, term->err_term,
952 					strdup(config_term_name(term->type_term)),
953 					parse_events_formats_error_string(NULL));
954 		return -EINVAL;
955 	}
956 
957 	/*
958 	 * Check term availability after basic checking so
959 	 * PARSE_EVENTS__TERM_TYPE_USER can be found and filtered.
960 	 *
961 	 * If check availability at the entry of this function,
962 	 * user will see "'<sysfs term>' is not usable in 'perf stat'"
963 	 * if an invalid config term is provided for legacy events
964 	 * (for example, instructions/badterm/...), which is confusing.
965 	 */
966 	if (!config_term_avail(term->type_term, err))
967 		return -EINVAL;
968 	return 0;
969 #undef CHECK_TYPE_VAL
970 }
971 
config_term_pmu(struct perf_event_attr * attr,struct parse_events_term * term,struct parse_events_error * err)972 static int config_term_pmu(struct perf_event_attr *attr,
973 			   struct parse_events_term *term,
974 			   struct parse_events_error *err)
975 {
976 	if (term->type_term == PARSE_EVENTS__TERM_TYPE_LEGACY_CACHE) {
977 		const struct perf_pmu *pmu = perf_pmus__find_by_type(attr->type);
978 
979 		if (!pmu) {
980 			char *err_str;
981 
982 			if (asprintf(&err_str, "Failed to find PMU for type %d", attr->type) >= 0)
983 				parse_events_error__handle(err, term->err_term,
984 							   err_str, /*help=*/NULL);
985 			return -EINVAL;
986 		}
987 		if (perf_pmu__supports_legacy_cache(pmu)) {
988 			attr->type = PERF_TYPE_HW_CACHE;
989 			return parse_events__decode_legacy_cache(term->config, pmu->type,
990 								 &attr->config);
991 		} else
992 			term->type_term = PARSE_EVENTS__TERM_TYPE_USER;
993 	}
994 	if (term->type_term == PARSE_EVENTS__TERM_TYPE_HARDWARE) {
995 		const struct perf_pmu *pmu = perf_pmus__find_by_type(attr->type);
996 
997 		if (!pmu) {
998 			char *err_str;
999 
1000 			if (asprintf(&err_str, "Failed to find PMU for type %d", attr->type) >= 0)
1001 				parse_events_error__handle(err, term->err_term,
1002 							   err_str, /*help=*/NULL);
1003 			return -EINVAL;
1004 		}
1005 		attr->type = PERF_TYPE_HARDWARE;
1006 		attr->config = term->val.num;
1007 		if (perf_pmus__supports_extended_type())
1008 			attr->config |= (__u64)pmu->type << PERF_PMU_TYPE_SHIFT;
1009 		return 0;
1010 	}
1011 	if (term->type_term == PARSE_EVENTS__TERM_TYPE_USER ||
1012 	    term->type_term == PARSE_EVENTS__TERM_TYPE_DRV_CFG) {
1013 		/*
1014 		 * Always succeed for sysfs terms, as we dont know
1015 		 * at this point what type they need to have.
1016 		 */
1017 		return 0;
1018 	}
1019 	return config_term_common(attr, term, err);
1020 }
1021 
1022 #ifdef HAVE_LIBTRACEEVENT
config_term_tracepoint(struct perf_event_attr * attr,struct parse_events_term * term,struct parse_events_error * err)1023 static int config_term_tracepoint(struct perf_event_attr *attr,
1024 				  struct parse_events_term *term,
1025 				  struct parse_events_error *err)
1026 {
1027 	switch (term->type_term) {
1028 	case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1029 	case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1030 	case PARSE_EVENTS__TERM_TYPE_INHERIT:
1031 	case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1032 	case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1033 	case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
1034 	case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1035 	case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1036 	case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
1037 	case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
1038 		return config_term_common(attr, term, err);
1039 	case PARSE_EVENTS__TERM_TYPE_USER:
1040 	case PARSE_EVENTS__TERM_TYPE_CONFIG:
1041 	case PARSE_EVENTS__TERM_TYPE_CONFIG1:
1042 	case PARSE_EVENTS__TERM_TYPE_CONFIG2:
1043 	case PARSE_EVENTS__TERM_TYPE_CONFIG3:
1044 	case PARSE_EVENTS__TERM_TYPE_NAME:
1045 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
1046 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
1047 	case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
1048 	case PARSE_EVENTS__TERM_TYPE_TIME:
1049 	case PARSE_EVENTS__TERM_TYPE_DRV_CFG:
1050 	case PARSE_EVENTS__TERM_TYPE_PERCORE:
1051 	case PARSE_EVENTS__TERM_TYPE_METRIC_ID:
1052 	case PARSE_EVENTS__TERM_TYPE_RAW:
1053 	case PARSE_EVENTS__TERM_TYPE_LEGACY_CACHE:
1054 	case PARSE_EVENTS__TERM_TYPE_HARDWARE:
1055 	default:
1056 		if (err) {
1057 			parse_events_error__handle(err, term->err_term,
1058 						   strdup(config_term_name(term->type_term)),
1059 				strdup("valid terms: call-graph,stack-size\n"));
1060 		}
1061 		return -EINVAL;
1062 	}
1063 
1064 	return 0;
1065 }
1066 #endif
1067 
config_attr(struct perf_event_attr * attr,struct list_head * head,struct parse_events_error * err,config_term_func_t config_term)1068 static int config_attr(struct perf_event_attr *attr,
1069 		       struct list_head *head,
1070 		       struct parse_events_error *err,
1071 		       config_term_func_t config_term)
1072 {
1073 	struct parse_events_term *term;
1074 
1075 	list_for_each_entry(term, head, list)
1076 		if (config_term(attr, term, err))
1077 			return -EINVAL;
1078 
1079 	return 0;
1080 }
1081 
get_config_terms(struct list_head * head_config,struct list_head * head_terms __maybe_unused)1082 static int get_config_terms(struct list_head *head_config,
1083 			    struct list_head *head_terms __maybe_unused)
1084 {
1085 #define ADD_CONFIG_TERM(__type, __weak)				\
1086 	struct evsel_config_term *__t;			\
1087 								\
1088 	__t = zalloc(sizeof(*__t));				\
1089 	if (!__t)						\
1090 		return -ENOMEM;					\
1091 								\
1092 	INIT_LIST_HEAD(&__t->list);				\
1093 	__t->type       = EVSEL__CONFIG_TERM_ ## __type;	\
1094 	__t->weak	= __weak;				\
1095 	list_add_tail(&__t->list, head_terms)
1096 
1097 #define ADD_CONFIG_TERM_VAL(__type, __name, __val, __weak)	\
1098 do {								\
1099 	ADD_CONFIG_TERM(__type, __weak);			\
1100 	__t->val.__name = __val;				\
1101 } while (0)
1102 
1103 #define ADD_CONFIG_TERM_STR(__type, __val, __weak)		\
1104 do {								\
1105 	ADD_CONFIG_TERM(__type, __weak);			\
1106 	__t->val.str = strdup(__val);				\
1107 	if (!__t->val.str) {					\
1108 		zfree(&__t);					\
1109 		return -ENOMEM;					\
1110 	}							\
1111 	__t->free_str = true;					\
1112 } while (0)
1113 
1114 	struct parse_events_term *term;
1115 
1116 	list_for_each_entry(term, head_config, list) {
1117 		switch (term->type_term) {
1118 		case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
1119 			ADD_CONFIG_TERM_VAL(PERIOD, period, term->val.num, term->weak);
1120 			break;
1121 		case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
1122 			ADD_CONFIG_TERM_VAL(FREQ, freq, term->val.num, term->weak);
1123 			break;
1124 		case PARSE_EVENTS__TERM_TYPE_TIME:
1125 			ADD_CONFIG_TERM_VAL(TIME, time, term->val.num, term->weak);
1126 			break;
1127 		case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1128 			ADD_CONFIG_TERM_STR(CALLGRAPH, term->val.str, term->weak);
1129 			break;
1130 		case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
1131 			ADD_CONFIG_TERM_STR(BRANCH, term->val.str, term->weak);
1132 			break;
1133 		case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1134 			ADD_CONFIG_TERM_VAL(STACK_USER, stack_user,
1135 					    term->val.num, term->weak);
1136 			break;
1137 		case PARSE_EVENTS__TERM_TYPE_INHERIT:
1138 			ADD_CONFIG_TERM_VAL(INHERIT, inherit,
1139 					    term->val.num ? 1 : 0, term->weak);
1140 			break;
1141 		case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1142 			ADD_CONFIG_TERM_VAL(INHERIT, inherit,
1143 					    term->val.num ? 0 : 1, term->weak);
1144 			break;
1145 		case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1146 			ADD_CONFIG_TERM_VAL(MAX_STACK, max_stack,
1147 					    term->val.num, term->weak);
1148 			break;
1149 		case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
1150 			ADD_CONFIG_TERM_VAL(MAX_EVENTS, max_events,
1151 					    term->val.num, term->weak);
1152 			break;
1153 		case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1154 			ADD_CONFIG_TERM_VAL(OVERWRITE, overwrite,
1155 					    term->val.num ? 1 : 0, term->weak);
1156 			break;
1157 		case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1158 			ADD_CONFIG_TERM_VAL(OVERWRITE, overwrite,
1159 					    term->val.num ? 0 : 1, term->weak);
1160 			break;
1161 		case PARSE_EVENTS__TERM_TYPE_DRV_CFG:
1162 			ADD_CONFIG_TERM_STR(DRV_CFG, term->val.str, term->weak);
1163 			break;
1164 		case PARSE_EVENTS__TERM_TYPE_PERCORE:
1165 			ADD_CONFIG_TERM_VAL(PERCORE, percore,
1166 					    term->val.num ? true : false, term->weak);
1167 			break;
1168 		case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
1169 			ADD_CONFIG_TERM_VAL(AUX_OUTPUT, aux_output,
1170 					    term->val.num ? 1 : 0, term->weak);
1171 			break;
1172 		case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
1173 			ADD_CONFIG_TERM_VAL(AUX_SAMPLE_SIZE, aux_sample_size,
1174 					    term->val.num, term->weak);
1175 			break;
1176 		case PARSE_EVENTS__TERM_TYPE_USER:
1177 		case PARSE_EVENTS__TERM_TYPE_CONFIG:
1178 		case PARSE_EVENTS__TERM_TYPE_CONFIG1:
1179 		case PARSE_EVENTS__TERM_TYPE_CONFIG2:
1180 		case PARSE_EVENTS__TERM_TYPE_CONFIG3:
1181 		case PARSE_EVENTS__TERM_TYPE_NAME:
1182 		case PARSE_EVENTS__TERM_TYPE_METRIC_ID:
1183 		case PARSE_EVENTS__TERM_TYPE_RAW:
1184 		case PARSE_EVENTS__TERM_TYPE_LEGACY_CACHE:
1185 		case PARSE_EVENTS__TERM_TYPE_HARDWARE:
1186 		default:
1187 			break;
1188 		}
1189 	}
1190 	return 0;
1191 }
1192 
1193 /*
1194  * Add EVSEL__CONFIG_TERM_CFG_CHG where cfg_chg will have a bit set for
1195  * each bit of attr->config that the user has changed.
1196  */
get_config_chgs(struct perf_pmu * pmu,struct list_head * head_config,struct list_head * head_terms)1197 static int get_config_chgs(struct perf_pmu *pmu, struct list_head *head_config,
1198 			   struct list_head *head_terms)
1199 {
1200 	struct parse_events_term *term;
1201 	u64 bits = 0;
1202 	int type;
1203 
1204 	list_for_each_entry(term, head_config, list) {
1205 		switch (term->type_term) {
1206 		case PARSE_EVENTS__TERM_TYPE_USER:
1207 			type = perf_pmu__format_type(pmu, term->config);
1208 			if (type != PERF_PMU_FORMAT_VALUE_CONFIG)
1209 				continue;
1210 			bits |= perf_pmu__format_bits(pmu, term->config);
1211 			break;
1212 		case PARSE_EVENTS__TERM_TYPE_CONFIG:
1213 			bits = ~(u64)0;
1214 			break;
1215 		case PARSE_EVENTS__TERM_TYPE_CONFIG1:
1216 		case PARSE_EVENTS__TERM_TYPE_CONFIG2:
1217 		case PARSE_EVENTS__TERM_TYPE_CONFIG3:
1218 		case PARSE_EVENTS__TERM_TYPE_NAME:
1219 		case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
1220 		case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
1221 		case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
1222 		case PARSE_EVENTS__TERM_TYPE_TIME:
1223 		case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1224 		case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1225 		case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1226 		case PARSE_EVENTS__TERM_TYPE_INHERIT:
1227 		case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1228 		case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
1229 		case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1230 		case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1231 		case PARSE_EVENTS__TERM_TYPE_DRV_CFG:
1232 		case PARSE_EVENTS__TERM_TYPE_PERCORE:
1233 		case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
1234 		case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
1235 		case PARSE_EVENTS__TERM_TYPE_METRIC_ID:
1236 		case PARSE_EVENTS__TERM_TYPE_RAW:
1237 		case PARSE_EVENTS__TERM_TYPE_LEGACY_CACHE:
1238 		case PARSE_EVENTS__TERM_TYPE_HARDWARE:
1239 		default:
1240 			break;
1241 		}
1242 	}
1243 
1244 	if (bits)
1245 		ADD_CONFIG_TERM_VAL(CFG_CHG, cfg_chg, bits, false);
1246 
1247 #undef ADD_CONFIG_TERM
1248 	return 0;
1249 }
1250 
parse_events_add_tracepoint(struct list_head * list,int * idx,const char * sys,const char * event,struct parse_events_error * err,struct list_head * head_config,void * loc_)1251 int parse_events_add_tracepoint(struct list_head *list, int *idx,
1252 				const char *sys, const char *event,
1253 				struct parse_events_error *err,
1254 				struct list_head *head_config, void *loc_)
1255 {
1256 	YYLTYPE *loc = loc_;
1257 #ifdef HAVE_LIBTRACEEVENT
1258 	if (head_config) {
1259 		struct perf_event_attr attr;
1260 
1261 		if (config_attr(&attr, head_config, err,
1262 				config_term_tracepoint))
1263 			return -EINVAL;
1264 	}
1265 
1266 	if (strpbrk(sys, "*?"))
1267 		return add_tracepoint_multi_sys(list, idx, sys, event,
1268 						err, head_config, loc);
1269 	else
1270 		return add_tracepoint_event(list, idx, sys, event,
1271 					    err, head_config, loc);
1272 #else
1273 	(void)list;
1274 	(void)idx;
1275 	(void)sys;
1276 	(void)event;
1277 	(void)head_config;
1278 	parse_events_error__handle(err, loc->first_column, strdup("unsupported tracepoint"),
1279 				strdup("libtraceevent is necessary for tracepoint support"));
1280 	return -1;
1281 #endif
1282 }
1283 
__parse_events_add_numeric(struct parse_events_state * parse_state,struct list_head * list,struct perf_pmu * pmu,u32 type,u32 extended_type,u64 config,struct list_head * head_config)1284 static int __parse_events_add_numeric(struct parse_events_state *parse_state,
1285 				struct list_head *list,
1286 				struct perf_pmu *pmu, u32 type, u32 extended_type,
1287 				u64 config, struct list_head *head_config)
1288 {
1289 	struct perf_event_attr attr;
1290 	LIST_HEAD(config_terms);
1291 	const char *name, *metric_id;
1292 	int ret;
1293 
1294 	memset(&attr, 0, sizeof(attr));
1295 	attr.type = type;
1296 	attr.config = config;
1297 	if (extended_type && (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)) {
1298 		assert(perf_pmus__supports_extended_type());
1299 		attr.config |= (u64)extended_type << PERF_PMU_TYPE_SHIFT;
1300 	}
1301 
1302 	if (head_config) {
1303 		if (config_attr(&attr, head_config, parse_state->error,
1304 				config_term_common))
1305 			return -EINVAL;
1306 
1307 		if (get_config_terms(head_config, &config_terms))
1308 			return -ENOMEM;
1309 	}
1310 
1311 	name = get_config_name(head_config);
1312 	metric_id = get_config_metric_id(head_config);
1313 	ret = __add_event(list, &parse_state->idx, &attr, /*init_attr*/true, name,
1314 			metric_id, pmu, &config_terms, /*auto_merge_stats=*/false,
1315 			/*cpu_list=*/NULL) ? 0 : -ENOMEM;
1316 	free_config_terms(&config_terms);
1317 	return ret;
1318 }
1319 
parse_events_add_numeric(struct parse_events_state * parse_state,struct list_head * list,u32 type,u64 config,struct list_head * head_config,bool wildcard)1320 int parse_events_add_numeric(struct parse_events_state *parse_state,
1321 			     struct list_head *list,
1322 			     u32 type, u64 config,
1323 			     struct list_head *head_config,
1324 			     bool wildcard)
1325 {
1326 	struct perf_pmu *pmu = NULL;
1327 	bool found_supported = false;
1328 
1329 	/* Wildcards on numeric values are only supported by core PMUs. */
1330 	if (wildcard && perf_pmus__supports_extended_type()) {
1331 		while ((pmu = perf_pmus__scan_core(pmu)) != NULL) {
1332 			int ret;
1333 
1334 			found_supported = true;
1335 			if (parse_events__filter_pmu(parse_state, pmu))
1336 				continue;
1337 
1338 			ret = __parse_events_add_numeric(parse_state, list, pmu,
1339 							 type, pmu->type,
1340 							 config, head_config);
1341 			if (ret)
1342 				return ret;
1343 		}
1344 		if (found_supported)
1345 			return 0;
1346 	}
1347 	return __parse_events_add_numeric(parse_state, list, perf_pmus__find_by_type(type),
1348 					type, /*extended_type=*/0, config, head_config);
1349 }
1350 
parse_events_add_tool(struct parse_events_state * parse_state,struct list_head * list,int tool_event)1351 int parse_events_add_tool(struct parse_events_state *parse_state,
1352 			  struct list_head *list,
1353 			  int tool_event)
1354 {
1355 	return add_event_tool(list, &parse_state->idx, tool_event);
1356 }
1357 
config_term_percore(struct list_head * config_terms)1358 static bool config_term_percore(struct list_head *config_terms)
1359 {
1360 	struct evsel_config_term *term;
1361 
1362 	list_for_each_entry(term, config_terms, list) {
1363 		if (term->type == EVSEL__CONFIG_TERM_PERCORE)
1364 			return term->val.percore;
1365 	}
1366 
1367 	return false;
1368 }
1369 
parse_events_add_pmu(struct parse_events_state * parse_state,struct list_head * list,const char * name,struct list_head * head_config,bool auto_merge_stats,void * loc_)1370 int parse_events_add_pmu(struct parse_events_state *parse_state,
1371 			 struct list_head *list, const char *name,
1372 			 struct list_head *head_config,
1373 			 bool auto_merge_stats, void *loc_)
1374 {
1375 	struct perf_event_attr attr;
1376 	struct perf_pmu_info info;
1377 	struct perf_pmu *pmu;
1378 	struct evsel *evsel;
1379 	struct parse_events_error *err = parse_state->error;
1380 	YYLTYPE *loc = loc_;
1381 	LIST_HEAD(config_terms);
1382 
1383 	pmu = parse_state->fake_pmu ?: perf_pmus__find(name);
1384 
1385 	if (!pmu) {
1386 		char *err_str;
1387 
1388 		if (asprintf(&err_str,
1389 				"Cannot find PMU `%s'. Missing kernel support?",
1390 				name) >= 0)
1391 			parse_events_error__handle(err, loc->first_column, err_str, NULL);
1392 		return -EINVAL;
1393 	}
1394 
1395 	if (verbose > 1) {
1396 		struct strbuf sb;
1397 
1398 		strbuf_init(&sb, /*hint=*/ 0);
1399 		if (pmu->selectable && !head_config) {
1400 			strbuf_addf(&sb, "%s//", name);
1401 		} else {
1402 			strbuf_addf(&sb, "%s/", name);
1403 			parse_events_term__to_strbuf(head_config, &sb);
1404 			strbuf_addch(&sb, '/');
1405 		}
1406 		fprintf(stderr, "Attempt to add: %s\n", sb.buf);
1407 		strbuf_release(&sb);
1408 	}
1409 	if (head_config)
1410 		fix_raw(head_config, pmu);
1411 
1412 	if (pmu->default_config) {
1413 		memcpy(&attr, pmu->default_config,
1414 		       sizeof(struct perf_event_attr));
1415 	} else {
1416 		memset(&attr, 0, sizeof(attr));
1417 	}
1418 	attr.type = pmu->type;
1419 
1420 	if (!head_config) {
1421 		evsel = __add_event(list, &parse_state->idx, &attr,
1422 				    /*init_attr=*/true, /*name=*/NULL,
1423 				    /*metric_id=*/NULL, pmu,
1424 				    /*config_terms=*/NULL, auto_merge_stats,
1425 				    /*cpu_list=*/NULL);
1426 		return evsel ? 0 : -ENOMEM;
1427 	}
1428 
1429 	if (!parse_state->fake_pmu && perf_pmu__check_alias(pmu, head_config, &info, err))
1430 		return -EINVAL;
1431 
1432 	if (verbose > 1) {
1433 		struct strbuf sb;
1434 
1435 		strbuf_init(&sb, /*hint=*/ 0);
1436 		parse_events_term__to_strbuf(head_config, &sb);
1437 		fprintf(stderr, "..after resolving event: %s/%s/\n", name, sb.buf);
1438 		strbuf_release(&sb);
1439 	}
1440 
1441 	/*
1442 	 * Configure hardcoded terms first, no need to check
1443 	 * return value when called with fail == 0 ;)
1444 	 */
1445 	if (config_attr(&attr, head_config, parse_state->error, config_term_pmu))
1446 		return -EINVAL;
1447 
1448 	if (get_config_terms(head_config, &config_terms))
1449 		return -ENOMEM;
1450 
1451 	/*
1452 	 * When using default config, record which bits of attr->config were
1453 	 * changed by the user.
1454 	 */
1455 	if (pmu->default_config && get_config_chgs(pmu, head_config, &config_terms))
1456 		return -ENOMEM;
1457 
1458 	if (!parse_state->fake_pmu && perf_pmu__config(pmu, &attr, head_config, parse_state->error)) {
1459 		free_config_terms(&config_terms);
1460 		return -EINVAL;
1461 	}
1462 
1463 	evsel = __add_event(list, &parse_state->idx, &attr, /*init_attr=*/true,
1464 			    get_config_name(head_config),
1465 			    get_config_metric_id(head_config), pmu,
1466 			    &config_terms, auto_merge_stats, /*cpu_list=*/NULL);
1467 	if (!evsel)
1468 		return -ENOMEM;
1469 
1470 	if (evsel->name)
1471 		evsel->use_config_name = true;
1472 
1473 	evsel->percore = config_term_percore(&evsel->config_terms);
1474 
1475 	if (parse_state->fake_pmu)
1476 		return 0;
1477 
1478 	free((char *)evsel->unit);
1479 	evsel->unit = strdup(info.unit);
1480 	evsel->scale = info.scale;
1481 	evsel->per_pkg = info.per_pkg;
1482 	evsel->snapshot = info.snapshot;
1483 	return 0;
1484 }
1485 
parse_events_multi_pmu_add(struct parse_events_state * parse_state,char * str,struct list_head * head,struct list_head ** listp,void * loc_)1486 int parse_events_multi_pmu_add(struct parse_events_state *parse_state,
1487 			       char *str, struct list_head *head,
1488 			       struct list_head **listp, void *loc_)
1489 {
1490 	struct parse_events_term *term;
1491 	struct list_head *list = NULL;
1492 	struct list_head *orig_head = NULL;
1493 	struct perf_pmu *pmu = NULL;
1494 	YYLTYPE *loc = loc_;
1495 	int ok = 0;
1496 	const char *config;
1497 
1498 	*listp = NULL;
1499 
1500 	if (!head) {
1501 		head = malloc(sizeof(struct list_head));
1502 		if (!head)
1503 			goto out_err;
1504 
1505 		INIT_LIST_HEAD(head);
1506 	}
1507 	config = strdup(str);
1508 	if (!config)
1509 		goto out_err;
1510 
1511 	if (parse_events_term__num(&term,
1512 				   PARSE_EVENTS__TERM_TYPE_USER,
1513 				   config, /*num=*/1, /*novalue=*/true,
1514 				   loc, /*loc_val=*/NULL) < 0) {
1515 		zfree(&config);
1516 		goto out_err;
1517 	}
1518 	list_add_tail(&term->list, head);
1519 
1520 	/* Add it for all PMUs that support the alias */
1521 	list = malloc(sizeof(struct list_head));
1522 	if (!list)
1523 		goto out_err;
1524 
1525 	INIT_LIST_HEAD(list);
1526 
1527 	while ((pmu = perf_pmus__scan(pmu)) != NULL) {
1528 		bool auto_merge_stats;
1529 
1530 		if (parse_events__filter_pmu(parse_state, pmu))
1531 			continue;
1532 
1533 		if (!perf_pmu__have_event(pmu, str))
1534 			continue;
1535 
1536 		auto_merge_stats = perf_pmu__auto_merge_stats(pmu);
1537 		parse_events_copy_term_list(head, &orig_head);
1538 		if (!parse_events_add_pmu(parse_state, list, pmu->name,
1539 					  orig_head, auto_merge_stats, loc)) {
1540 			struct strbuf sb;
1541 
1542 			strbuf_init(&sb, /*hint=*/ 0);
1543 			parse_events_term__to_strbuf(orig_head, &sb);
1544 			pr_debug("%s -> %s/%s/\n", str, pmu->name, sb.buf);
1545 			strbuf_release(&sb);
1546 			ok++;
1547 		}
1548 		parse_events_terms__delete(orig_head);
1549 	}
1550 
1551 	if (parse_state->fake_pmu) {
1552 		if (!parse_events_add_pmu(parse_state, list, str, head,
1553 					  /*auto_merge_stats=*/true, loc)) {
1554 			struct strbuf sb;
1555 
1556 			strbuf_init(&sb, /*hint=*/ 0);
1557 			parse_events_term__to_strbuf(head, &sb);
1558 			pr_debug("%s -> %s/%s/\n", str, "fake_pmu", sb.buf);
1559 			strbuf_release(&sb);
1560 			ok++;
1561 		}
1562 	}
1563 
1564 out_err:
1565 	if (ok)
1566 		*listp = list;
1567 	else
1568 		free(list);
1569 
1570 	parse_events_terms__delete(head);
1571 	return ok ? 0 : -1;
1572 }
1573 
parse_events__modifier_group(struct list_head * list,char * event_mod)1574 int parse_events__modifier_group(struct list_head *list,
1575 				 char *event_mod)
1576 {
1577 	return parse_events__modifier_event(list, event_mod, true);
1578 }
1579 
parse_events__set_leader(char * name,struct list_head * list)1580 void parse_events__set_leader(char *name, struct list_head *list)
1581 {
1582 	struct evsel *leader;
1583 
1584 	if (list_empty(list)) {
1585 		WARN_ONCE(true, "WARNING: failed to set leader: empty list");
1586 		return;
1587 	}
1588 
1589 	leader = list_first_entry(list, struct evsel, core.node);
1590 	__perf_evlist__set_leader(list, &leader->core);
1591 	leader->group_name = name;
1592 }
1593 
1594 /* list_event is assumed to point to malloc'ed memory */
parse_events_update_lists(struct list_head * list_event,struct list_head * list_all)1595 void parse_events_update_lists(struct list_head *list_event,
1596 			       struct list_head *list_all)
1597 {
1598 	/*
1599 	 * Called for single event definition. Update the
1600 	 * 'all event' list, and reinit the 'single event'
1601 	 * list, for next event definition.
1602 	 */
1603 	list_splice_tail(list_event, list_all);
1604 	free(list_event);
1605 }
1606 
1607 struct event_modifier {
1608 	int eu;
1609 	int ek;
1610 	int eh;
1611 	int eH;
1612 	int eG;
1613 	int eI;
1614 	int precise;
1615 	int precise_max;
1616 	int exclude_GH;
1617 	int sample_read;
1618 	int pinned;
1619 	int weak;
1620 	int exclusive;
1621 	int bpf_counter;
1622 };
1623 
get_event_modifier(struct event_modifier * mod,char * str,struct evsel * evsel)1624 static int get_event_modifier(struct event_modifier *mod, char *str,
1625 			       struct evsel *evsel)
1626 {
1627 	int eu = evsel ? evsel->core.attr.exclude_user : 0;
1628 	int ek = evsel ? evsel->core.attr.exclude_kernel : 0;
1629 	int eh = evsel ? evsel->core.attr.exclude_hv : 0;
1630 	int eH = evsel ? evsel->core.attr.exclude_host : 0;
1631 	int eG = evsel ? evsel->core.attr.exclude_guest : 0;
1632 	int eI = evsel ? evsel->core.attr.exclude_idle : 0;
1633 	int precise = evsel ? evsel->core.attr.precise_ip : 0;
1634 	int precise_max = 0;
1635 	int sample_read = 0;
1636 	int pinned = evsel ? evsel->core.attr.pinned : 0;
1637 	int exclusive = evsel ? evsel->core.attr.exclusive : 0;
1638 
1639 	int exclude = eu | ek | eh;
1640 	int exclude_GH = evsel ? evsel->exclude_GH : 0;
1641 	int weak = 0;
1642 	int bpf_counter = 0;
1643 
1644 	memset(mod, 0, sizeof(*mod));
1645 
1646 	while (*str) {
1647 		if (*str == 'u') {
1648 			if (!exclude)
1649 				exclude = eu = ek = eh = 1;
1650 			if (!exclude_GH && !perf_guest)
1651 				eG = 1;
1652 			eu = 0;
1653 		} else if (*str == 'k') {
1654 			if (!exclude)
1655 				exclude = eu = ek = eh = 1;
1656 			ek = 0;
1657 		} else if (*str == 'h') {
1658 			if (!exclude)
1659 				exclude = eu = ek = eh = 1;
1660 			eh = 0;
1661 		} else if (*str == 'G') {
1662 			if (!exclude_GH)
1663 				exclude_GH = eG = eH = 1;
1664 			eG = 0;
1665 		} else if (*str == 'H') {
1666 			if (!exclude_GH)
1667 				exclude_GH = eG = eH = 1;
1668 			eH = 0;
1669 		} else if (*str == 'I') {
1670 			eI = 1;
1671 		} else if (*str == 'p') {
1672 			precise++;
1673 			/* use of precise requires exclude_guest */
1674 			if (!exclude_GH)
1675 				eG = 1;
1676 		} else if (*str == 'P') {
1677 			precise_max = 1;
1678 		} else if (*str == 'S') {
1679 			sample_read = 1;
1680 		} else if (*str == 'D') {
1681 			pinned = 1;
1682 		} else if (*str == 'e') {
1683 			exclusive = 1;
1684 		} else if (*str == 'W') {
1685 			weak = 1;
1686 		} else if (*str == 'b') {
1687 			bpf_counter = 1;
1688 		} else
1689 			break;
1690 
1691 		++str;
1692 	}
1693 
1694 	/*
1695 	 * precise ip:
1696 	 *
1697 	 *  0 - SAMPLE_IP can have arbitrary skid
1698 	 *  1 - SAMPLE_IP must have constant skid
1699 	 *  2 - SAMPLE_IP requested to have 0 skid
1700 	 *  3 - SAMPLE_IP must have 0 skid
1701 	 *
1702 	 *  See also PERF_RECORD_MISC_EXACT_IP
1703 	 */
1704 	if (precise > 3)
1705 		return -EINVAL;
1706 
1707 	mod->eu = eu;
1708 	mod->ek = ek;
1709 	mod->eh = eh;
1710 	mod->eH = eH;
1711 	mod->eG = eG;
1712 	mod->eI = eI;
1713 	mod->precise = precise;
1714 	mod->precise_max = precise_max;
1715 	mod->exclude_GH = exclude_GH;
1716 	mod->sample_read = sample_read;
1717 	mod->pinned = pinned;
1718 	mod->weak = weak;
1719 	mod->bpf_counter = bpf_counter;
1720 	mod->exclusive = exclusive;
1721 
1722 	return 0;
1723 }
1724 
1725 /*
1726  * Basic modifier sanity check to validate it contains only one
1727  * instance of any modifier (apart from 'p') present.
1728  */
check_modifier(char * str)1729 static int check_modifier(char *str)
1730 {
1731 	char *p = str;
1732 
1733 	/* The sizeof includes 0 byte as well. */
1734 	if (strlen(str) > (sizeof("ukhGHpppPSDIWeb") - 1))
1735 		return -1;
1736 
1737 	while (*p) {
1738 		if (*p != 'p' && strchr(p + 1, *p))
1739 			return -1;
1740 		p++;
1741 	}
1742 
1743 	return 0;
1744 }
1745 
parse_events__modifier_event(struct list_head * list,char * str,bool add)1746 int parse_events__modifier_event(struct list_head *list, char *str, bool add)
1747 {
1748 	struct evsel *evsel;
1749 	struct event_modifier mod;
1750 
1751 	if (str == NULL)
1752 		return 0;
1753 
1754 	if (check_modifier(str))
1755 		return -EINVAL;
1756 
1757 	if (!add && get_event_modifier(&mod, str, NULL))
1758 		return -EINVAL;
1759 
1760 	__evlist__for_each_entry(list, evsel) {
1761 		if (add && get_event_modifier(&mod, str, evsel))
1762 			return -EINVAL;
1763 
1764 		evsel->core.attr.exclude_user   = mod.eu;
1765 		evsel->core.attr.exclude_kernel = mod.ek;
1766 		evsel->core.attr.exclude_hv     = mod.eh;
1767 		evsel->core.attr.precise_ip     = mod.precise;
1768 		evsel->core.attr.exclude_host   = mod.eH;
1769 		evsel->core.attr.exclude_guest  = mod.eG;
1770 		evsel->core.attr.exclude_idle   = mod.eI;
1771 		evsel->exclude_GH          = mod.exclude_GH;
1772 		evsel->sample_read         = mod.sample_read;
1773 		evsel->precise_max         = mod.precise_max;
1774 		evsel->weak_group	   = mod.weak;
1775 		evsel->bpf_counter	   = mod.bpf_counter;
1776 
1777 		if (evsel__is_group_leader(evsel)) {
1778 			evsel->core.attr.pinned = mod.pinned;
1779 			evsel->core.attr.exclusive = mod.exclusive;
1780 		}
1781 	}
1782 
1783 	return 0;
1784 }
1785 
parse_events_name(struct list_head * list,const char * name)1786 int parse_events_name(struct list_head *list, const char *name)
1787 {
1788 	struct evsel *evsel;
1789 
1790 	__evlist__for_each_entry(list, evsel) {
1791 		if (!evsel->name) {
1792 			evsel->name = strdup(name);
1793 			if (!evsel->name)
1794 				return -ENOMEM;
1795 		}
1796 	}
1797 
1798 	return 0;
1799 }
1800 
parse_events__scanner(const char * str,FILE * input,struct parse_events_state * parse_state)1801 static int parse_events__scanner(const char *str,
1802 				 FILE *input,
1803 				 struct parse_events_state *parse_state)
1804 {
1805 	YY_BUFFER_STATE buffer;
1806 	void *scanner;
1807 	int ret;
1808 
1809 	ret = parse_events_lex_init_extra(parse_state, &scanner);
1810 	if (ret)
1811 		return ret;
1812 
1813 	if (str)
1814 		buffer = parse_events__scan_string(str, scanner);
1815 	else
1816 	        parse_events_set_in(input, scanner);
1817 
1818 #ifdef PARSER_DEBUG
1819 	parse_events_debug = 1;
1820 	parse_events_set_debug(1, scanner);
1821 #endif
1822 	ret = parse_events_parse(parse_state, scanner);
1823 
1824 	if (str) {
1825 		parse_events__flush_buffer(buffer, scanner);
1826 		parse_events__delete_buffer(buffer, scanner);
1827 	}
1828 	parse_events_lex_destroy(scanner);
1829 	return ret;
1830 }
1831 
1832 /*
1833  * parse event config string, return a list of event terms.
1834  */
parse_events_terms(struct list_head * terms,const char * str,FILE * input)1835 int parse_events_terms(struct list_head *terms, const char *str, FILE *input)
1836 {
1837 	struct parse_events_state parse_state = {
1838 		.terms  = NULL,
1839 		.stoken = PE_START_TERMS,
1840 	};
1841 	int ret;
1842 
1843 	ret = parse_events__scanner(str, input, &parse_state);
1844 
1845 	if (!ret) {
1846 		list_splice(parse_state.terms, terms);
1847 		zfree(&parse_state.terms);
1848 		return 0;
1849 	}
1850 
1851 	parse_events_terms__delete(parse_state.terms);
1852 	return ret;
1853 }
1854 
evsel__compute_group_pmu_name(struct evsel * evsel,const struct list_head * head)1855 static int evsel__compute_group_pmu_name(struct evsel *evsel,
1856 					  const struct list_head *head)
1857 {
1858 	struct evsel *leader = evsel__leader(evsel);
1859 	struct evsel *pos;
1860 	const char *group_pmu_name;
1861 	struct perf_pmu *pmu = evsel__find_pmu(evsel);
1862 
1863 	if (!pmu) {
1864 		/*
1865 		 * For PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE types the PMU
1866 		 * is a core PMU, but in heterogeneous systems this is
1867 		 * unknown. For now pick the first core PMU.
1868 		 */
1869 		pmu = perf_pmus__scan_core(NULL);
1870 	}
1871 	if (!pmu) {
1872 		pr_debug("No PMU found for '%s'\n", evsel__name(evsel));
1873 		return -EINVAL;
1874 	}
1875 	group_pmu_name = pmu->name;
1876 	/*
1877 	 * Software events may be in a group with other uncore PMU events. Use
1878 	 * the pmu_name of the first non-software event to avoid breaking the
1879 	 * software event out of the group.
1880 	 *
1881 	 * Aux event leaders, like intel_pt, expect a group with events from
1882 	 * other PMUs, so substitute the AUX event's PMU in this case.
1883 	 */
1884 	if (perf_pmu__is_software(pmu) || evsel__is_aux_event(leader)) {
1885 		struct perf_pmu *leader_pmu = evsel__find_pmu(leader);
1886 
1887 		if (!leader_pmu) {
1888 			/* As with determining pmu above. */
1889 			leader_pmu = perf_pmus__scan_core(NULL);
1890 		}
1891 		/*
1892 		 * Starting with the leader, find the first event with a named
1893 		 * non-software PMU. for_each_group_(member|evsel) isn't used as
1894 		 * the list isn't yet sorted putting evsel's in the same group
1895 		 * together.
1896 		 */
1897 		if (leader_pmu && !perf_pmu__is_software(leader_pmu)) {
1898 			group_pmu_name = leader_pmu->name;
1899 		} else if (leader->core.nr_members > 1) {
1900 			list_for_each_entry(pos, head, core.node) {
1901 				struct perf_pmu *pos_pmu;
1902 
1903 				if (pos == leader || evsel__leader(pos) != leader)
1904 					continue;
1905 				pos_pmu = evsel__find_pmu(pos);
1906 				if (!pos_pmu) {
1907 					/* As with determining pmu above. */
1908 					pos_pmu = perf_pmus__scan_core(NULL);
1909 				}
1910 				if (pos_pmu && !perf_pmu__is_software(pos_pmu)) {
1911 					group_pmu_name = pos_pmu->name;
1912 					break;
1913 				}
1914 			}
1915 		}
1916 	}
1917 	/* Assign the actual name taking care that the fake PMU lacks a name. */
1918 	evsel->group_pmu_name = strdup(group_pmu_name ?: "fake");
1919 	return evsel->group_pmu_name ? 0 : -ENOMEM;
1920 }
1921 
arch_evlist__cmp(const struct evsel * lhs,const struct evsel * rhs)1922 __weak int arch_evlist__cmp(const struct evsel *lhs, const struct evsel *rhs)
1923 {
1924 	/* Order by insertion index. */
1925 	return lhs->core.idx - rhs->core.idx;
1926 }
1927 
evlist__cmp(void * _fg_idx,const struct list_head * l,const struct list_head * r)1928 static int evlist__cmp(void *_fg_idx, const struct list_head *l, const struct list_head *r)
1929 {
1930 	const struct perf_evsel *lhs_core = container_of(l, struct perf_evsel, node);
1931 	const struct evsel *lhs = container_of(lhs_core, struct evsel, core);
1932 	const struct perf_evsel *rhs_core = container_of(r, struct perf_evsel, node);
1933 	const struct evsel *rhs = container_of(rhs_core, struct evsel, core);
1934 	int *force_grouped_idx = _fg_idx;
1935 	int lhs_sort_idx, rhs_sort_idx, ret;
1936 	const char *lhs_pmu_name, *rhs_pmu_name;
1937 	bool lhs_has_group, rhs_has_group;
1938 
1939 	/*
1940 	 * First sort by grouping/leader. Read the leader idx only if the evsel
1941 	 * is part of a group, by default ungrouped events will be sorted
1942 	 * relative to grouped events based on where the first ungrouped event
1943 	 * occurs. If both events don't have a group we want to fall-through to
1944 	 * the arch specific sorting, that can reorder and fix things like
1945 	 * Intel's topdown events.
1946 	 */
1947 	if (lhs_core->leader != lhs_core || lhs_core->nr_members > 1) {
1948 		lhs_has_group = true;
1949 		lhs_sort_idx = lhs_core->leader->idx;
1950 	} else {
1951 		lhs_has_group = false;
1952 		lhs_sort_idx = *force_grouped_idx != -1 && arch_evsel__must_be_in_group(lhs)
1953 			? *force_grouped_idx
1954 			: lhs_core->idx;
1955 	}
1956 	if (rhs_core->leader != rhs_core || rhs_core->nr_members > 1) {
1957 		rhs_has_group = true;
1958 		rhs_sort_idx = rhs_core->leader->idx;
1959 	} else {
1960 		rhs_has_group = false;
1961 		rhs_sort_idx = *force_grouped_idx != -1 && arch_evsel__must_be_in_group(rhs)
1962 			? *force_grouped_idx
1963 			: rhs_core->idx;
1964 	}
1965 
1966 	if (lhs_sort_idx != rhs_sort_idx)
1967 		return lhs_sort_idx - rhs_sort_idx;
1968 
1969 	/* Group by PMU if there is a group. Groups can't span PMUs. */
1970 	if (lhs_has_group && rhs_has_group) {
1971 		lhs_pmu_name = lhs->group_pmu_name;
1972 		rhs_pmu_name = rhs->group_pmu_name;
1973 		ret = strcmp(lhs_pmu_name, rhs_pmu_name);
1974 		if (ret)
1975 			return ret;
1976 	}
1977 
1978 	/* Architecture specific sorting. */
1979 	return arch_evlist__cmp(lhs, rhs);
1980 }
1981 
parse_events__sort_events_and_fix_groups(struct list_head * list)1982 static int parse_events__sort_events_and_fix_groups(struct list_head *list)
1983 {
1984 	int idx = 0, force_grouped_idx = -1;
1985 	struct evsel *pos, *cur_leader = NULL;
1986 	struct perf_evsel *cur_leaders_grp = NULL;
1987 	bool idx_changed = false, cur_leader_force_grouped = false;
1988 	int orig_num_leaders = 0, num_leaders = 0;
1989 	int ret;
1990 
1991 	/*
1992 	 * Compute index to insert ungrouped events at. Place them where the
1993 	 * first ungrouped event appears.
1994 	 */
1995 	list_for_each_entry(pos, list, core.node) {
1996 		const struct evsel *pos_leader = evsel__leader(pos);
1997 
1998 		ret = evsel__compute_group_pmu_name(pos, list);
1999 		if (ret)
2000 			return ret;
2001 
2002 		if (pos == pos_leader)
2003 			orig_num_leaders++;
2004 
2005 		/*
2006 		 * Ensure indexes are sequential, in particular for multiple
2007 		 * event lists being merged. The indexes are used to detect when
2008 		 * the user order is modified.
2009 		 */
2010 		pos->core.idx = idx++;
2011 
2012 		/* Remember an index to sort all forced grouped events together to. */
2013 		if (force_grouped_idx == -1 && pos == pos_leader && pos->core.nr_members < 2 &&
2014 		    arch_evsel__must_be_in_group(pos))
2015 			force_grouped_idx = pos->core.idx;
2016 	}
2017 
2018 	/* Sort events. */
2019 	list_sort(&force_grouped_idx, list, evlist__cmp);
2020 
2021 	/*
2022 	 * Recompute groups, splitting for PMUs and adding groups for events
2023 	 * that require them.
2024 	 */
2025 	idx = 0;
2026 	list_for_each_entry(pos, list, core.node) {
2027 		const struct evsel *pos_leader = evsel__leader(pos);
2028 		const char *pos_pmu_name = pos->group_pmu_name;
2029 		const char *cur_leader_pmu_name;
2030 		bool pos_force_grouped = force_grouped_idx != -1 &&
2031 			arch_evsel__must_be_in_group(pos);
2032 
2033 		/* Reset index and nr_members. */
2034 		if (pos->core.idx != idx)
2035 			idx_changed = true;
2036 		pos->core.idx = idx++;
2037 		pos->core.nr_members = 0;
2038 
2039 		/*
2040 		 * Set the group leader respecting the given groupings and that
2041 		 * groups can't span PMUs.
2042 		 */
2043 		if (!cur_leader)
2044 			cur_leader = pos;
2045 
2046 		cur_leader_pmu_name = cur_leader->group_pmu_name;
2047 		if ((cur_leaders_grp != pos->core.leader &&
2048 		     (!pos_force_grouped || !cur_leader_force_grouped)) ||
2049 		    strcmp(cur_leader_pmu_name, pos_pmu_name)) {
2050 			/* Event is for a different group/PMU than last. */
2051 			cur_leader = pos;
2052 			/*
2053 			 * Remember the leader's group before it is overwritten,
2054 			 * so that later events match as being in the same
2055 			 * group.
2056 			 */
2057 			cur_leaders_grp = pos->core.leader;
2058 			/*
2059 			 * Avoid forcing events into groups with events that
2060 			 * don't need to be in the group.
2061 			 */
2062 			cur_leader_force_grouped = pos_force_grouped;
2063 		}
2064 		if (pos_leader != cur_leader) {
2065 			/* The leader changed so update it. */
2066 			evsel__set_leader(pos, cur_leader);
2067 		}
2068 	}
2069 	list_for_each_entry(pos, list, core.node) {
2070 		struct evsel *pos_leader = evsel__leader(pos);
2071 
2072 		if (pos == pos_leader)
2073 			num_leaders++;
2074 		pos_leader->core.nr_members++;
2075 	}
2076 	return (idx_changed || num_leaders != orig_num_leaders) ? 1 : 0;
2077 }
2078 
__parse_events(struct evlist * evlist,const char * str,const char * pmu_filter,struct parse_events_error * err,struct perf_pmu * fake_pmu,bool warn_if_reordered)2079 int __parse_events(struct evlist *evlist, const char *str, const char *pmu_filter,
2080 		   struct parse_events_error *err, struct perf_pmu *fake_pmu,
2081 		   bool warn_if_reordered)
2082 {
2083 	struct parse_events_state parse_state = {
2084 		.list	  = LIST_HEAD_INIT(parse_state.list),
2085 		.idx	  = evlist->core.nr_entries,
2086 		.error	  = err,
2087 		.stoken	  = PE_START_EVENTS,
2088 		.fake_pmu = fake_pmu,
2089 		.pmu_filter = pmu_filter,
2090 		.match_legacy_cache_terms = true,
2091 	};
2092 	int ret, ret2;
2093 
2094 	ret = parse_events__scanner(str, /*input=*/ NULL, &parse_state);
2095 
2096 	if (!ret && list_empty(&parse_state.list)) {
2097 		WARN_ONCE(true, "WARNING: event parser found nothing\n");
2098 		return -1;
2099 	}
2100 
2101 	ret2 = parse_events__sort_events_and_fix_groups(&parse_state.list);
2102 	if (ret2 < 0)
2103 		return ret;
2104 
2105 	if (ret2 && warn_if_reordered && !parse_state.wild_card_pmus)
2106 		pr_warning("WARNING: events were regrouped to match PMUs\n");
2107 
2108 	/*
2109 	 * Add list to the evlist even with errors to allow callers to clean up.
2110 	 */
2111 	evlist__splice_list_tail(evlist, &parse_state.list);
2112 
2113 	if (!ret) {
2114 		struct evsel *last;
2115 
2116 		last = evlist__last(evlist);
2117 		last->cmdline_group_boundary = true;
2118 
2119 		return 0;
2120 	}
2121 
2122 	/*
2123 	 * There are 2 users - builtin-record and builtin-test objects.
2124 	 * Both call evlist__delete in case of error, so we dont
2125 	 * need to bother.
2126 	 */
2127 	return ret;
2128 }
2129 
parse_event(struct evlist * evlist,const char * str)2130 int parse_event(struct evlist *evlist, const char *str)
2131 {
2132 	struct parse_events_error err;
2133 	int ret;
2134 
2135 	parse_events_error__init(&err);
2136 	ret = parse_events(evlist, str, &err);
2137 	parse_events_error__exit(&err);
2138 	return ret;
2139 }
2140 
parse_events_error__init(struct parse_events_error * err)2141 void parse_events_error__init(struct parse_events_error *err)
2142 {
2143 	bzero(err, sizeof(*err));
2144 }
2145 
parse_events_error__exit(struct parse_events_error * err)2146 void parse_events_error__exit(struct parse_events_error *err)
2147 {
2148 	zfree(&err->str);
2149 	zfree(&err->help);
2150 	zfree(&err->first_str);
2151 	zfree(&err->first_help);
2152 }
2153 
parse_events_error__handle(struct parse_events_error * err,int idx,char * str,char * help)2154 void parse_events_error__handle(struct parse_events_error *err, int idx,
2155 				char *str, char *help)
2156 {
2157 	if (WARN(!str || !err, "WARNING: failed to provide error string or struct\n"))
2158 		goto out_free;
2159 	switch (err->num_errors) {
2160 	case 0:
2161 		err->idx = idx;
2162 		err->str = str;
2163 		err->help = help;
2164 		break;
2165 	case 1:
2166 		err->first_idx = err->idx;
2167 		err->idx = idx;
2168 		err->first_str = err->str;
2169 		err->str = str;
2170 		err->first_help = err->help;
2171 		err->help = help;
2172 		break;
2173 	default:
2174 		pr_debug("Multiple errors dropping message: %s (%s)\n",
2175 			err->str, err->help ?: "<no help>");
2176 		free(err->str);
2177 		err->str = str;
2178 		free(err->help);
2179 		err->help = help;
2180 		break;
2181 	}
2182 	err->num_errors++;
2183 	return;
2184 
2185 out_free:
2186 	free(str);
2187 	free(help);
2188 }
2189 
2190 #define MAX_WIDTH 1000
get_term_width(void)2191 static int get_term_width(void)
2192 {
2193 	struct winsize ws;
2194 
2195 	get_term_dimensions(&ws);
2196 	return ws.ws_col > MAX_WIDTH ? MAX_WIDTH : ws.ws_col;
2197 }
2198 
__parse_events_error__print(int err_idx,const char * err_str,const char * err_help,const char * event)2199 static void __parse_events_error__print(int err_idx, const char *err_str,
2200 					const char *err_help, const char *event)
2201 {
2202 	const char *str = "invalid or unsupported event: ";
2203 	char _buf[MAX_WIDTH];
2204 	char *buf = (char *) event;
2205 	int idx = 0;
2206 	if (err_str) {
2207 		/* -2 for extra '' in the final fprintf */
2208 		int width       = get_term_width() - 2;
2209 		int len_event   = strlen(event);
2210 		int len_str, max_len, cut = 0;
2211 
2212 		/*
2213 		 * Maximum error index indent, we will cut
2214 		 * the event string if it's bigger.
2215 		 */
2216 		int max_err_idx = 13;
2217 
2218 		/*
2219 		 * Let's be specific with the message when
2220 		 * we have the precise error.
2221 		 */
2222 		str     = "event syntax error: ";
2223 		len_str = strlen(str);
2224 		max_len = width - len_str;
2225 
2226 		buf = _buf;
2227 
2228 		/* We're cutting from the beginning. */
2229 		if (err_idx > max_err_idx)
2230 			cut = err_idx - max_err_idx;
2231 
2232 		strncpy(buf, event + cut, max_len);
2233 
2234 		/* Mark cut parts with '..' on both sides. */
2235 		if (cut)
2236 			buf[0] = buf[1] = '.';
2237 
2238 		if ((len_event - cut) > max_len) {
2239 			buf[max_len - 1] = buf[max_len - 2] = '.';
2240 			buf[max_len] = 0;
2241 		}
2242 
2243 		idx = len_str + err_idx - cut;
2244 	}
2245 
2246 	fprintf(stderr, "%s'%s'\n", str, buf);
2247 	if (idx) {
2248 		fprintf(stderr, "%*s\\___ %s\n", idx + 1, "", err_str);
2249 		if (err_help)
2250 			fprintf(stderr, "\n%s\n", err_help);
2251 	}
2252 }
2253 
parse_events_error__print(struct parse_events_error * err,const char * event)2254 void parse_events_error__print(struct parse_events_error *err,
2255 			       const char *event)
2256 {
2257 	if (!err->num_errors)
2258 		return;
2259 
2260 	__parse_events_error__print(err->idx, err->str, err->help, event);
2261 
2262 	if (err->num_errors > 1) {
2263 		fputs("\nInitial error:\n", stderr);
2264 		__parse_events_error__print(err->first_idx, err->first_str,
2265 					err->first_help, event);
2266 	}
2267 }
2268 
2269 #undef MAX_WIDTH
2270 
parse_events_option(const struct option * opt,const char * str,int unset __maybe_unused)2271 int parse_events_option(const struct option *opt, const char *str,
2272 			int unset __maybe_unused)
2273 {
2274 	struct parse_events_option_args *args = opt->value;
2275 	struct parse_events_error err;
2276 	int ret;
2277 
2278 	parse_events_error__init(&err);
2279 	ret = __parse_events(*args->evlistp, str, args->pmu_filter, &err,
2280 			     /*fake_pmu=*/NULL, /*warn_if_reordered=*/true);
2281 
2282 	if (ret) {
2283 		parse_events_error__print(&err, str);
2284 		fprintf(stderr, "Run 'perf list' for a list of valid events\n");
2285 	}
2286 	parse_events_error__exit(&err);
2287 
2288 	return ret;
2289 }
2290 
parse_events_option_new_evlist(const struct option * opt,const char * str,int unset)2291 int parse_events_option_new_evlist(const struct option *opt, const char *str, int unset)
2292 {
2293 	struct parse_events_option_args *args = opt->value;
2294 	int ret;
2295 
2296 	if (*args->evlistp == NULL) {
2297 		*args->evlistp = evlist__new();
2298 
2299 		if (*args->evlistp == NULL) {
2300 			fprintf(stderr, "Not enough memory to create evlist\n");
2301 			return -1;
2302 		}
2303 	}
2304 	ret = parse_events_option(opt, str, unset);
2305 	if (ret) {
2306 		evlist__delete(*args->evlistp);
2307 		*args->evlistp = NULL;
2308 	}
2309 
2310 	return ret;
2311 }
2312 
2313 static int
foreach_evsel_in_last_glob(struct evlist * evlist,int (* func)(struct evsel * evsel,const void * arg),const void * arg)2314 foreach_evsel_in_last_glob(struct evlist *evlist,
2315 			   int (*func)(struct evsel *evsel,
2316 				       const void *arg),
2317 			   const void *arg)
2318 {
2319 	struct evsel *last = NULL;
2320 	int err;
2321 
2322 	/*
2323 	 * Don't return when list_empty, give func a chance to report
2324 	 * error when it found last == NULL.
2325 	 *
2326 	 * So no need to WARN here, let *func do this.
2327 	 */
2328 	if (evlist->core.nr_entries > 0)
2329 		last = evlist__last(evlist);
2330 
2331 	do {
2332 		err = (*func)(last, arg);
2333 		if (err)
2334 			return -1;
2335 		if (!last)
2336 			return 0;
2337 
2338 		if (last->core.node.prev == &evlist->core.entries)
2339 			return 0;
2340 		last = list_entry(last->core.node.prev, struct evsel, core.node);
2341 	} while (!last->cmdline_group_boundary);
2342 
2343 	return 0;
2344 }
2345 
set_filter(struct evsel * evsel,const void * arg)2346 static int set_filter(struct evsel *evsel, const void *arg)
2347 {
2348 	const char *str = arg;
2349 	bool found = false;
2350 	int nr_addr_filters = 0;
2351 	struct perf_pmu *pmu = NULL;
2352 
2353 	if (evsel == NULL) {
2354 		fprintf(stderr,
2355 			"--filter option should follow a -e tracepoint or HW tracer option\n");
2356 		return -1;
2357 	}
2358 
2359 	if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT) {
2360 		if (evsel__append_tp_filter(evsel, str) < 0) {
2361 			fprintf(stderr,
2362 				"not enough memory to hold filter string\n");
2363 			return -1;
2364 		}
2365 
2366 		return 0;
2367 	}
2368 
2369 	while ((pmu = perf_pmus__scan(pmu)) != NULL)
2370 		if (pmu->type == evsel->core.attr.type) {
2371 			found = true;
2372 			break;
2373 		}
2374 
2375 	if (found)
2376 		perf_pmu__scan_file(pmu, "nr_addr_filters",
2377 				    "%d", &nr_addr_filters);
2378 
2379 	if (!nr_addr_filters)
2380 		return perf_bpf_filter__parse(&evsel->bpf_filters, str);
2381 
2382 	if (evsel__append_addr_filter(evsel, str) < 0) {
2383 		fprintf(stderr,
2384 			"not enough memory to hold filter string\n");
2385 		return -1;
2386 	}
2387 
2388 	return 0;
2389 }
2390 
parse_filter(const struct option * opt,const char * str,int unset __maybe_unused)2391 int parse_filter(const struct option *opt, const char *str,
2392 		 int unset __maybe_unused)
2393 {
2394 	struct evlist *evlist = *(struct evlist **)opt->value;
2395 
2396 	return foreach_evsel_in_last_glob(evlist, set_filter,
2397 					  (const void *)str);
2398 }
2399 
add_exclude_perf_filter(struct evsel * evsel,const void * arg __maybe_unused)2400 static int add_exclude_perf_filter(struct evsel *evsel,
2401 				   const void *arg __maybe_unused)
2402 {
2403 	char new_filter[64];
2404 
2405 	if (evsel == NULL || evsel->core.attr.type != PERF_TYPE_TRACEPOINT) {
2406 		fprintf(stderr,
2407 			"--exclude-perf option should follow a -e tracepoint option\n");
2408 		return -1;
2409 	}
2410 
2411 	snprintf(new_filter, sizeof(new_filter), "common_pid != %d", getpid());
2412 
2413 	if (evsel__append_tp_filter(evsel, new_filter) < 0) {
2414 		fprintf(stderr,
2415 			"not enough memory to hold filter string\n");
2416 		return -1;
2417 	}
2418 
2419 	return 0;
2420 }
2421 
exclude_perf(const struct option * opt,const char * arg __maybe_unused,int unset __maybe_unused)2422 int exclude_perf(const struct option *opt,
2423 		 const char *arg __maybe_unused,
2424 		 int unset __maybe_unused)
2425 {
2426 	struct evlist *evlist = *(struct evlist **)opt->value;
2427 
2428 	return foreach_evsel_in_last_glob(evlist, add_exclude_perf_filter,
2429 					  NULL);
2430 }
2431 
parse_events__is_hardcoded_term(struct parse_events_term * term)2432 int parse_events__is_hardcoded_term(struct parse_events_term *term)
2433 {
2434 	return term->type_term != PARSE_EVENTS__TERM_TYPE_USER;
2435 }
2436 
new_term(struct parse_events_term ** _term,struct parse_events_term * temp,char * str,u64 num)2437 static int new_term(struct parse_events_term **_term,
2438 		    struct parse_events_term *temp,
2439 		    char *str, u64 num)
2440 {
2441 	struct parse_events_term *term;
2442 
2443 	term = malloc(sizeof(*term));
2444 	if (!term)
2445 		return -ENOMEM;
2446 
2447 	*term = *temp;
2448 	INIT_LIST_HEAD(&term->list);
2449 	term->weak = false;
2450 
2451 	switch (term->type_val) {
2452 	case PARSE_EVENTS__TERM_TYPE_NUM:
2453 		term->val.num = num;
2454 		break;
2455 	case PARSE_EVENTS__TERM_TYPE_STR:
2456 		term->val.str = str;
2457 		break;
2458 	default:
2459 		free(term);
2460 		return -EINVAL;
2461 	}
2462 
2463 	*_term = term;
2464 	return 0;
2465 }
2466 
parse_events_term__num(struct parse_events_term ** term,enum parse_events__term_type type_term,const char * config,u64 num,bool no_value,void * loc_term_,void * loc_val_)2467 int parse_events_term__num(struct parse_events_term **term,
2468 			   enum parse_events__term_type type_term,
2469 			   const char *config, u64 num,
2470 			   bool no_value,
2471 			   void *loc_term_, void *loc_val_)
2472 {
2473 	YYLTYPE *loc_term = loc_term_;
2474 	YYLTYPE *loc_val = loc_val_;
2475 
2476 	struct parse_events_term temp = {
2477 		.type_val  = PARSE_EVENTS__TERM_TYPE_NUM,
2478 		.type_term = type_term,
2479 		.config    = config ? : strdup(config_term_name(type_term)),
2480 		.no_value  = no_value,
2481 		.err_term  = loc_term ? loc_term->first_column : 0,
2482 		.err_val   = loc_val  ? loc_val->first_column  : 0,
2483 	};
2484 
2485 	return new_term(term, &temp, /*str=*/NULL, num);
2486 }
2487 
parse_events_term__str(struct parse_events_term ** term,enum parse_events__term_type type_term,char * config,char * str,void * loc_term_,void * loc_val_)2488 int parse_events_term__str(struct parse_events_term **term,
2489 			   enum parse_events__term_type type_term,
2490 			   char *config, char *str,
2491 			   void *loc_term_, void *loc_val_)
2492 {
2493 	YYLTYPE *loc_term = loc_term_;
2494 	YYLTYPE *loc_val = loc_val_;
2495 
2496 	struct parse_events_term temp = {
2497 		.type_val  = PARSE_EVENTS__TERM_TYPE_STR,
2498 		.type_term = type_term,
2499 		.config    = config,
2500 		.err_term  = loc_term ? loc_term->first_column : 0,
2501 		.err_val   = loc_val  ? loc_val->first_column  : 0,
2502 	};
2503 
2504 	return new_term(term, &temp, str, /*num=*/0);
2505 }
2506 
parse_events_term__term(struct parse_events_term ** term,enum parse_events__term_type term_lhs,enum parse_events__term_type term_rhs,void * loc_term,void * loc_val)2507 int parse_events_term__term(struct parse_events_term **term,
2508 			    enum parse_events__term_type term_lhs,
2509 			    enum parse_events__term_type term_rhs,
2510 			    void *loc_term, void *loc_val)
2511 {
2512 	return parse_events_term__str(term, term_lhs, NULL,
2513 				      strdup(config_term_name(term_rhs)),
2514 				      loc_term, loc_val);
2515 }
2516 
parse_events_term__clone(struct parse_events_term ** new,struct parse_events_term * term)2517 int parse_events_term__clone(struct parse_events_term **new,
2518 			     struct parse_events_term *term)
2519 {
2520 	char *str;
2521 	struct parse_events_term temp = *term;
2522 
2523 	temp.used = false;
2524 	if (term->config) {
2525 		temp.config = strdup(term->config);
2526 		if (!temp.config)
2527 			return -ENOMEM;
2528 	}
2529 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM)
2530 		return new_term(new, &temp, /*str=*/NULL, term->val.num);
2531 
2532 	str = strdup(term->val.str);
2533 	if (!str)
2534 		return -ENOMEM;
2535 	return new_term(new, &temp, str, /*num=*/0);
2536 }
2537 
parse_events_term__delete(struct parse_events_term * term)2538 void parse_events_term__delete(struct parse_events_term *term)
2539 {
2540 	if (term->type_val != PARSE_EVENTS__TERM_TYPE_NUM)
2541 		zfree(&term->val.str);
2542 
2543 	zfree(&term->config);
2544 	free(term);
2545 }
2546 
parse_events_copy_term_list(struct list_head * old,struct list_head ** new)2547 int parse_events_copy_term_list(struct list_head *old,
2548 				 struct list_head **new)
2549 {
2550 	struct parse_events_term *term, *n;
2551 	int ret;
2552 
2553 	if (!old) {
2554 		*new = NULL;
2555 		return 0;
2556 	}
2557 
2558 	*new = malloc(sizeof(struct list_head));
2559 	if (!*new)
2560 		return -ENOMEM;
2561 	INIT_LIST_HEAD(*new);
2562 
2563 	list_for_each_entry (term, old, list) {
2564 		ret = parse_events_term__clone(&n, term);
2565 		if (ret)
2566 			return ret;
2567 		list_add_tail(&n->list, *new);
2568 	}
2569 	return 0;
2570 }
2571 
parse_events_terms__purge(struct list_head * terms)2572 void parse_events_terms__purge(struct list_head *terms)
2573 {
2574 	struct parse_events_term *term, *h;
2575 
2576 	list_for_each_entry_safe(term, h, terms, list) {
2577 		list_del_init(&term->list);
2578 		parse_events_term__delete(term);
2579 	}
2580 }
2581 
parse_events_terms__delete(struct list_head * terms)2582 void parse_events_terms__delete(struct list_head *terms)
2583 {
2584 	if (!terms)
2585 		return;
2586 	parse_events_terms__purge(terms);
2587 	free(terms);
2588 }
2589 
parse_events_term__to_strbuf(struct list_head * term_list,struct strbuf * sb)2590 int parse_events_term__to_strbuf(struct list_head *term_list, struct strbuf *sb)
2591 {
2592 	struct parse_events_term *term;
2593 	bool first = true;
2594 
2595 	if (!term_list)
2596 		return 0;
2597 
2598 	list_for_each_entry(term, term_list, list) {
2599 		int ret;
2600 
2601 		if (!first) {
2602 			ret = strbuf_addch(sb, ',');
2603 			if (ret < 0)
2604 				return ret;
2605 		}
2606 		first = false;
2607 
2608 		if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM)
2609 			if (term->no_value) {
2610 				assert(term->val.num == 1);
2611 				ret = strbuf_addf(sb, "%s", term->config);
2612 			} else
2613 				ret = strbuf_addf(sb, "%s=%#"PRIx64, term->config, term->val.num);
2614 		else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
2615 			if (term->config) {
2616 				ret = strbuf_addf(sb, "%s=", term->config);
2617 				if (ret < 0)
2618 					return ret;
2619 			} else if ((unsigned int)term->type_term < __PARSE_EVENTS__TERM_TYPE_NR) {
2620 				ret = strbuf_addf(sb, "%s=", config_term_name(term->type_term));
2621 				if (ret < 0)
2622 					return ret;
2623 			}
2624 			assert(!term->no_value);
2625 			ret = strbuf_addf(sb, "%s", term->val.str);
2626 		}
2627 		if (ret < 0)
2628 			return ret;
2629 	}
2630 	return 0;
2631 }
2632 
parse_events_evlist_error(struct parse_events_state * parse_state,int idx,const char * str)2633 void parse_events_evlist_error(struct parse_events_state *parse_state,
2634 			       int idx, const char *str)
2635 {
2636 	if (!parse_state->error)
2637 		return;
2638 
2639 	parse_events_error__handle(parse_state->error, idx, strdup(str), NULL);
2640 }
2641 
config_terms_list(char * buf,size_t buf_sz)2642 static void config_terms_list(char *buf, size_t buf_sz)
2643 {
2644 	int i;
2645 	bool first = true;
2646 
2647 	buf[0] = '\0';
2648 	for (i = 0; i < __PARSE_EVENTS__TERM_TYPE_NR; i++) {
2649 		const char *name = config_term_name(i);
2650 
2651 		if (!config_term_avail(i, NULL))
2652 			continue;
2653 		if (!name)
2654 			continue;
2655 		if (name[0] == '<')
2656 			continue;
2657 
2658 		if (strlen(buf) + strlen(name) + 2 >= buf_sz)
2659 			return;
2660 
2661 		if (!first)
2662 			strcat(buf, ",");
2663 		else
2664 			first = false;
2665 		strcat(buf, name);
2666 	}
2667 }
2668 
2669 /*
2670  * Return string contains valid config terms of an event.
2671  * @additional_terms: For terms such as PMU sysfs terms.
2672  */
parse_events_formats_error_string(char * additional_terms)2673 char *parse_events_formats_error_string(char *additional_terms)
2674 {
2675 	char *str;
2676 	/* "no-overwrite" is the longest name */
2677 	char static_terms[__PARSE_EVENTS__TERM_TYPE_NR *
2678 			  (sizeof("no-overwrite") - 1)];
2679 
2680 	config_terms_list(static_terms, sizeof(static_terms));
2681 	/* valid terms */
2682 	if (additional_terms) {
2683 		if (asprintf(&str, "valid terms: %s,%s",
2684 			     additional_terms, static_terms) < 0)
2685 			goto fail;
2686 	} else {
2687 		if (asprintf(&str, "valid terms: %s", static_terms) < 0)
2688 			goto fail;
2689 	}
2690 	return str;
2691 
2692 fail:
2693 	return NULL;
2694 }
2695