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