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