xref: /linux/tools/perf/util/probe-event.c (revision a1087ef6abedf0bfd60e5e3fddf33192cb2c1325)
1 /*
2  * probe-event.c : perf-probe definition to probe_events format converter
3  *
4  * Written by Masami Hiramatsu <mhiramat@redhat.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19  *
20  */
21 
22 #define _GNU_SOURCE
23 #include <sys/utsname.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <stdio.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <stdarg.h>
33 #include <limits.h>
34 
35 #undef _GNU_SOURCE
36 #include "util.h"
37 #include "event.h"
38 #include "string.h"
39 #include "strlist.h"
40 #include "debug.h"
41 #include "cache.h"
42 #include "color.h"
43 #include "symbol.h"
44 #include "thread.h"
45 #include "debugfs.h"
46 #include "trace-event.h"	/* For __unused */
47 #include "probe-event.h"
48 #include "probe-finder.h"
49 
50 #define MAX_CMDLEN 256
51 #define MAX_PROBE_ARGS 128
52 #define PERFPROBE_GROUP "probe"
53 
54 bool probe_event_dry_run;	/* Dry run flag */
55 
56 #define semantic_error(msg ...) pr_err("Semantic error :" msg)
57 
58 /* If there is no space to write, returns -E2BIG. */
59 static int e_snprintf(char *str, size_t size, const char *format, ...)
60 	__attribute__((format(printf, 3, 4)));
61 
62 static int e_snprintf(char *str, size_t size, const char *format, ...)
63 {
64 	int ret;
65 	va_list ap;
66 	va_start(ap, format);
67 	ret = vsnprintf(str, size, format, ap);
68 	va_end(ap);
69 	if (ret >= (int)size)
70 		ret = -E2BIG;
71 	return ret;
72 }
73 
74 static char *synthesize_perf_probe_point(struct perf_probe_point *pp);
75 static struct machine machine;
76 
77 /* Initialize symbol maps and path of vmlinux/modules */
78 static int init_vmlinux(void)
79 {
80 	int ret;
81 
82 	symbol_conf.sort_by_name = true;
83 	if (symbol_conf.vmlinux_name == NULL)
84 		symbol_conf.try_vmlinux_path = true;
85 	else
86 		pr_debug("Use vmlinux: %s\n", symbol_conf.vmlinux_name);
87 	ret = symbol__init();
88 	if (ret < 0) {
89 		pr_debug("Failed to init symbol map.\n");
90 		goto out;
91 	}
92 
93 	ret = machine__init(&machine, "", HOST_KERNEL_ID);
94 	if (ret < 0)
95 		goto out;
96 
97 	if (machine__create_kernel_maps(&machine) < 0) {
98 		pr_debug("machine__create_kernel_maps ");
99 		goto out;
100 	}
101 out:
102 	if (ret < 0)
103 		pr_warning("Failed to init vmlinux path.\n");
104 	return ret;
105 }
106 
107 static struct symbol *__find_kernel_function_by_name(const char *name,
108 						     struct map **mapp)
109 {
110 	return machine__find_kernel_function_by_name(&machine, name, mapp,
111 						     NULL);
112 }
113 
114 const char *kernel_get_module_path(const char *module)
115 {
116 	struct dso *dso;
117 
118 	if (module) {
119 		list_for_each_entry(dso, &machine.kernel_dsos, node) {
120 			if (strncmp(dso->short_name + 1, module,
121 				    dso->short_name_len - 2) == 0)
122 				goto found;
123 		}
124 		pr_debug("Failed to find module %s.\n", module);
125 		return NULL;
126 	} else {
127 		dso = machine.vmlinux_maps[MAP__FUNCTION]->dso;
128 		if (dso__load_vmlinux_path(dso,
129 			 machine.vmlinux_maps[MAP__FUNCTION], NULL) < 0) {
130 			pr_debug("Failed to load kernel map.\n");
131 			return NULL;
132 		}
133 	}
134 found:
135 	return dso->long_name;
136 }
137 
138 #ifdef DWARF_SUPPORT
139 static int open_vmlinux(const char *module)
140 {
141 	const char *path = kernel_get_module_path(module);
142 	if (!path) {
143 		pr_err("Failed to find path of %s module", module ?: "kernel");
144 		return -ENOENT;
145 	}
146 	pr_debug("Try to open %s\n", path);
147 	return open(path, O_RDONLY);
148 }
149 
150 /*
151  * Convert trace point to probe point with debuginfo
152  * Currently only handles kprobes.
153  */
154 static int kprobe_convert_to_perf_probe(struct probe_trace_point *tp,
155 					struct perf_probe_point *pp)
156 {
157 	struct symbol *sym;
158 	struct map *map;
159 	u64 addr;
160 	int ret = -ENOENT;
161 
162 	sym = __find_kernel_function_by_name(tp->symbol, &map);
163 	if (sym) {
164 		addr = map->unmap_ip(map, sym->start + tp->offset);
165 		pr_debug("try to find %s+%ld@%llx\n", tp->symbol,
166 			 tp->offset, addr);
167 		ret = find_perf_probe_point((unsigned long)addr, pp);
168 	}
169 	if (ret <= 0) {
170 		pr_debug("Failed to find corresponding probes from "
171 			 "debuginfo. Use kprobe event information.\n");
172 		pp->function = strdup(tp->symbol);
173 		if (pp->function == NULL)
174 			return -ENOMEM;
175 		pp->offset = tp->offset;
176 	}
177 	pp->retprobe = tp->retprobe;
178 
179 	return 0;
180 }
181 
182 /* Try to find perf_probe_event with debuginfo */
183 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
184 					   struct probe_trace_event **tevs,
185 					   int max_tevs, const char *module)
186 {
187 	bool need_dwarf = perf_probe_event_need_dwarf(pev);
188 	int fd, ntevs;
189 
190 	fd = open_vmlinux(module);
191 	if (fd < 0) {
192 		if (need_dwarf) {
193 			pr_warning("Failed to open debuginfo file.\n");
194 			return fd;
195 		}
196 		pr_debug("Could not open vmlinux. Try to use symbols.\n");
197 		return 0;
198 	}
199 
200 	/* Searching trace events corresponding to probe event */
201 	ntevs = find_probe_trace_events(fd, pev, tevs, max_tevs);
202 	close(fd);
203 
204 	if (ntevs > 0) {	/* Succeeded to find trace events */
205 		pr_debug("find %d probe_trace_events.\n", ntevs);
206 		return ntevs;
207 	}
208 
209 	if (ntevs == 0)	{	/* No error but failed to find probe point. */
210 		pr_warning("Probe point '%s' not found.\n",
211 			   synthesize_perf_probe_point(&pev->point));
212 		return -ENOENT;
213 	}
214 	/* Error path : ntevs < 0 */
215 	pr_debug("An error occurred in debuginfo analysis (%d).\n", ntevs);
216 	if (ntevs == -EBADF) {
217 		pr_warning("Warning: No dwarf info found in the vmlinux - "
218 			"please rebuild kernel with CONFIG_DEBUG_INFO=y.\n");
219 		if (!need_dwarf) {
220 			pr_debug("Trying to use symbols.\nn");
221 			return 0;
222 		}
223 	}
224 	return ntevs;
225 }
226 
227 /*
228  * Find a src file from a DWARF tag path. Prepend optional source path prefix
229  * and chop off leading directories that do not exist. Result is passed back as
230  * a newly allocated path on success.
231  * Return 0 if file was found and readable, -errno otherwise.
232  */
233 static int get_real_path(const char *raw_path, const char *comp_dir,
234 			 char **new_path)
235 {
236 	const char *prefix = symbol_conf.source_prefix;
237 
238 	if (!prefix) {
239 		if (raw_path[0] != '/' && comp_dir)
240 			/* If not an absolute path, try to use comp_dir */
241 			prefix = comp_dir;
242 		else {
243 			if (access(raw_path, R_OK) == 0) {
244 				*new_path = strdup(raw_path);
245 				return 0;
246 			} else
247 				return -errno;
248 		}
249 	}
250 
251 	*new_path = malloc((strlen(prefix) + strlen(raw_path) + 2));
252 	if (!*new_path)
253 		return -ENOMEM;
254 
255 	for (;;) {
256 		sprintf(*new_path, "%s/%s", prefix, raw_path);
257 
258 		if (access(*new_path, R_OK) == 0)
259 			return 0;
260 
261 		if (!symbol_conf.source_prefix)
262 			/* In case of searching comp_dir, don't retry */
263 			return -errno;
264 
265 		switch (errno) {
266 		case ENAMETOOLONG:
267 		case ENOENT:
268 		case EROFS:
269 		case EFAULT:
270 			raw_path = strchr(++raw_path, '/');
271 			if (!raw_path) {
272 				free(*new_path);
273 				*new_path = NULL;
274 				return -ENOENT;
275 			}
276 			continue;
277 
278 		default:
279 			free(*new_path);
280 			*new_path = NULL;
281 			return -errno;
282 		}
283 	}
284 }
285 
286 #define LINEBUF_SIZE 256
287 #define NR_ADDITIONAL_LINES 2
288 
289 static int show_one_line(FILE *fp, int l, bool skip, bool show_num)
290 {
291 	char buf[LINEBUF_SIZE];
292 	const char *color = PERF_COLOR_BLUE;
293 
294 	if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
295 		goto error;
296 	if (!skip) {
297 		if (show_num)
298 			fprintf(stdout, "%7d  %s", l, buf);
299 		else
300 			color_fprintf(stdout, color, "         %s", buf);
301 	}
302 
303 	while (strlen(buf) == LINEBUF_SIZE - 1 &&
304 	       buf[LINEBUF_SIZE - 2] != '\n') {
305 		if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
306 			goto error;
307 		if (!skip) {
308 			if (show_num)
309 				fprintf(stdout, "%s", buf);
310 			else
311 				color_fprintf(stdout, color, "%s", buf);
312 		}
313 	}
314 
315 	return 0;
316 error:
317 	if (feof(fp))
318 		pr_warning("Source file is shorter than expected.\n");
319 	else
320 		pr_warning("File read error: %s\n", strerror(errno));
321 
322 	return -1;
323 }
324 
325 /*
326  * Show line-range always requires debuginfo to find source file and
327  * line number.
328  */
329 int show_line_range(struct line_range *lr, const char *module)
330 {
331 	int l = 1;
332 	struct line_node *ln;
333 	FILE *fp;
334 	int fd, ret;
335 	char *tmp;
336 
337 	/* Search a line range */
338 	ret = init_vmlinux();
339 	if (ret < 0)
340 		return ret;
341 
342 	fd = open_vmlinux(module);
343 	if (fd < 0) {
344 		pr_warning("Failed to open debuginfo file.\n");
345 		return fd;
346 	}
347 
348 	ret = find_line_range(fd, lr);
349 	close(fd);
350 	if (ret == 0) {
351 		pr_warning("Specified source line is not found.\n");
352 		return -ENOENT;
353 	} else if (ret < 0) {
354 		pr_warning("Debuginfo analysis failed. (%d)\n", ret);
355 		return ret;
356 	}
357 
358 	/* Convert source file path */
359 	tmp = lr->path;
360 	ret = get_real_path(tmp, lr->comp_dir, &lr->path);
361 	free(tmp);	/* Free old path */
362 	if (ret < 0) {
363 		pr_warning("Failed to find source file. (%d)\n", ret);
364 		return ret;
365 	}
366 
367 	setup_pager();
368 
369 	if (lr->function)
370 		fprintf(stdout, "<%s:%d>\n", lr->function,
371 			lr->start - lr->offset);
372 	else
373 		fprintf(stdout, "<%s:%d>\n", lr->file, lr->start);
374 
375 	fp = fopen(lr->path, "r");
376 	if (fp == NULL) {
377 		pr_warning("Failed to open %s: %s\n", lr->path,
378 			   strerror(errno));
379 		return -errno;
380 	}
381 	/* Skip to starting line number */
382 	while (l < lr->start && ret >= 0)
383 		ret = show_one_line(fp, l++, true, false);
384 	if (ret < 0)
385 		goto end;
386 
387 	list_for_each_entry(ln, &lr->line_list, list) {
388 		while (ln->line > l && ret >= 0)
389 			ret = show_one_line(fp, (l++) - lr->offset,
390 					    false, false);
391 		if (ret >= 0)
392 			ret = show_one_line(fp, (l++) - lr->offset,
393 					    false, true);
394 		if (ret < 0)
395 			goto end;
396 	}
397 
398 	if (lr->end == INT_MAX)
399 		lr->end = l + NR_ADDITIONAL_LINES;
400 	while (l <= lr->end && !feof(fp) && ret >= 0)
401 		ret = show_one_line(fp, (l++) - lr->offset, false, false);
402 end:
403 	fclose(fp);
404 	return ret;
405 }
406 
407 static int show_available_vars_at(int fd, struct perf_probe_event *pev,
408 				  int max_vls, bool externs)
409 {
410 	char *buf;
411 	int ret, i;
412 	struct str_node *node;
413 	struct variable_list *vls = NULL, *vl;
414 
415 	buf = synthesize_perf_probe_point(&pev->point);
416 	if (!buf)
417 		return -EINVAL;
418 	pr_debug("Searching variables at %s\n", buf);
419 
420 	ret = find_available_vars_at(fd, pev, &vls, max_vls, externs);
421 	if (ret > 0) {
422 		/* Some variables were found */
423 		fprintf(stdout, "Available variables at %s\n", buf);
424 		for (i = 0; i < ret; i++) {
425 			vl = &vls[i];
426 			/*
427 			 * A probe point might be converted to
428 			 * several trace points.
429 			 */
430 			fprintf(stdout, "\t@<%s+%lu>\n", vl->point.symbol,
431 				vl->point.offset);
432 			free(vl->point.symbol);
433 			if (vl->vars) {
434 				strlist__for_each(node, vl->vars)
435 					fprintf(stdout, "\t\t%s\n", node->s);
436 				strlist__delete(vl->vars);
437 			} else
438 				fprintf(stdout, "(No variables)\n");
439 		}
440 		free(vls);
441 	} else
442 		pr_err("Failed to find variables at %s (%d)\n", buf, ret);
443 
444 	free(buf);
445 	return ret;
446 }
447 
448 /* Show available variables on given probe point */
449 int show_available_vars(struct perf_probe_event *pevs, int npevs,
450 			int max_vls, const char *module, bool externs)
451 {
452 	int i, fd, ret = 0;
453 
454 	ret = init_vmlinux();
455 	if (ret < 0)
456 		return ret;
457 
458 	fd = open_vmlinux(module);
459 	if (fd < 0) {
460 		pr_warning("Failed to open debuginfo file.\n");
461 		return fd;
462 	}
463 
464 	setup_pager();
465 
466 	for (i = 0; i < npevs && ret >= 0; i++)
467 		ret = show_available_vars_at(fd, &pevs[i], max_vls, externs);
468 
469 	close(fd);
470 	return ret;
471 }
472 
473 #else	/* !DWARF_SUPPORT */
474 
475 static int kprobe_convert_to_perf_probe(struct probe_trace_point *tp,
476 					struct perf_probe_point *pp)
477 {
478 	struct symbol *sym;
479 
480 	sym = __find_kernel_function_by_name(tp->symbol, NULL);
481 	if (!sym) {
482 		pr_err("Failed to find symbol %s in kernel.\n", tp->symbol);
483 		return -ENOENT;
484 	}
485 	pp->function = strdup(tp->symbol);
486 	if (pp->function == NULL)
487 		return -ENOMEM;
488 	pp->offset = tp->offset;
489 	pp->retprobe = tp->retprobe;
490 
491 	return 0;
492 }
493 
494 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
495 				struct probe_trace_event **tevs __unused,
496 				int max_tevs __unused, const char *mod __unused)
497 {
498 	if (perf_probe_event_need_dwarf(pev)) {
499 		pr_warning("Debuginfo-analysis is not supported.\n");
500 		return -ENOSYS;
501 	}
502 	return 0;
503 }
504 
505 int show_line_range(struct line_range *lr __unused, const char *module __unused)
506 {
507 	pr_warning("Debuginfo-analysis is not supported.\n");
508 	return -ENOSYS;
509 }
510 
511 int show_available_vars(struct perf_probe_event *pevs __unused,
512 			int npevs __unused, int max_vls __unused,
513 			const char *module __unused, bool externs __unused)
514 {
515 	pr_warning("Debuginfo-analysis is not supported.\n");
516 	return -ENOSYS;
517 }
518 #endif
519 
520 int parse_line_range_desc(const char *arg, struct line_range *lr)
521 {
522 	const char *ptr;
523 	char *tmp;
524 	/*
525 	 * <Syntax>
526 	 * SRC:SLN[+NUM|-ELN]
527 	 * FUNC[:SLN[+NUM|-ELN]]
528 	 */
529 	ptr = strchr(arg, ':');
530 	if (ptr) {
531 		lr->start = (int)strtoul(ptr + 1, &tmp, 0);
532 		if (*tmp == '+') {
533 			lr->end = lr->start + (int)strtoul(tmp + 1, &tmp, 0);
534 			lr->end--;	/*
535 					 * Adjust the number of lines here.
536 					 * If the number of lines == 1, the
537 					 * the end of line should be equal to
538 					 * the start of line.
539 					 */
540 		} else if (*tmp == '-')
541 			lr->end = (int)strtoul(tmp + 1, &tmp, 0);
542 		else
543 			lr->end = INT_MAX;
544 		pr_debug("Line range is %d to %d\n", lr->start, lr->end);
545 		if (lr->start > lr->end) {
546 			semantic_error("Start line must be smaller"
547 				       " than end line.\n");
548 			return -EINVAL;
549 		}
550 		if (*tmp != '\0') {
551 			semantic_error("Tailing with invalid character '%d'.\n",
552 				       *tmp);
553 			return -EINVAL;
554 		}
555 		tmp = strndup(arg, (ptr - arg));
556 	} else {
557 		tmp = strdup(arg);
558 		lr->end = INT_MAX;
559 	}
560 
561 	if (tmp == NULL)
562 		return -ENOMEM;
563 
564 	if (strchr(tmp, '.'))
565 		lr->file = tmp;
566 	else
567 		lr->function = tmp;
568 
569 	return 0;
570 }
571 
572 /* Check the name is good for event/group */
573 static bool check_event_name(const char *name)
574 {
575 	if (!isalpha(*name) && *name != '_')
576 		return false;
577 	while (*++name != '\0') {
578 		if (!isalpha(*name) && !isdigit(*name) && *name != '_')
579 			return false;
580 	}
581 	return true;
582 }
583 
584 /* Parse probepoint definition. */
585 static int parse_perf_probe_point(char *arg, struct perf_probe_event *pev)
586 {
587 	struct perf_probe_point *pp = &pev->point;
588 	char *ptr, *tmp;
589 	char c, nc = 0;
590 	/*
591 	 * <Syntax>
592 	 * perf probe [EVENT=]SRC[:LN|;PTN]
593 	 * perf probe [EVENT=]FUNC[@SRC][+OFFS|%return|:LN|;PAT]
594 	 *
595 	 * TODO:Group name support
596 	 */
597 
598 	ptr = strpbrk(arg, ";=@+%");
599 	if (ptr && *ptr == '=') {	/* Event name */
600 		*ptr = '\0';
601 		tmp = ptr + 1;
602 		if (strchr(arg, ':')) {
603 			semantic_error("Group name is not supported yet.\n");
604 			return -ENOTSUP;
605 		}
606 		if (!check_event_name(arg)) {
607 			semantic_error("%s is bad for event name -it must "
608 				       "follow C symbol-naming rule.\n", arg);
609 			return -EINVAL;
610 		}
611 		pev->event = strdup(arg);
612 		if (pev->event == NULL)
613 			return -ENOMEM;
614 		pev->group = NULL;
615 		arg = tmp;
616 	}
617 
618 	ptr = strpbrk(arg, ";:+@%");
619 	if (ptr) {
620 		nc = *ptr;
621 		*ptr++ = '\0';
622 	}
623 
624 	tmp = strdup(arg);
625 	if (tmp == NULL)
626 		return -ENOMEM;
627 
628 	/* Check arg is function or file and copy it */
629 	if (strchr(tmp, '.'))	/* File */
630 		pp->file = tmp;
631 	else			/* Function */
632 		pp->function = tmp;
633 
634 	/* Parse other options */
635 	while (ptr) {
636 		arg = ptr;
637 		c = nc;
638 		if (c == ';') {	/* Lazy pattern must be the last part */
639 			pp->lazy_line = strdup(arg);
640 			if (pp->lazy_line == NULL)
641 				return -ENOMEM;
642 			break;
643 		}
644 		ptr = strpbrk(arg, ";:+@%");
645 		if (ptr) {
646 			nc = *ptr;
647 			*ptr++ = '\0';
648 		}
649 		switch (c) {
650 		case ':':	/* Line number */
651 			pp->line = strtoul(arg, &tmp, 0);
652 			if (*tmp != '\0') {
653 				semantic_error("There is non-digit char"
654 					       " in line number.\n");
655 				return -EINVAL;
656 			}
657 			break;
658 		case '+':	/* Byte offset from a symbol */
659 			pp->offset = strtoul(arg, &tmp, 0);
660 			if (*tmp != '\0') {
661 				semantic_error("There is non-digit character"
662 						" in offset.\n");
663 				return -EINVAL;
664 			}
665 			break;
666 		case '@':	/* File name */
667 			if (pp->file) {
668 				semantic_error("SRC@SRC is not allowed.\n");
669 				return -EINVAL;
670 			}
671 			pp->file = strdup(arg);
672 			if (pp->file == NULL)
673 				return -ENOMEM;
674 			break;
675 		case '%':	/* Probe places */
676 			if (strcmp(arg, "return") == 0) {
677 				pp->retprobe = 1;
678 			} else {	/* Others not supported yet */
679 				semantic_error("%%%s is not supported.\n", arg);
680 				return -ENOTSUP;
681 			}
682 			break;
683 		default:	/* Buggy case */
684 			pr_err("This program has a bug at %s:%d.\n",
685 				__FILE__, __LINE__);
686 			return -ENOTSUP;
687 			break;
688 		}
689 	}
690 
691 	/* Exclusion check */
692 	if (pp->lazy_line && pp->line) {
693 		semantic_error("Lazy pattern can't be used with line number.");
694 		return -EINVAL;
695 	}
696 
697 	if (pp->lazy_line && pp->offset) {
698 		semantic_error("Lazy pattern can't be used with offset.");
699 		return -EINVAL;
700 	}
701 
702 	if (pp->line && pp->offset) {
703 		semantic_error("Offset can't be used with line number.");
704 		return -EINVAL;
705 	}
706 
707 	if (!pp->line && !pp->lazy_line && pp->file && !pp->function) {
708 		semantic_error("File always requires line number or "
709 			       "lazy pattern.");
710 		return -EINVAL;
711 	}
712 
713 	if (pp->offset && !pp->function) {
714 		semantic_error("Offset requires an entry function.");
715 		return -EINVAL;
716 	}
717 
718 	if (pp->retprobe && !pp->function) {
719 		semantic_error("Return probe requires an entry function.");
720 		return -EINVAL;
721 	}
722 
723 	if ((pp->offset || pp->line || pp->lazy_line) && pp->retprobe) {
724 		semantic_error("Offset/Line/Lazy pattern can't be used with "
725 			       "return probe.");
726 		return -EINVAL;
727 	}
728 
729 	pr_debug("symbol:%s file:%s line:%d offset:%lu return:%d lazy:%s\n",
730 		 pp->function, pp->file, pp->line, pp->offset, pp->retprobe,
731 		 pp->lazy_line);
732 	return 0;
733 }
734 
735 /* Parse perf-probe event argument */
736 static int parse_perf_probe_arg(char *str, struct perf_probe_arg *arg)
737 {
738 	char *tmp, *goodname;
739 	struct perf_probe_arg_field **fieldp;
740 
741 	pr_debug("parsing arg: %s into ", str);
742 
743 	tmp = strchr(str, '=');
744 	if (tmp) {
745 		arg->name = strndup(str, tmp - str);
746 		if (arg->name == NULL)
747 			return -ENOMEM;
748 		pr_debug("name:%s ", arg->name);
749 		str = tmp + 1;
750 	}
751 
752 	tmp = strchr(str, ':');
753 	if (tmp) {	/* Type setting */
754 		*tmp = '\0';
755 		arg->type = strdup(tmp + 1);
756 		if (arg->type == NULL)
757 			return -ENOMEM;
758 		pr_debug("type:%s ", arg->type);
759 	}
760 
761 	tmp = strpbrk(str, "-.[");
762 	if (!is_c_varname(str) || !tmp) {
763 		/* A variable, register, symbol or special value */
764 		arg->var = strdup(str);
765 		if (arg->var == NULL)
766 			return -ENOMEM;
767 		pr_debug("%s\n", arg->var);
768 		return 0;
769 	}
770 
771 	/* Structure fields or array element */
772 	arg->var = strndup(str, tmp - str);
773 	if (arg->var == NULL)
774 		return -ENOMEM;
775 	goodname = arg->var;
776 	pr_debug("%s, ", arg->var);
777 	fieldp = &arg->field;
778 
779 	do {
780 		*fieldp = zalloc(sizeof(struct perf_probe_arg_field));
781 		if (*fieldp == NULL)
782 			return -ENOMEM;
783 		if (*tmp == '[') {	/* Array */
784 			str = tmp;
785 			(*fieldp)->index = strtol(str + 1, &tmp, 0);
786 			(*fieldp)->ref = true;
787 			if (*tmp != ']' || tmp == str + 1) {
788 				semantic_error("Array index must be a"
789 						" number.\n");
790 				return -EINVAL;
791 			}
792 			tmp++;
793 			if (*tmp == '\0')
794 				tmp = NULL;
795 		} else {		/* Structure */
796 			if (*tmp == '.') {
797 				str = tmp + 1;
798 				(*fieldp)->ref = false;
799 			} else if (tmp[1] == '>') {
800 				str = tmp + 2;
801 				(*fieldp)->ref = true;
802 			} else {
803 				semantic_error("Argument parse error: %s\n",
804 					       str);
805 				return -EINVAL;
806 			}
807 			tmp = strpbrk(str, "-.[");
808 		}
809 		if (tmp) {
810 			(*fieldp)->name = strndup(str, tmp - str);
811 			if ((*fieldp)->name == NULL)
812 				return -ENOMEM;
813 			if (*str != '[')
814 				goodname = (*fieldp)->name;
815 			pr_debug("%s(%d), ", (*fieldp)->name, (*fieldp)->ref);
816 			fieldp = &(*fieldp)->next;
817 		}
818 	} while (tmp);
819 	(*fieldp)->name = strdup(str);
820 	if ((*fieldp)->name == NULL)
821 		return -ENOMEM;
822 	if (*str != '[')
823 		goodname = (*fieldp)->name;
824 	pr_debug("%s(%d)\n", (*fieldp)->name, (*fieldp)->ref);
825 
826 	/* If no name is specified, set the last field name (not array index)*/
827 	if (!arg->name) {
828 		arg->name = strdup(goodname);
829 		if (arg->name == NULL)
830 			return -ENOMEM;
831 	}
832 	return 0;
833 }
834 
835 /* Parse perf-probe event command */
836 int parse_perf_probe_command(const char *cmd, struct perf_probe_event *pev)
837 {
838 	char **argv;
839 	int argc, i, ret = 0;
840 
841 	argv = argv_split(cmd, &argc);
842 	if (!argv) {
843 		pr_debug("Failed to split arguments.\n");
844 		return -ENOMEM;
845 	}
846 	if (argc - 1 > MAX_PROBE_ARGS) {
847 		semantic_error("Too many probe arguments (%d).\n", argc - 1);
848 		ret = -ERANGE;
849 		goto out;
850 	}
851 	/* Parse probe point */
852 	ret = parse_perf_probe_point(argv[0], pev);
853 	if (ret < 0)
854 		goto out;
855 
856 	/* Copy arguments and ensure return probe has no C argument */
857 	pev->nargs = argc - 1;
858 	pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
859 	if (pev->args == NULL) {
860 		ret = -ENOMEM;
861 		goto out;
862 	}
863 	for (i = 0; i < pev->nargs && ret >= 0; i++) {
864 		ret = parse_perf_probe_arg(argv[i + 1], &pev->args[i]);
865 		if (ret >= 0 &&
866 		    is_c_varname(pev->args[i].var) && pev->point.retprobe) {
867 			semantic_error("You can't specify local variable for"
868 				       " kretprobe.\n");
869 			ret = -EINVAL;
870 		}
871 	}
872 out:
873 	argv_free(argv);
874 
875 	return ret;
876 }
877 
878 /* Return true if this perf_probe_event requires debuginfo */
879 bool perf_probe_event_need_dwarf(struct perf_probe_event *pev)
880 {
881 	int i;
882 
883 	if (pev->point.file || pev->point.line || pev->point.lazy_line)
884 		return true;
885 
886 	for (i = 0; i < pev->nargs; i++)
887 		if (is_c_varname(pev->args[i].var))
888 			return true;
889 
890 	return false;
891 }
892 
893 /* Parse probe_events event into struct probe_point */
894 static int parse_probe_trace_command(const char *cmd,
895 					struct probe_trace_event *tev)
896 {
897 	struct probe_trace_point *tp = &tev->point;
898 	char pr;
899 	char *p;
900 	int ret, i, argc;
901 	char **argv;
902 
903 	pr_debug("Parsing probe_events: %s\n", cmd);
904 	argv = argv_split(cmd, &argc);
905 	if (!argv) {
906 		pr_debug("Failed to split arguments.\n");
907 		return -ENOMEM;
908 	}
909 	if (argc < 2) {
910 		semantic_error("Too few probe arguments.\n");
911 		ret = -ERANGE;
912 		goto out;
913 	}
914 
915 	/* Scan event and group name. */
916 	ret = sscanf(argv[0], "%c:%a[^/ \t]/%a[^ \t]",
917 		     &pr, (float *)(void *)&tev->group,
918 		     (float *)(void *)&tev->event);
919 	if (ret != 3) {
920 		semantic_error("Failed to parse event name: %s\n", argv[0]);
921 		ret = -EINVAL;
922 		goto out;
923 	}
924 	pr_debug("Group:%s Event:%s probe:%c\n", tev->group, tev->event, pr);
925 
926 	tp->retprobe = (pr == 'r');
927 
928 	/* Scan function name and offset */
929 	ret = sscanf(argv[1], "%a[^+]+%lu", (float *)(void *)&tp->symbol,
930 		     &tp->offset);
931 	if (ret == 1)
932 		tp->offset = 0;
933 
934 	tev->nargs = argc - 2;
935 	tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
936 	if (tev->args == NULL) {
937 		ret = -ENOMEM;
938 		goto out;
939 	}
940 	for (i = 0; i < tev->nargs; i++) {
941 		p = strchr(argv[i + 2], '=');
942 		if (p)	/* We don't need which register is assigned. */
943 			*p++ = '\0';
944 		else
945 			p = argv[i + 2];
946 		tev->args[i].name = strdup(argv[i + 2]);
947 		/* TODO: parse regs and offset */
948 		tev->args[i].value = strdup(p);
949 		if (tev->args[i].name == NULL || tev->args[i].value == NULL) {
950 			ret = -ENOMEM;
951 			goto out;
952 		}
953 	}
954 	ret = 0;
955 out:
956 	argv_free(argv);
957 	return ret;
958 }
959 
960 /* Compose only probe arg */
961 int synthesize_perf_probe_arg(struct perf_probe_arg *pa, char *buf, size_t len)
962 {
963 	struct perf_probe_arg_field *field = pa->field;
964 	int ret;
965 	char *tmp = buf;
966 
967 	if (pa->name && pa->var)
968 		ret = e_snprintf(tmp, len, "%s=%s", pa->name, pa->var);
969 	else
970 		ret = e_snprintf(tmp, len, "%s", pa->name ? pa->name : pa->var);
971 	if (ret <= 0)
972 		goto error;
973 	tmp += ret;
974 	len -= ret;
975 
976 	while (field) {
977 		if (field->name[0] == '[')
978 			ret = e_snprintf(tmp, len, "%s", field->name);
979 		else
980 			ret = e_snprintf(tmp, len, "%s%s",
981 					 field->ref ? "->" : ".", field->name);
982 		if (ret <= 0)
983 			goto error;
984 		tmp += ret;
985 		len -= ret;
986 		field = field->next;
987 	}
988 
989 	if (pa->type) {
990 		ret = e_snprintf(tmp, len, ":%s", pa->type);
991 		if (ret <= 0)
992 			goto error;
993 		tmp += ret;
994 		len -= ret;
995 	}
996 
997 	return tmp - buf;
998 error:
999 	pr_debug("Failed to synthesize perf probe argument: %s",
1000 		 strerror(-ret));
1001 	return ret;
1002 }
1003 
1004 /* Compose only probe point (not argument) */
1005 static char *synthesize_perf_probe_point(struct perf_probe_point *pp)
1006 {
1007 	char *buf, *tmp;
1008 	char offs[32] = "", line[32] = "", file[32] = "";
1009 	int ret, len;
1010 
1011 	buf = zalloc(MAX_CMDLEN);
1012 	if (buf == NULL) {
1013 		ret = -ENOMEM;
1014 		goto error;
1015 	}
1016 	if (pp->offset) {
1017 		ret = e_snprintf(offs, 32, "+%lu", pp->offset);
1018 		if (ret <= 0)
1019 			goto error;
1020 	}
1021 	if (pp->line) {
1022 		ret = e_snprintf(line, 32, ":%d", pp->line);
1023 		if (ret <= 0)
1024 			goto error;
1025 	}
1026 	if (pp->file) {
1027 		len = strlen(pp->file) - 31;
1028 		if (len < 0)
1029 			len = 0;
1030 		tmp = strchr(pp->file + len, '/');
1031 		if (!tmp)
1032 			tmp = pp->file + len;
1033 		ret = e_snprintf(file, 32, "@%s", tmp + 1);
1034 		if (ret <= 0)
1035 			goto error;
1036 	}
1037 
1038 	if (pp->function)
1039 		ret = e_snprintf(buf, MAX_CMDLEN, "%s%s%s%s%s", pp->function,
1040 				 offs, pp->retprobe ? "%return" : "", line,
1041 				 file);
1042 	else
1043 		ret = e_snprintf(buf, MAX_CMDLEN, "%s%s", file, line);
1044 	if (ret <= 0)
1045 		goto error;
1046 
1047 	return buf;
1048 error:
1049 	pr_debug("Failed to synthesize perf probe point: %s",
1050 		 strerror(-ret));
1051 	if (buf)
1052 		free(buf);
1053 	return NULL;
1054 }
1055 
1056 #if 0
1057 char *synthesize_perf_probe_command(struct perf_probe_event *pev)
1058 {
1059 	char *buf;
1060 	int i, len, ret;
1061 
1062 	buf = synthesize_perf_probe_point(&pev->point);
1063 	if (!buf)
1064 		return NULL;
1065 
1066 	len = strlen(buf);
1067 	for (i = 0; i < pev->nargs; i++) {
1068 		ret = e_snprintf(&buf[len], MAX_CMDLEN - len, " %s",
1069 				 pev->args[i].name);
1070 		if (ret <= 0) {
1071 			free(buf);
1072 			return NULL;
1073 		}
1074 		len += ret;
1075 	}
1076 
1077 	return buf;
1078 }
1079 #endif
1080 
1081 static int __synthesize_probe_trace_arg_ref(struct probe_trace_arg_ref *ref,
1082 					     char **buf, size_t *buflen,
1083 					     int depth)
1084 {
1085 	int ret;
1086 	if (ref->next) {
1087 		depth = __synthesize_probe_trace_arg_ref(ref->next, buf,
1088 							 buflen, depth + 1);
1089 		if (depth < 0)
1090 			goto out;
1091 	}
1092 
1093 	ret = e_snprintf(*buf, *buflen, "%+ld(", ref->offset);
1094 	if (ret < 0)
1095 		depth = ret;
1096 	else {
1097 		*buf += ret;
1098 		*buflen -= ret;
1099 	}
1100 out:
1101 	return depth;
1102 
1103 }
1104 
1105 static int synthesize_probe_trace_arg(struct probe_trace_arg *arg,
1106 				       char *buf, size_t buflen)
1107 {
1108 	struct probe_trace_arg_ref *ref = arg->ref;
1109 	int ret, depth = 0;
1110 	char *tmp = buf;
1111 
1112 	/* Argument name or separator */
1113 	if (arg->name)
1114 		ret = e_snprintf(buf, buflen, " %s=", arg->name);
1115 	else
1116 		ret = e_snprintf(buf, buflen, " ");
1117 	if (ret < 0)
1118 		return ret;
1119 	buf += ret;
1120 	buflen -= ret;
1121 
1122 	/* Special case: @XXX */
1123 	if (arg->value[0] == '@' && arg->ref)
1124 			ref = ref->next;
1125 
1126 	/* Dereferencing arguments */
1127 	if (ref) {
1128 		depth = __synthesize_probe_trace_arg_ref(ref, &buf,
1129 							  &buflen, 1);
1130 		if (depth < 0)
1131 			return depth;
1132 	}
1133 
1134 	/* Print argument value */
1135 	if (arg->value[0] == '@' && arg->ref)
1136 		ret = e_snprintf(buf, buflen, "%s%+ld", arg->value,
1137 				 arg->ref->offset);
1138 	else
1139 		ret = e_snprintf(buf, buflen, "%s", arg->value);
1140 	if (ret < 0)
1141 		return ret;
1142 	buf += ret;
1143 	buflen -= ret;
1144 
1145 	/* Closing */
1146 	while (depth--) {
1147 		ret = e_snprintf(buf, buflen, ")");
1148 		if (ret < 0)
1149 			return ret;
1150 		buf += ret;
1151 		buflen -= ret;
1152 	}
1153 	/* Print argument type */
1154 	if (arg->type) {
1155 		ret = e_snprintf(buf, buflen, ":%s", arg->type);
1156 		if (ret <= 0)
1157 			return ret;
1158 		buf += ret;
1159 	}
1160 
1161 	return buf - tmp;
1162 }
1163 
1164 char *synthesize_probe_trace_command(struct probe_trace_event *tev)
1165 {
1166 	struct probe_trace_point *tp = &tev->point;
1167 	char *buf;
1168 	int i, len, ret;
1169 
1170 	buf = zalloc(MAX_CMDLEN);
1171 	if (buf == NULL)
1172 		return NULL;
1173 
1174 	len = e_snprintf(buf, MAX_CMDLEN, "%c:%s/%s %s+%lu",
1175 			 tp->retprobe ? 'r' : 'p',
1176 			 tev->group, tev->event,
1177 			 tp->symbol, tp->offset);
1178 	if (len <= 0)
1179 		goto error;
1180 
1181 	for (i = 0; i < tev->nargs; i++) {
1182 		ret = synthesize_probe_trace_arg(&tev->args[i], buf + len,
1183 						  MAX_CMDLEN - len);
1184 		if (ret <= 0)
1185 			goto error;
1186 		len += ret;
1187 	}
1188 
1189 	return buf;
1190 error:
1191 	free(buf);
1192 	return NULL;
1193 }
1194 
1195 static int convert_to_perf_probe_event(struct probe_trace_event *tev,
1196 				       struct perf_probe_event *pev)
1197 {
1198 	char buf[64] = "";
1199 	int i, ret;
1200 
1201 	/* Convert event/group name */
1202 	pev->event = strdup(tev->event);
1203 	pev->group = strdup(tev->group);
1204 	if (pev->event == NULL || pev->group == NULL)
1205 		return -ENOMEM;
1206 
1207 	/* Convert trace_point to probe_point */
1208 	ret = kprobe_convert_to_perf_probe(&tev->point, &pev->point);
1209 	if (ret < 0)
1210 		return ret;
1211 
1212 	/* Convert trace_arg to probe_arg */
1213 	pev->nargs = tev->nargs;
1214 	pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1215 	if (pev->args == NULL)
1216 		return -ENOMEM;
1217 	for (i = 0; i < tev->nargs && ret >= 0; i++) {
1218 		if (tev->args[i].name)
1219 			pev->args[i].name = strdup(tev->args[i].name);
1220 		else {
1221 			ret = synthesize_probe_trace_arg(&tev->args[i],
1222 							  buf, 64);
1223 			pev->args[i].name = strdup(buf);
1224 		}
1225 		if (pev->args[i].name == NULL && ret >= 0)
1226 			ret = -ENOMEM;
1227 	}
1228 
1229 	if (ret < 0)
1230 		clear_perf_probe_event(pev);
1231 
1232 	return ret;
1233 }
1234 
1235 void clear_perf_probe_event(struct perf_probe_event *pev)
1236 {
1237 	struct perf_probe_point *pp = &pev->point;
1238 	struct perf_probe_arg_field *field, *next;
1239 	int i;
1240 
1241 	if (pev->event)
1242 		free(pev->event);
1243 	if (pev->group)
1244 		free(pev->group);
1245 	if (pp->file)
1246 		free(pp->file);
1247 	if (pp->function)
1248 		free(pp->function);
1249 	if (pp->lazy_line)
1250 		free(pp->lazy_line);
1251 	for (i = 0; i < pev->nargs; i++) {
1252 		if (pev->args[i].name)
1253 			free(pev->args[i].name);
1254 		if (pev->args[i].var)
1255 			free(pev->args[i].var);
1256 		if (pev->args[i].type)
1257 			free(pev->args[i].type);
1258 		field = pev->args[i].field;
1259 		while (field) {
1260 			next = field->next;
1261 			if (field->name)
1262 				free(field->name);
1263 			free(field);
1264 			field = next;
1265 		}
1266 	}
1267 	if (pev->args)
1268 		free(pev->args);
1269 	memset(pev, 0, sizeof(*pev));
1270 }
1271 
1272 static void clear_probe_trace_event(struct probe_trace_event *tev)
1273 {
1274 	struct probe_trace_arg_ref *ref, *next;
1275 	int i;
1276 
1277 	if (tev->event)
1278 		free(tev->event);
1279 	if (tev->group)
1280 		free(tev->group);
1281 	if (tev->point.symbol)
1282 		free(tev->point.symbol);
1283 	for (i = 0; i < tev->nargs; i++) {
1284 		if (tev->args[i].name)
1285 			free(tev->args[i].name);
1286 		if (tev->args[i].value)
1287 			free(tev->args[i].value);
1288 		if (tev->args[i].type)
1289 			free(tev->args[i].type);
1290 		ref = tev->args[i].ref;
1291 		while (ref) {
1292 			next = ref->next;
1293 			free(ref);
1294 			ref = next;
1295 		}
1296 	}
1297 	if (tev->args)
1298 		free(tev->args);
1299 	memset(tev, 0, sizeof(*tev));
1300 }
1301 
1302 static int open_kprobe_events(bool readwrite)
1303 {
1304 	char buf[PATH_MAX];
1305 	const char *__debugfs;
1306 	int ret;
1307 
1308 	__debugfs = debugfs_find_mountpoint();
1309 	if (__debugfs == NULL) {
1310 		pr_warning("Debugfs is not mounted.\n");
1311 		return -ENOENT;
1312 	}
1313 
1314 	ret = e_snprintf(buf, PATH_MAX, "%stracing/kprobe_events", __debugfs);
1315 	if (ret >= 0) {
1316 		pr_debug("Opening %s write=%d\n", buf, readwrite);
1317 		if (readwrite && !probe_event_dry_run)
1318 			ret = open(buf, O_RDWR, O_APPEND);
1319 		else
1320 			ret = open(buf, O_RDONLY, 0);
1321 	}
1322 
1323 	if (ret < 0) {
1324 		if (errno == ENOENT)
1325 			pr_warning("kprobe_events file does not exist - please"
1326 				 " rebuild kernel with CONFIG_KPROBE_EVENT.\n");
1327 		else
1328 			pr_warning("Failed to open kprobe_events file: %s\n",
1329 				   strerror(errno));
1330 	}
1331 	return ret;
1332 }
1333 
1334 /* Get raw string list of current kprobe_events */
1335 static struct strlist *get_probe_trace_command_rawlist(int fd)
1336 {
1337 	int ret, idx;
1338 	FILE *fp;
1339 	char buf[MAX_CMDLEN];
1340 	char *p;
1341 	struct strlist *sl;
1342 
1343 	sl = strlist__new(true, NULL);
1344 
1345 	fp = fdopen(dup(fd), "r");
1346 	while (!feof(fp)) {
1347 		p = fgets(buf, MAX_CMDLEN, fp);
1348 		if (!p)
1349 			break;
1350 
1351 		idx = strlen(p) - 1;
1352 		if (p[idx] == '\n')
1353 			p[idx] = '\0';
1354 		ret = strlist__add(sl, buf);
1355 		if (ret < 0) {
1356 			pr_debug("strlist__add failed: %s\n", strerror(-ret));
1357 			strlist__delete(sl);
1358 			return NULL;
1359 		}
1360 	}
1361 	fclose(fp);
1362 
1363 	return sl;
1364 }
1365 
1366 /* Show an event */
1367 static int show_perf_probe_event(struct perf_probe_event *pev)
1368 {
1369 	int i, ret;
1370 	char buf[128];
1371 	char *place;
1372 
1373 	/* Synthesize only event probe point */
1374 	place = synthesize_perf_probe_point(&pev->point);
1375 	if (!place)
1376 		return -EINVAL;
1377 
1378 	ret = e_snprintf(buf, 128, "%s:%s", pev->group, pev->event);
1379 	if (ret < 0)
1380 		return ret;
1381 
1382 	printf("  %-20s (on %s", buf, place);
1383 
1384 	if (pev->nargs > 0) {
1385 		printf(" with");
1386 		for (i = 0; i < pev->nargs; i++) {
1387 			ret = synthesize_perf_probe_arg(&pev->args[i],
1388 							buf, 128);
1389 			if (ret < 0)
1390 				break;
1391 			printf(" %s", buf);
1392 		}
1393 	}
1394 	printf(")\n");
1395 	free(place);
1396 	return ret;
1397 }
1398 
1399 /* List up current perf-probe events */
1400 int show_perf_probe_events(void)
1401 {
1402 	int fd, ret;
1403 	struct probe_trace_event tev;
1404 	struct perf_probe_event pev;
1405 	struct strlist *rawlist;
1406 	struct str_node *ent;
1407 
1408 	setup_pager();
1409 	ret = init_vmlinux();
1410 	if (ret < 0)
1411 		return ret;
1412 
1413 	memset(&tev, 0, sizeof(tev));
1414 	memset(&pev, 0, sizeof(pev));
1415 
1416 	fd = open_kprobe_events(false);
1417 	if (fd < 0)
1418 		return fd;
1419 
1420 	rawlist = get_probe_trace_command_rawlist(fd);
1421 	close(fd);
1422 	if (!rawlist)
1423 		return -ENOENT;
1424 
1425 	strlist__for_each(ent, rawlist) {
1426 		ret = parse_probe_trace_command(ent->s, &tev);
1427 		if (ret >= 0) {
1428 			ret = convert_to_perf_probe_event(&tev, &pev);
1429 			if (ret >= 0)
1430 				ret = show_perf_probe_event(&pev);
1431 		}
1432 		clear_perf_probe_event(&pev);
1433 		clear_probe_trace_event(&tev);
1434 		if (ret < 0)
1435 			break;
1436 	}
1437 	strlist__delete(rawlist);
1438 
1439 	return ret;
1440 }
1441 
1442 /* Get current perf-probe event names */
1443 static struct strlist *get_probe_trace_event_names(int fd, bool include_group)
1444 {
1445 	char buf[128];
1446 	struct strlist *sl, *rawlist;
1447 	struct str_node *ent;
1448 	struct probe_trace_event tev;
1449 	int ret = 0;
1450 
1451 	memset(&tev, 0, sizeof(tev));
1452 	rawlist = get_probe_trace_command_rawlist(fd);
1453 	sl = strlist__new(true, NULL);
1454 	strlist__for_each(ent, rawlist) {
1455 		ret = parse_probe_trace_command(ent->s, &tev);
1456 		if (ret < 0)
1457 			break;
1458 		if (include_group) {
1459 			ret = e_snprintf(buf, 128, "%s:%s", tev.group,
1460 					tev.event);
1461 			if (ret >= 0)
1462 				ret = strlist__add(sl, buf);
1463 		} else
1464 			ret = strlist__add(sl, tev.event);
1465 		clear_probe_trace_event(&tev);
1466 		if (ret < 0)
1467 			break;
1468 	}
1469 	strlist__delete(rawlist);
1470 
1471 	if (ret < 0) {
1472 		strlist__delete(sl);
1473 		return NULL;
1474 	}
1475 	return sl;
1476 }
1477 
1478 static int write_probe_trace_event(int fd, struct probe_trace_event *tev)
1479 {
1480 	int ret = 0;
1481 	char *buf = synthesize_probe_trace_command(tev);
1482 
1483 	if (!buf) {
1484 		pr_debug("Failed to synthesize probe trace event.\n");
1485 		return -EINVAL;
1486 	}
1487 
1488 	pr_debug("Writing event: %s\n", buf);
1489 	if (!probe_event_dry_run) {
1490 		ret = write(fd, buf, strlen(buf));
1491 		if (ret <= 0)
1492 			pr_warning("Failed to write event: %s\n",
1493 				   strerror(errno));
1494 	}
1495 	free(buf);
1496 	return ret;
1497 }
1498 
1499 static int get_new_event_name(char *buf, size_t len, const char *base,
1500 			      struct strlist *namelist, bool allow_suffix)
1501 {
1502 	int i, ret;
1503 
1504 	/* Try no suffix */
1505 	ret = e_snprintf(buf, len, "%s", base);
1506 	if (ret < 0) {
1507 		pr_debug("snprintf() failed: %s\n", strerror(-ret));
1508 		return ret;
1509 	}
1510 	if (!strlist__has_entry(namelist, buf))
1511 		return 0;
1512 
1513 	if (!allow_suffix) {
1514 		pr_warning("Error: event \"%s\" already exists. "
1515 			   "(Use -f to force duplicates.)\n", base);
1516 		return -EEXIST;
1517 	}
1518 
1519 	/* Try to add suffix */
1520 	for (i = 1; i < MAX_EVENT_INDEX; i++) {
1521 		ret = e_snprintf(buf, len, "%s_%d", base, i);
1522 		if (ret < 0) {
1523 			pr_debug("snprintf() failed: %s\n", strerror(-ret));
1524 			return ret;
1525 		}
1526 		if (!strlist__has_entry(namelist, buf))
1527 			break;
1528 	}
1529 	if (i == MAX_EVENT_INDEX) {
1530 		pr_warning("Too many events are on the same function.\n");
1531 		ret = -ERANGE;
1532 	}
1533 
1534 	return ret;
1535 }
1536 
1537 static int __add_probe_trace_events(struct perf_probe_event *pev,
1538 				     struct probe_trace_event *tevs,
1539 				     int ntevs, bool allow_suffix)
1540 {
1541 	int i, fd, ret;
1542 	struct probe_trace_event *tev = NULL;
1543 	char buf[64];
1544 	const char *event, *group;
1545 	struct strlist *namelist;
1546 
1547 	fd = open_kprobe_events(true);
1548 	if (fd < 0)
1549 		return fd;
1550 	/* Get current event names */
1551 	namelist = get_probe_trace_event_names(fd, false);
1552 	if (!namelist) {
1553 		pr_debug("Failed to get current event list.\n");
1554 		return -EIO;
1555 	}
1556 
1557 	ret = 0;
1558 	printf("Add new event%s\n", (ntevs > 1) ? "s:" : ":");
1559 	for (i = 0; i < ntevs; i++) {
1560 		tev = &tevs[i];
1561 		if (pev->event)
1562 			event = pev->event;
1563 		else
1564 			if (pev->point.function)
1565 				event = pev->point.function;
1566 			else
1567 				event = tev->point.symbol;
1568 		if (pev->group)
1569 			group = pev->group;
1570 		else
1571 			group = PERFPROBE_GROUP;
1572 
1573 		/* Get an unused new event name */
1574 		ret = get_new_event_name(buf, 64, event,
1575 					 namelist, allow_suffix);
1576 		if (ret < 0)
1577 			break;
1578 		event = buf;
1579 
1580 		tev->event = strdup(event);
1581 		tev->group = strdup(group);
1582 		if (tev->event == NULL || tev->group == NULL) {
1583 			ret = -ENOMEM;
1584 			break;
1585 		}
1586 		ret = write_probe_trace_event(fd, tev);
1587 		if (ret < 0)
1588 			break;
1589 		/* Add added event name to namelist */
1590 		strlist__add(namelist, event);
1591 
1592 		/* Trick here - save current event/group */
1593 		event = pev->event;
1594 		group = pev->group;
1595 		pev->event = tev->event;
1596 		pev->group = tev->group;
1597 		show_perf_probe_event(pev);
1598 		/* Trick here - restore current event/group */
1599 		pev->event = (char *)event;
1600 		pev->group = (char *)group;
1601 
1602 		/*
1603 		 * Probes after the first probe which comes from same
1604 		 * user input are always allowed to add suffix, because
1605 		 * there might be several addresses corresponding to
1606 		 * one code line.
1607 		 */
1608 		allow_suffix = true;
1609 	}
1610 
1611 	if (ret >= 0) {
1612 		/* Show how to use the event. */
1613 		printf("\nYou can now use it on all perf tools, such as:\n\n");
1614 		printf("\tperf record -e %s:%s -aR sleep 1\n\n", tev->group,
1615 			 tev->event);
1616 	}
1617 
1618 	strlist__delete(namelist);
1619 	close(fd);
1620 	return ret;
1621 }
1622 
1623 static int convert_to_probe_trace_events(struct perf_probe_event *pev,
1624 					  struct probe_trace_event **tevs,
1625 					  int max_tevs, const char *module)
1626 {
1627 	struct symbol *sym;
1628 	int ret = 0, i;
1629 	struct probe_trace_event *tev;
1630 
1631 	/* Convert perf_probe_event with debuginfo */
1632 	ret = try_to_find_probe_trace_events(pev, tevs, max_tevs, module);
1633 	if (ret != 0)
1634 		return ret;
1635 
1636 	/* Allocate trace event buffer */
1637 	tev = *tevs = zalloc(sizeof(struct probe_trace_event));
1638 	if (tev == NULL)
1639 		return -ENOMEM;
1640 
1641 	/* Copy parameters */
1642 	tev->point.symbol = strdup(pev->point.function);
1643 	if (tev->point.symbol == NULL) {
1644 		ret = -ENOMEM;
1645 		goto error;
1646 	}
1647 	tev->point.offset = pev->point.offset;
1648 	tev->point.retprobe = pev->point.retprobe;
1649 	tev->nargs = pev->nargs;
1650 	if (tev->nargs) {
1651 		tev->args = zalloc(sizeof(struct probe_trace_arg)
1652 				   * tev->nargs);
1653 		if (tev->args == NULL) {
1654 			ret = -ENOMEM;
1655 			goto error;
1656 		}
1657 		for (i = 0; i < tev->nargs; i++) {
1658 			if (pev->args[i].name) {
1659 				tev->args[i].name = strdup(pev->args[i].name);
1660 				if (tev->args[i].name == NULL) {
1661 					ret = -ENOMEM;
1662 					goto error;
1663 				}
1664 			}
1665 			tev->args[i].value = strdup(pev->args[i].var);
1666 			if (tev->args[i].value == NULL) {
1667 				ret = -ENOMEM;
1668 				goto error;
1669 			}
1670 			if (pev->args[i].type) {
1671 				tev->args[i].type = strdup(pev->args[i].type);
1672 				if (tev->args[i].type == NULL) {
1673 					ret = -ENOMEM;
1674 					goto error;
1675 				}
1676 			}
1677 		}
1678 	}
1679 
1680 	/* Currently just checking function name from symbol map */
1681 	sym = __find_kernel_function_by_name(tev->point.symbol, NULL);
1682 	if (!sym) {
1683 		pr_warning("Kernel symbol \'%s\' not found.\n",
1684 			   tev->point.symbol);
1685 		ret = -ENOENT;
1686 		goto error;
1687 	}
1688 
1689 	return 1;
1690 error:
1691 	clear_probe_trace_event(tev);
1692 	free(tev);
1693 	*tevs = NULL;
1694 	return ret;
1695 }
1696 
1697 struct __event_package {
1698 	struct perf_probe_event		*pev;
1699 	struct probe_trace_event	*tevs;
1700 	int				ntevs;
1701 };
1702 
1703 int add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
1704 			  int max_tevs, const char *module, bool force_add)
1705 {
1706 	int i, j, ret;
1707 	struct __event_package *pkgs;
1708 
1709 	pkgs = zalloc(sizeof(struct __event_package) * npevs);
1710 	if (pkgs == NULL)
1711 		return -ENOMEM;
1712 
1713 	/* Init vmlinux path */
1714 	ret = init_vmlinux();
1715 	if (ret < 0) {
1716 		free(pkgs);
1717 		return ret;
1718 	}
1719 
1720 	/* Loop 1: convert all events */
1721 	for (i = 0; i < npevs; i++) {
1722 		pkgs[i].pev = &pevs[i];
1723 		/* Convert with or without debuginfo */
1724 		ret  = convert_to_probe_trace_events(pkgs[i].pev,
1725 						     &pkgs[i].tevs,
1726 						     max_tevs,
1727 						     module);
1728 		if (ret < 0)
1729 			goto end;
1730 		pkgs[i].ntevs = ret;
1731 	}
1732 
1733 	/* Loop 2: add all events */
1734 	for (i = 0; i < npevs && ret >= 0; i++)
1735 		ret = __add_probe_trace_events(pkgs[i].pev, pkgs[i].tevs,
1736 						pkgs[i].ntevs, force_add);
1737 end:
1738 	/* Loop 3: cleanup and free trace events  */
1739 	for (i = 0; i < npevs; i++) {
1740 		for (j = 0; j < pkgs[i].ntevs; j++)
1741 			clear_probe_trace_event(&pkgs[i].tevs[j]);
1742 		free(pkgs[i].tevs);
1743 	}
1744 	free(pkgs);
1745 
1746 	return ret;
1747 }
1748 
1749 static int __del_trace_probe_event(int fd, struct str_node *ent)
1750 {
1751 	char *p;
1752 	char buf[128];
1753 	int ret;
1754 
1755 	/* Convert from perf-probe event to trace-probe event */
1756 	ret = e_snprintf(buf, 128, "-:%s", ent->s);
1757 	if (ret < 0)
1758 		goto error;
1759 
1760 	p = strchr(buf + 2, ':');
1761 	if (!p) {
1762 		pr_debug("Internal error: %s should have ':' but not.\n",
1763 			 ent->s);
1764 		ret = -ENOTSUP;
1765 		goto error;
1766 	}
1767 	*p = '/';
1768 
1769 	pr_debug("Writing event: %s\n", buf);
1770 	ret = write(fd, buf, strlen(buf));
1771 	if (ret < 0)
1772 		goto error;
1773 
1774 	printf("Remove event: %s\n", ent->s);
1775 	return 0;
1776 error:
1777 	pr_warning("Failed to delete event: %s\n", strerror(-ret));
1778 	return ret;
1779 }
1780 
1781 static int del_trace_probe_event(int fd, const char *group,
1782 				  const char *event, struct strlist *namelist)
1783 {
1784 	char buf[128];
1785 	struct str_node *ent, *n;
1786 	int found = 0, ret = 0;
1787 
1788 	ret = e_snprintf(buf, 128, "%s:%s", group, event);
1789 	if (ret < 0) {
1790 		pr_err("Failed to copy event.");
1791 		return ret;
1792 	}
1793 
1794 	if (strpbrk(buf, "*?")) { /* Glob-exp */
1795 		strlist__for_each_safe(ent, n, namelist)
1796 			if (strglobmatch(ent->s, buf)) {
1797 				found++;
1798 				ret = __del_trace_probe_event(fd, ent);
1799 				if (ret < 0)
1800 					break;
1801 				strlist__remove(namelist, ent);
1802 			}
1803 	} else {
1804 		ent = strlist__find(namelist, buf);
1805 		if (ent) {
1806 			found++;
1807 			ret = __del_trace_probe_event(fd, ent);
1808 			if (ret >= 0)
1809 				strlist__remove(namelist, ent);
1810 		}
1811 	}
1812 	if (found == 0 && ret >= 0)
1813 		pr_info("Info: Event \"%s\" does not exist.\n", buf);
1814 
1815 	return ret;
1816 }
1817 
1818 int del_perf_probe_events(struct strlist *dellist)
1819 {
1820 	int fd, ret = 0;
1821 	const char *group, *event;
1822 	char *p, *str;
1823 	struct str_node *ent;
1824 	struct strlist *namelist;
1825 
1826 	fd = open_kprobe_events(true);
1827 	if (fd < 0)
1828 		return fd;
1829 
1830 	/* Get current event names */
1831 	namelist = get_probe_trace_event_names(fd, true);
1832 	if (namelist == NULL)
1833 		return -EINVAL;
1834 
1835 	strlist__for_each(ent, dellist) {
1836 		str = strdup(ent->s);
1837 		if (str == NULL) {
1838 			ret = -ENOMEM;
1839 			break;
1840 		}
1841 		pr_debug("Parsing: %s\n", str);
1842 		p = strchr(str, ':');
1843 		if (p) {
1844 			group = str;
1845 			*p = '\0';
1846 			event = p + 1;
1847 		} else {
1848 			group = "*";
1849 			event = str;
1850 		}
1851 		pr_debug("Group: %s, Event: %s\n", group, event);
1852 		ret = del_trace_probe_event(fd, group, event, namelist);
1853 		free(str);
1854 		if (ret < 0)
1855 			break;
1856 	}
1857 	strlist__delete(namelist);
1858 	close(fd);
1859 
1860 	return ret;
1861 }
1862 
1863