xref: /openbmc/linux/tools/perf/util/probe-event.c (revision 4a44a19b)
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 <api/fs/debugfs.h>
44 #include "trace-event.h"	/* For __maybe_unused */
45 #include "probe-event.h"
46 #include "probe-finder.h"
47 #include "session.h"
48 
49 #define MAX_CMDLEN 256
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 void clear_probe_trace_event(struct probe_trace_event *tev);
74 static struct machine *host_machine;
75 
76 /* Initialize symbol maps and path of vmlinux/modules */
77 static int init_symbol_maps(bool user_only)
78 {
79 	int ret;
80 
81 	symbol_conf.sort_by_name = true;
82 	ret = symbol__init(NULL);
83 	if (ret < 0) {
84 		pr_debug("Failed to init symbol map.\n");
85 		goto out;
86 	}
87 
88 	if (host_machine || user_only)	/* already initialized */
89 		return 0;
90 
91 	if (symbol_conf.vmlinux_name)
92 		pr_debug("Use vmlinux: %s\n", symbol_conf.vmlinux_name);
93 
94 	host_machine = machine__new_host();
95 	if (!host_machine) {
96 		pr_debug("machine__new_host() failed.\n");
97 		symbol__exit();
98 		ret = -1;
99 	}
100 out:
101 	if (ret < 0)
102 		pr_warning("Failed to init vmlinux path.\n");
103 	return ret;
104 }
105 
106 static void exit_symbol_maps(void)
107 {
108 	if (host_machine) {
109 		machine__delete(host_machine);
110 		host_machine = NULL;
111 	}
112 	symbol__exit();
113 }
114 
115 static struct symbol *__find_kernel_function_by_name(const char *name,
116 						     struct map **mapp)
117 {
118 	return machine__find_kernel_function_by_name(host_machine, name, mapp,
119 						     NULL);
120 }
121 
122 static struct symbol *__find_kernel_function(u64 addr, struct map **mapp)
123 {
124 	return machine__find_kernel_function(host_machine, addr, mapp, NULL);
125 }
126 
127 static struct ref_reloc_sym *kernel_get_ref_reloc_sym(void)
128 {
129 	/* kmap->ref_reloc_sym should be set if host_machine is initialized */
130 	struct kmap *kmap;
131 
132 	if (map__load(host_machine->vmlinux_maps[MAP__FUNCTION], NULL) < 0)
133 		return NULL;
134 
135 	kmap = map__kmap(host_machine->vmlinux_maps[MAP__FUNCTION]);
136 	return kmap->ref_reloc_sym;
137 }
138 
139 static u64 kernel_get_symbol_address_by_name(const char *name, bool reloc)
140 {
141 	struct ref_reloc_sym *reloc_sym;
142 	struct symbol *sym;
143 	struct map *map;
144 
145 	/* ref_reloc_sym is just a label. Need a special fix*/
146 	reloc_sym = kernel_get_ref_reloc_sym();
147 	if (reloc_sym && strcmp(name, reloc_sym->name) == 0)
148 		return (reloc) ? reloc_sym->addr : reloc_sym->unrelocated_addr;
149 	else {
150 		sym = __find_kernel_function_by_name(name, &map);
151 		if (sym)
152 			return map->unmap_ip(map, sym->start) -
153 				(reloc) ? 0 : map->reloc;
154 	}
155 	return 0;
156 }
157 
158 static struct map *kernel_get_module_map(const char *module)
159 {
160 	struct rb_node *nd;
161 	struct map_groups *grp = &host_machine->kmaps;
162 
163 	/* A file path -- this is an offline module */
164 	if (module && strchr(module, '/'))
165 		return machine__new_module(host_machine, 0, module);
166 
167 	if (!module)
168 		module = "kernel";
169 
170 	for (nd = rb_first(&grp->maps[MAP__FUNCTION]); nd; nd = rb_next(nd)) {
171 		struct map *pos = rb_entry(nd, struct map, rb_node);
172 		if (strncmp(pos->dso->short_name + 1, module,
173 			    pos->dso->short_name_len - 2) == 0) {
174 			return pos;
175 		}
176 	}
177 	return NULL;
178 }
179 
180 static struct dso *kernel_get_module_dso(const char *module)
181 {
182 	struct dso *dso;
183 	struct map *map;
184 	const char *vmlinux_name;
185 
186 	if (module) {
187 		list_for_each_entry(dso, &host_machine->kernel_dsos.head,
188 				    node) {
189 			if (strncmp(dso->short_name + 1, module,
190 				    dso->short_name_len - 2) == 0)
191 				goto found;
192 		}
193 		pr_debug("Failed to find module %s.\n", module);
194 		return NULL;
195 	}
196 
197 	map = host_machine->vmlinux_maps[MAP__FUNCTION];
198 	dso = map->dso;
199 
200 	vmlinux_name = symbol_conf.vmlinux_name;
201 	if (vmlinux_name) {
202 		if (dso__load_vmlinux(dso, map, vmlinux_name, false, NULL) <= 0)
203 			return NULL;
204 	} else {
205 		if (dso__load_vmlinux_path(dso, map, NULL) <= 0) {
206 			pr_debug("Failed to load kernel map.\n");
207 			return NULL;
208 		}
209 	}
210 found:
211 	return dso;
212 }
213 
214 const char *kernel_get_module_path(const char *module)
215 {
216 	struct dso *dso = kernel_get_module_dso(module);
217 	return (dso) ? dso->long_name : NULL;
218 }
219 
220 static int convert_exec_to_group(const char *exec, char **result)
221 {
222 	char *ptr1, *ptr2, *exec_copy;
223 	char buf[64];
224 	int ret;
225 
226 	exec_copy = strdup(exec);
227 	if (!exec_copy)
228 		return -ENOMEM;
229 
230 	ptr1 = basename(exec_copy);
231 	if (!ptr1) {
232 		ret = -EINVAL;
233 		goto out;
234 	}
235 
236 	ptr2 = strpbrk(ptr1, "-._");
237 	if (ptr2)
238 		*ptr2 = '\0';
239 	ret = e_snprintf(buf, 64, "%s_%s", PERFPROBE_GROUP, ptr1);
240 	if (ret < 0)
241 		goto out;
242 
243 	*result = strdup(buf);
244 	ret = *result ? 0 : -ENOMEM;
245 
246 out:
247 	free(exec_copy);
248 	return ret;
249 }
250 
251 static void clear_probe_trace_events(struct probe_trace_event *tevs, int ntevs)
252 {
253 	int i;
254 
255 	for (i = 0; i < ntevs; i++)
256 		clear_probe_trace_event(tevs + i);
257 }
258 
259 #ifdef HAVE_DWARF_SUPPORT
260 
261 /* Open new debuginfo of given module */
262 static struct debuginfo *open_debuginfo(const char *module, bool silent)
263 {
264 	const char *path = module;
265 	struct debuginfo *ret;
266 
267 	if (!module || !strchr(module, '/')) {
268 		path = kernel_get_module_path(module);
269 		if (!path) {
270 			if (!silent)
271 				pr_err("Failed to find path of %s module.\n",
272 				       module ?: "kernel");
273 			return NULL;
274 		}
275 	}
276 	ret = debuginfo__new(path);
277 	if (!ret && !silent) {
278 		pr_warning("The %s file has no debug information.\n", path);
279 		if (!module || !strtailcmp(path, ".ko"))
280 			pr_warning("Rebuild with CONFIG_DEBUG_INFO=y, ");
281 		else
282 			pr_warning("Rebuild with -g, ");
283 		pr_warning("or install an appropriate debuginfo package.\n");
284 	}
285 	return ret;
286 }
287 
288 
289 static int get_text_start_address(const char *exec, unsigned long *address)
290 {
291 	Elf *elf;
292 	GElf_Ehdr ehdr;
293 	GElf_Shdr shdr;
294 	int fd, ret = -ENOENT;
295 
296 	fd = open(exec, O_RDONLY);
297 	if (fd < 0)
298 		return -errno;
299 
300 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
301 	if (elf == NULL)
302 		return -EINVAL;
303 
304 	if (gelf_getehdr(elf, &ehdr) == NULL)
305 		goto out;
306 
307 	if (!elf_section_by_name(elf, &ehdr, &shdr, ".text", NULL))
308 		goto out;
309 
310 	*address = shdr.sh_addr - shdr.sh_offset;
311 	ret = 0;
312 out:
313 	elf_end(elf);
314 	return ret;
315 }
316 
317 /*
318  * Convert trace point to probe point with debuginfo
319  */
320 static int find_perf_probe_point_from_dwarf(struct probe_trace_point *tp,
321 					    struct perf_probe_point *pp,
322 					    bool is_kprobe)
323 {
324 	struct debuginfo *dinfo = NULL;
325 	unsigned long stext = 0;
326 	u64 addr = tp->address;
327 	int ret = -ENOENT;
328 
329 	/* convert the address to dwarf address */
330 	if (!is_kprobe) {
331 		if (!addr) {
332 			ret = -EINVAL;
333 			goto error;
334 		}
335 		ret = get_text_start_address(tp->module, &stext);
336 		if (ret < 0)
337 			goto error;
338 		addr += stext;
339 	} else {
340 		addr = kernel_get_symbol_address_by_name(tp->symbol, false);
341 		if (addr == 0)
342 			goto error;
343 		addr += tp->offset;
344 	}
345 
346 	pr_debug("try to find information at %" PRIx64 " in %s\n", addr,
347 		 tp->module ? : "kernel");
348 
349 	dinfo = open_debuginfo(tp->module, verbose == 0);
350 	if (dinfo) {
351 		ret = debuginfo__find_probe_point(dinfo,
352 						 (unsigned long)addr, pp);
353 		debuginfo__delete(dinfo);
354 	} else
355 		ret = -ENOENT;
356 
357 	if (ret > 0) {
358 		pp->retprobe = tp->retprobe;
359 		return 0;
360 	}
361 error:
362 	pr_debug("Failed to find corresponding probes from debuginfo.\n");
363 	return ret ? : -ENOENT;
364 }
365 
366 static int add_exec_to_probe_trace_events(struct probe_trace_event *tevs,
367 					  int ntevs, const char *exec)
368 {
369 	int i, ret = 0;
370 	unsigned long stext = 0;
371 
372 	if (!exec)
373 		return 0;
374 
375 	ret = get_text_start_address(exec, &stext);
376 	if (ret < 0)
377 		return ret;
378 
379 	for (i = 0; i < ntevs && ret >= 0; i++) {
380 		/* point.address is the addres of point.symbol + point.offset */
381 		tevs[i].point.address -= stext;
382 		tevs[i].point.module = strdup(exec);
383 		if (!tevs[i].point.module) {
384 			ret = -ENOMEM;
385 			break;
386 		}
387 		tevs[i].uprobes = true;
388 	}
389 
390 	return ret;
391 }
392 
393 static int add_module_to_probe_trace_events(struct probe_trace_event *tevs,
394 					    int ntevs, const char *module)
395 {
396 	int i, ret = 0;
397 	char *tmp;
398 
399 	if (!module)
400 		return 0;
401 
402 	tmp = strrchr(module, '/');
403 	if (tmp) {
404 		/* This is a module path -- get the module name */
405 		module = strdup(tmp + 1);
406 		if (!module)
407 			return -ENOMEM;
408 		tmp = strchr(module, '.');
409 		if (tmp)
410 			*tmp = '\0';
411 		tmp = (char *)module;	/* For free() */
412 	}
413 
414 	for (i = 0; i < ntevs; i++) {
415 		tevs[i].point.module = strdup(module);
416 		if (!tevs[i].point.module) {
417 			ret = -ENOMEM;
418 			break;
419 		}
420 	}
421 
422 	free(tmp);
423 	return ret;
424 }
425 
426 /* Post processing the probe events */
427 static int post_process_probe_trace_events(struct probe_trace_event *tevs,
428 					   int ntevs, const char *module,
429 					   bool uprobe)
430 {
431 	struct ref_reloc_sym *reloc_sym;
432 	char *tmp;
433 	int i;
434 
435 	if (uprobe)
436 		return add_exec_to_probe_trace_events(tevs, ntevs, module);
437 
438 	/* Note that currently ref_reloc_sym based probe is not for drivers */
439 	if (module)
440 		return add_module_to_probe_trace_events(tevs, ntevs, module);
441 
442 	reloc_sym = kernel_get_ref_reloc_sym();
443 	if (!reloc_sym) {
444 		pr_warning("Relocated base symbol is not found!\n");
445 		return -EINVAL;
446 	}
447 
448 	for (i = 0; i < ntevs; i++) {
449 		if (tevs[i].point.address) {
450 			tmp = strdup(reloc_sym->name);
451 			if (!tmp)
452 				return -ENOMEM;
453 			free(tevs[i].point.symbol);
454 			tevs[i].point.symbol = tmp;
455 			tevs[i].point.offset = tevs[i].point.address -
456 					       reloc_sym->unrelocated_addr;
457 		}
458 	}
459 	return 0;
460 }
461 
462 /* Try to find perf_probe_event with debuginfo */
463 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
464 					  struct probe_trace_event **tevs,
465 					  int max_tevs, const char *target)
466 {
467 	bool need_dwarf = perf_probe_event_need_dwarf(pev);
468 	struct debuginfo *dinfo;
469 	int ntevs, ret = 0;
470 
471 	dinfo = open_debuginfo(target, !need_dwarf);
472 
473 	if (!dinfo) {
474 		if (need_dwarf)
475 			return -ENOENT;
476 		pr_debug("Could not open debuginfo. Try to use symbols.\n");
477 		return 0;
478 	}
479 
480 	pr_debug("Try to find probe point from debuginfo.\n");
481 	/* Searching trace events corresponding to a probe event */
482 	ntevs = debuginfo__find_trace_events(dinfo, pev, tevs, max_tevs);
483 
484 	debuginfo__delete(dinfo);
485 
486 	if (ntevs > 0) {	/* Succeeded to find trace events */
487 		pr_debug("Found %d probe_trace_events.\n", ntevs);
488 		ret = post_process_probe_trace_events(*tevs, ntevs,
489 							target, pev->uprobes);
490 		if (ret < 0) {
491 			clear_probe_trace_events(*tevs, ntevs);
492 			zfree(tevs);
493 		}
494 		return ret < 0 ? ret : ntevs;
495 	}
496 
497 	if (ntevs == 0)	{	/* No error but failed to find probe point. */
498 		pr_warning("Probe point '%s' not found.\n",
499 			   synthesize_perf_probe_point(&pev->point));
500 		return -ENOENT;
501 	}
502 	/* Error path : ntevs < 0 */
503 	pr_debug("An error occurred in debuginfo analysis (%d).\n", ntevs);
504 	if (ntevs == -EBADF) {
505 		pr_warning("Warning: No dwarf info found in the vmlinux - "
506 			"please rebuild kernel with CONFIG_DEBUG_INFO=y.\n");
507 		if (!need_dwarf) {
508 			pr_debug("Trying to use symbols.\n");
509 			return 0;
510 		}
511 	}
512 	return ntevs;
513 }
514 
515 /*
516  * Find a src file from a DWARF tag path. Prepend optional source path prefix
517  * and chop off leading directories that do not exist. Result is passed back as
518  * a newly allocated path on success.
519  * Return 0 if file was found and readable, -errno otherwise.
520  */
521 static int get_real_path(const char *raw_path, const char *comp_dir,
522 			 char **new_path)
523 {
524 	const char *prefix = symbol_conf.source_prefix;
525 
526 	if (!prefix) {
527 		if (raw_path[0] != '/' && comp_dir)
528 			/* If not an absolute path, try to use comp_dir */
529 			prefix = comp_dir;
530 		else {
531 			if (access(raw_path, R_OK) == 0) {
532 				*new_path = strdup(raw_path);
533 				return 0;
534 			} else
535 				return -errno;
536 		}
537 	}
538 
539 	*new_path = malloc((strlen(prefix) + strlen(raw_path) + 2));
540 	if (!*new_path)
541 		return -ENOMEM;
542 
543 	for (;;) {
544 		sprintf(*new_path, "%s/%s", prefix, raw_path);
545 
546 		if (access(*new_path, R_OK) == 0)
547 			return 0;
548 
549 		if (!symbol_conf.source_prefix)
550 			/* In case of searching comp_dir, don't retry */
551 			return -errno;
552 
553 		switch (errno) {
554 		case ENAMETOOLONG:
555 		case ENOENT:
556 		case EROFS:
557 		case EFAULT:
558 			raw_path = strchr(++raw_path, '/');
559 			if (!raw_path) {
560 				zfree(new_path);
561 				return -ENOENT;
562 			}
563 			continue;
564 
565 		default:
566 			zfree(new_path);
567 			return -errno;
568 		}
569 	}
570 }
571 
572 #define LINEBUF_SIZE 256
573 #define NR_ADDITIONAL_LINES 2
574 
575 static int __show_one_line(FILE *fp, int l, bool skip, bool show_num)
576 {
577 	char buf[LINEBUF_SIZE], sbuf[STRERR_BUFSIZE];
578 	const char *color = show_num ? "" : PERF_COLOR_BLUE;
579 	const char *prefix = NULL;
580 
581 	do {
582 		if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
583 			goto error;
584 		if (skip)
585 			continue;
586 		if (!prefix) {
587 			prefix = show_num ? "%7d  " : "         ";
588 			color_fprintf(stdout, color, prefix, l);
589 		}
590 		color_fprintf(stdout, color, "%s", buf);
591 
592 	} while (strchr(buf, '\n') == NULL);
593 
594 	return 1;
595 error:
596 	if (ferror(fp)) {
597 		pr_warning("File read error: %s\n",
598 			   strerror_r(errno, sbuf, sizeof(sbuf)));
599 		return -1;
600 	}
601 	return 0;
602 }
603 
604 static int _show_one_line(FILE *fp, int l, bool skip, bool show_num)
605 {
606 	int rv = __show_one_line(fp, l, skip, show_num);
607 	if (rv == 0) {
608 		pr_warning("Source file is shorter than expected.\n");
609 		rv = -1;
610 	}
611 	return rv;
612 }
613 
614 #define show_one_line_with_num(f,l)	_show_one_line(f,l,false,true)
615 #define show_one_line(f,l)		_show_one_line(f,l,false,false)
616 #define skip_one_line(f,l)		_show_one_line(f,l,true,false)
617 #define show_one_line_or_eof(f,l)	__show_one_line(f,l,false,false)
618 
619 /*
620  * Show line-range always requires debuginfo to find source file and
621  * line number.
622  */
623 static int __show_line_range(struct line_range *lr, const char *module)
624 {
625 	int l = 1;
626 	struct int_node *ln;
627 	struct debuginfo *dinfo;
628 	FILE *fp;
629 	int ret;
630 	char *tmp;
631 	char sbuf[STRERR_BUFSIZE];
632 
633 	/* Search a line range */
634 	dinfo = open_debuginfo(module, false);
635 	if (!dinfo)
636 		return -ENOENT;
637 
638 	ret = debuginfo__find_line_range(dinfo, lr);
639 	debuginfo__delete(dinfo);
640 	if (ret == 0 || ret == -ENOENT) {
641 		pr_warning("Specified source line is not found.\n");
642 		return -ENOENT;
643 	} else if (ret < 0) {
644 		pr_warning("Debuginfo analysis failed.\n");
645 		return ret;
646 	}
647 
648 	/* Convert source file path */
649 	tmp = lr->path;
650 	ret = get_real_path(tmp, lr->comp_dir, &lr->path);
651 	free(tmp);	/* Free old path */
652 	if (ret < 0) {
653 		pr_warning("Failed to find source file path.\n");
654 		return ret;
655 	}
656 
657 	setup_pager();
658 
659 	if (lr->function)
660 		fprintf(stdout, "<%s@%s:%d>\n", lr->function, lr->path,
661 			lr->start - lr->offset);
662 	else
663 		fprintf(stdout, "<%s:%d>\n", lr->path, lr->start);
664 
665 	fp = fopen(lr->path, "r");
666 	if (fp == NULL) {
667 		pr_warning("Failed to open %s: %s\n", lr->path,
668 			   strerror_r(errno, sbuf, sizeof(sbuf)));
669 		return -errno;
670 	}
671 	/* Skip to starting line number */
672 	while (l < lr->start) {
673 		ret = skip_one_line(fp, l++);
674 		if (ret < 0)
675 			goto end;
676 	}
677 
678 	intlist__for_each(ln, lr->line_list) {
679 		for (; ln->i > l; l++) {
680 			ret = show_one_line(fp, l - lr->offset);
681 			if (ret < 0)
682 				goto end;
683 		}
684 		ret = show_one_line_with_num(fp, l++ - lr->offset);
685 		if (ret < 0)
686 			goto end;
687 	}
688 
689 	if (lr->end == INT_MAX)
690 		lr->end = l + NR_ADDITIONAL_LINES;
691 	while (l <= lr->end) {
692 		ret = show_one_line_or_eof(fp, l++ - lr->offset);
693 		if (ret <= 0)
694 			break;
695 	}
696 end:
697 	fclose(fp);
698 	return ret;
699 }
700 
701 int show_line_range(struct line_range *lr, const char *module, bool user)
702 {
703 	int ret;
704 
705 	ret = init_symbol_maps(user);
706 	if (ret < 0)
707 		return ret;
708 	ret = __show_line_range(lr, module);
709 	exit_symbol_maps();
710 
711 	return ret;
712 }
713 
714 static int show_available_vars_at(struct debuginfo *dinfo,
715 				  struct perf_probe_event *pev,
716 				  int max_vls, struct strfilter *_filter,
717 				  bool externs)
718 {
719 	char *buf;
720 	int ret, i, nvars;
721 	struct str_node *node;
722 	struct variable_list *vls = NULL, *vl;
723 	const char *var;
724 
725 	buf = synthesize_perf_probe_point(&pev->point);
726 	if (!buf)
727 		return -EINVAL;
728 	pr_debug("Searching variables at %s\n", buf);
729 
730 	ret = debuginfo__find_available_vars_at(dinfo, pev, &vls,
731 						max_vls, externs);
732 	if (ret <= 0) {
733 		if (ret == 0 || ret == -ENOENT) {
734 			pr_err("Failed to find the address of %s\n", buf);
735 			ret = -ENOENT;
736 		} else
737 			pr_warning("Debuginfo analysis failed.\n");
738 		goto end;
739 	}
740 
741 	/* Some variables are found */
742 	fprintf(stdout, "Available variables at %s\n", buf);
743 	for (i = 0; i < ret; i++) {
744 		vl = &vls[i];
745 		/*
746 		 * A probe point might be converted to
747 		 * several trace points.
748 		 */
749 		fprintf(stdout, "\t@<%s+%lu>\n", vl->point.symbol,
750 			vl->point.offset);
751 		zfree(&vl->point.symbol);
752 		nvars = 0;
753 		if (vl->vars) {
754 			strlist__for_each(node, vl->vars) {
755 				var = strchr(node->s, '\t') + 1;
756 				if (strfilter__compare(_filter, var)) {
757 					fprintf(stdout, "\t\t%s\n", node->s);
758 					nvars++;
759 				}
760 			}
761 			strlist__delete(vl->vars);
762 		}
763 		if (nvars == 0)
764 			fprintf(stdout, "\t\t(No matched variables)\n");
765 	}
766 	free(vls);
767 end:
768 	free(buf);
769 	return ret;
770 }
771 
772 /* Show available variables on given probe point */
773 int show_available_vars(struct perf_probe_event *pevs, int npevs,
774 			int max_vls, const char *module,
775 			struct strfilter *_filter, bool externs)
776 {
777 	int i, ret = 0;
778 	struct debuginfo *dinfo;
779 
780 	ret = init_symbol_maps(pevs->uprobes);
781 	if (ret < 0)
782 		return ret;
783 
784 	dinfo = open_debuginfo(module, false);
785 	if (!dinfo) {
786 		ret = -ENOENT;
787 		goto out;
788 	}
789 
790 	setup_pager();
791 
792 	for (i = 0; i < npevs && ret >= 0; i++)
793 		ret = show_available_vars_at(dinfo, &pevs[i], max_vls, _filter,
794 					     externs);
795 
796 	debuginfo__delete(dinfo);
797 out:
798 	exit_symbol_maps();
799 	return ret;
800 }
801 
802 #else	/* !HAVE_DWARF_SUPPORT */
803 
804 static int
805 find_perf_probe_point_from_dwarf(struct probe_trace_point *tp __maybe_unused,
806 				 struct perf_probe_point *pp __maybe_unused,
807 				 bool is_kprobe __maybe_unused)
808 {
809 	return -ENOSYS;
810 }
811 
812 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
813 				struct probe_trace_event **tevs __maybe_unused,
814 				int max_tevs __maybe_unused,
815 				const char *target __maybe_unused)
816 {
817 	if (perf_probe_event_need_dwarf(pev)) {
818 		pr_warning("Debuginfo-analysis is not supported.\n");
819 		return -ENOSYS;
820 	}
821 
822 	return 0;
823 }
824 
825 int show_line_range(struct line_range *lr __maybe_unused,
826 		    const char *module __maybe_unused,
827 		    bool user __maybe_unused)
828 {
829 	pr_warning("Debuginfo-analysis is not supported.\n");
830 	return -ENOSYS;
831 }
832 
833 int show_available_vars(struct perf_probe_event *pevs __maybe_unused,
834 			int npevs __maybe_unused, int max_vls __maybe_unused,
835 			const char *module __maybe_unused,
836 			struct strfilter *filter __maybe_unused,
837 			bool externs __maybe_unused)
838 {
839 	pr_warning("Debuginfo-analysis is not supported.\n");
840 	return -ENOSYS;
841 }
842 #endif
843 
844 void line_range__clear(struct line_range *lr)
845 {
846 	free(lr->function);
847 	free(lr->file);
848 	free(lr->path);
849 	free(lr->comp_dir);
850 	intlist__delete(lr->line_list);
851 	memset(lr, 0, sizeof(*lr));
852 }
853 
854 int line_range__init(struct line_range *lr)
855 {
856 	memset(lr, 0, sizeof(*lr));
857 	lr->line_list = intlist__new(NULL);
858 	if (!lr->line_list)
859 		return -ENOMEM;
860 	else
861 		return 0;
862 }
863 
864 static int parse_line_num(char **ptr, int *val, const char *what)
865 {
866 	const char *start = *ptr;
867 
868 	errno = 0;
869 	*val = strtol(*ptr, ptr, 0);
870 	if (errno || *ptr == start) {
871 		semantic_error("'%s' is not a valid number.\n", what);
872 		return -EINVAL;
873 	}
874 	return 0;
875 }
876 
877 /*
878  * Stuff 'lr' according to the line range described by 'arg'.
879  * The line range syntax is described by:
880  *
881  *         SRC[:SLN[+NUM|-ELN]]
882  *         FNC[@SRC][:SLN[+NUM|-ELN]]
883  */
884 int parse_line_range_desc(const char *arg, struct line_range *lr)
885 {
886 	char *range, *file, *name = strdup(arg);
887 	int err;
888 
889 	if (!name)
890 		return -ENOMEM;
891 
892 	lr->start = 0;
893 	lr->end = INT_MAX;
894 
895 	range = strchr(name, ':');
896 	if (range) {
897 		*range++ = '\0';
898 
899 		err = parse_line_num(&range, &lr->start, "start line");
900 		if (err)
901 			goto err;
902 
903 		if (*range == '+' || *range == '-') {
904 			const char c = *range++;
905 
906 			err = parse_line_num(&range, &lr->end, "end line");
907 			if (err)
908 				goto err;
909 
910 			if (c == '+') {
911 				lr->end += lr->start;
912 				/*
913 				 * Adjust the number of lines here.
914 				 * If the number of lines == 1, the
915 				 * the end of line should be equal to
916 				 * the start of line.
917 				 */
918 				lr->end--;
919 			}
920 		}
921 
922 		pr_debug("Line range is %d to %d\n", lr->start, lr->end);
923 
924 		err = -EINVAL;
925 		if (lr->start > lr->end) {
926 			semantic_error("Start line must be smaller"
927 				       " than end line.\n");
928 			goto err;
929 		}
930 		if (*range != '\0') {
931 			semantic_error("Tailing with invalid str '%s'.\n", range);
932 			goto err;
933 		}
934 	}
935 
936 	file = strchr(name, '@');
937 	if (file) {
938 		*file = '\0';
939 		lr->file = strdup(++file);
940 		if (lr->file == NULL) {
941 			err = -ENOMEM;
942 			goto err;
943 		}
944 		lr->function = name;
945 	} else if (strchr(name, '.'))
946 		lr->file = name;
947 	else
948 		lr->function = name;
949 
950 	return 0;
951 err:
952 	free(name);
953 	return err;
954 }
955 
956 /* Check the name is good for event/group */
957 static bool check_event_name(const char *name)
958 {
959 	if (!isalpha(*name) && *name != '_')
960 		return false;
961 	while (*++name != '\0') {
962 		if (!isalpha(*name) && !isdigit(*name) && *name != '_')
963 			return false;
964 	}
965 	return true;
966 }
967 
968 /* Parse probepoint definition. */
969 static int parse_perf_probe_point(char *arg, struct perf_probe_event *pev)
970 {
971 	struct perf_probe_point *pp = &pev->point;
972 	char *ptr, *tmp;
973 	char c, nc = 0;
974 	/*
975 	 * <Syntax>
976 	 * perf probe [EVENT=]SRC[:LN|;PTN]
977 	 * perf probe [EVENT=]FUNC[@SRC][+OFFS|%return|:LN|;PAT]
978 	 *
979 	 * TODO:Group name support
980 	 */
981 
982 	ptr = strpbrk(arg, ";=@+%");
983 	if (ptr && *ptr == '=') {	/* Event name */
984 		*ptr = '\0';
985 		tmp = ptr + 1;
986 		if (strchr(arg, ':')) {
987 			semantic_error("Group name is not supported yet.\n");
988 			return -ENOTSUP;
989 		}
990 		if (!check_event_name(arg)) {
991 			semantic_error("%s is bad for event name -it must "
992 				       "follow C symbol-naming rule.\n", arg);
993 			return -EINVAL;
994 		}
995 		pev->event = strdup(arg);
996 		if (pev->event == NULL)
997 			return -ENOMEM;
998 		pev->group = NULL;
999 		arg = tmp;
1000 	}
1001 
1002 	ptr = strpbrk(arg, ";:+@%");
1003 	if (ptr) {
1004 		nc = *ptr;
1005 		*ptr++ = '\0';
1006 	}
1007 
1008 	tmp = strdup(arg);
1009 	if (tmp == NULL)
1010 		return -ENOMEM;
1011 
1012 	/* Check arg is function or file and copy it */
1013 	if (strchr(tmp, '.'))	/* File */
1014 		pp->file = tmp;
1015 	else			/* Function */
1016 		pp->function = tmp;
1017 
1018 	/* Parse other options */
1019 	while (ptr) {
1020 		arg = ptr;
1021 		c = nc;
1022 		if (c == ';') {	/* Lazy pattern must be the last part */
1023 			pp->lazy_line = strdup(arg);
1024 			if (pp->lazy_line == NULL)
1025 				return -ENOMEM;
1026 			break;
1027 		}
1028 		ptr = strpbrk(arg, ";:+@%");
1029 		if (ptr) {
1030 			nc = *ptr;
1031 			*ptr++ = '\0';
1032 		}
1033 		switch (c) {
1034 		case ':':	/* Line number */
1035 			pp->line = strtoul(arg, &tmp, 0);
1036 			if (*tmp != '\0') {
1037 				semantic_error("There is non-digit char"
1038 					       " in line number.\n");
1039 				return -EINVAL;
1040 			}
1041 			break;
1042 		case '+':	/* Byte offset from a symbol */
1043 			pp->offset = strtoul(arg, &tmp, 0);
1044 			if (*tmp != '\0') {
1045 				semantic_error("There is non-digit character"
1046 						" in offset.\n");
1047 				return -EINVAL;
1048 			}
1049 			break;
1050 		case '@':	/* File name */
1051 			if (pp->file) {
1052 				semantic_error("SRC@SRC is not allowed.\n");
1053 				return -EINVAL;
1054 			}
1055 			pp->file = strdup(arg);
1056 			if (pp->file == NULL)
1057 				return -ENOMEM;
1058 			break;
1059 		case '%':	/* Probe places */
1060 			if (strcmp(arg, "return") == 0) {
1061 				pp->retprobe = 1;
1062 			} else {	/* Others not supported yet */
1063 				semantic_error("%%%s is not supported.\n", arg);
1064 				return -ENOTSUP;
1065 			}
1066 			break;
1067 		default:	/* Buggy case */
1068 			pr_err("This program has a bug at %s:%d.\n",
1069 				__FILE__, __LINE__);
1070 			return -ENOTSUP;
1071 			break;
1072 		}
1073 	}
1074 
1075 	/* Exclusion check */
1076 	if (pp->lazy_line && pp->line) {
1077 		semantic_error("Lazy pattern can't be used with"
1078 			       " line number.\n");
1079 		return -EINVAL;
1080 	}
1081 
1082 	if (pp->lazy_line && pp->offset) {
1083 		semantic_error("Lazy pattern can't be used with offset.\n");
1084 		return -EINVAL;
1085 	}
1086 
1087 	if (pp->line && pp->offset) {
1088 		semantic_error("Offset can't be used with line number.\n");
1089 		return -EINVAL;
1090 	}
1091 
1092 	if (!pp->line && !pp->lazy_line && pp->file && !pp->function) {
1093 		semantic_error("File always requires line number or "
1094 			       "lazy pattern.\n");
1095 		return -EINVAL;
1096 	}
1097 
1098 	if (pp->offset && !pp->function) {
1099 		semantic_error("Offset requires an entry function.\n");
1100 		return -EINVAL;
1101 	}
1102 
1103 	if (pp->retprobe && !pp->function) {
1104 		semantic_error("Return probe requires an entry function.\n");
1105 		return -EINVAL;
1106 	}
1107 
1108 	if ((pp->offset || pp->line || pp->lazy_line) && pp->retprobe) {
1109 		semantic_error("Offset/Line/Lazy pattern can't be used with "
1110 			       "return probe.\n");
1111 		return -EINVAL;
1112 	}
1113 
1114 	pr_debug("symbol:%s file:%s line:%d offset:%lu return:%d lazy:%s\n",
1115 		 pp->function, pp->file, pp->line, pp->offset, pp->retprobe,
1116 		 pp->lazy_line);
1117 	return 0;
1118 }
1119 
1120 /* Parse perf-probe event argument */
1121 static int parse_perf_probe_arg(char *str, struct perf_probe_arg *arg)
1122 {
1123 	char *tmp, *goodname;
1124 	struct perf_probe_arg_field **fieldp;
1125 
1126 	pr_debug("parsing arg: %s into ", str);
1127 
1128 	tmp = strchr(str, '=');
1129 	if (tmp) {
1130 		arg->name = strndup(str, tmp - str);
1131 		if (arg->name == NULL)
1132 			return -ENOMEM;
1133 		pr_debug("name:%s ", arg->name);
1134 		str = tmp + 1;
1135 	}
1136 
1137 	tmp = strchr(str, ':');
1138 	if (tmp) {	/* Type setting */
1139 		*tmp = '\0';
1140 		arg->type = strdup(tmp + 1);
1141 		if (arg->type == NULL)
1142 			return -ENOMEM;
1143 		pr_debug("type:%s ", arg->type);
1144 	}
1145 
1146 	tmp = strpbrk(str, "-.[");
1147 	if (!is_c_varname(str) || !tmp) {
1148 		/* A variable, register, symbol or special value */
1149 		arg->var = strdup(str);
1150 		if (arg->var == NULL)
1151 			return -ENOMEM;
1152 		pr_debug("%s\n", arg->var);
1153 		return 0;
1154 	}
1155 
1156 	/* Structure fields or array element */
1157 	arg->var = strndup(str, tmp - str);
1158 	if (arg->var == NULL)
1159 		return -ENOMEM;
1160 	goodname = arg->var;
1161 	pr_debug("%s, ", arg->var);
1162 	fieldp = &arg->field;
1163 
1164 	do {
1165 		*fieldp = zalloc(sizeof(struct perf_probe_arg_field));
1166 		if (*fieldp == NULL)
1167 			return -ENOMEM;
1168 		if (*tmp == '[') {	/* Array */
1169 			str = tmp;
1170 			(*fieldp)->index = strtol(str + 1, &tmp, 0);
1171 			(*fieldp)->ref = true;
1172 			if (*tmp != ']' || tmp == str + 1) {
1173 				semantic_error("Array index must be a"
1174 						" number.\n");
1175 				return -EINVAL;
1176 			}
1177 			tmp++;
1178 			if (*tmp == '\0')
1179 				tmp = NULL;
1180 		} else {		/* Structure */
1181 			if (*tmp == '.') {
1182 				str = tmp + 1;
1183 				(*fieldp)->ref = false;
1184 			} else if (tmp[1] == '>') {
1185 				str = tmp + 2;
1186 				(*fieldp)->ref = true;
1187 			} else {
1188 				semantic_error("Argument parse error: %s\n",
1189 					       str);
1190 				return -EINVAL;
1191 			}
1192 			tmp = strpbrk(str, "-.[");
1193 		}
1194 		if (tmp) {
1195 			(*fieldp)->name = strndup(str, tmp - str);
1196 			if ((*fieldp)->name == NULL)
1197 				return -ENOMEM;
1198 			if (*str != '[')
1199 				goodname = (*fieldp)->name;
1200 			pr_debug("%s(%d), ", (*fieldp)->name, (*fieldp)->ref);
1201 			fieldp = &(*fieldp)->next;
1202 		}
1203 	} while (tmp);
1204 	(*fieldp)->name = strdup(str);
1205 	if ((*fieldp)->name == NULL)
1206 		return -ENOMEM;
1207 	if (*str != '[')
1208 		goodname = (*fieldp)->name;
1209 	pr_debug("%s(%d)\n", (*fieldp)->name, (*fieldp)->ref);
1210 
1211 	/* If no name is specified, set the last field name (not array index)*/
1212 	if (!arg->name) {
1213 		arg->name = strdup(goodname);
1214 		if (arg->name == NULL)
1215 			return -ENOMEM;
1216 	}
1217 	return 0;
1218 }
1219 
1220 /* Parse perf-probe event command */
1221 int parse_perf_probe_command(const char *cmd, struct perf_probe_event *pev)
1222 {
1223 	char **argv;
1224 	int argc, i, ret = 0;
1225 
1226 	argv = argv_split(cmd, &argc);
1227 	if (!argv) {
1228 		pr_debug("Failed to split arguments.\n");
1229 		return -ENOMEM;
1230 	}
1231 	if (argc - 1 > MAX_PROBE_ARGS) {
1232 		semantic_error("Too many probe arguments (%d).\n", argc - 1);
1233 		ret = -ERANGE;
1234 		goto out;
1235 	}
1236 	/* Parse probe point */
1237 	ret = parse_perf_probe_point(argv[0], pev);
1238 	if (ret < 0)
1239 		goto out;
1240 
1241 	/* Copy arguments and ensure return probe has no C argument */
1242 	pev->nargs = argc - 1;
1243 	pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1244 	if (pev->args == NULL) {
1245 		ret = -ENOMEM;
1246 		goto out;
1247 	}
1248 	for (i = 0; i < pev->nargs && ret >= 0; i++) {
1249 		ret = parse_perf_probe_arg(argv[i + 1], &pev->args[i]);
1250 		if (ret >= 0 &&
1251 		    is_c_varname(pev->args[i].var) && pev->point.retprobe) {
1252 			semantic_error("You can't specify local variable for"
1253 				       " kretprobe.\n");
1254 			ret = -EINVAL;
1255 		}
1256 	}
1257 out:
1258 	argv_free(argv);
1259 
1260 	return ret;
1261 }
1262 
1263 /* Return true if this perf_probe_event requires debuginfo */
1264 bool perf_probe_event_need_dwarf(struct perf_probe_event *pev)
1265 {
1266 	int i;
1267 
1268 	if (pev->point.file || pev->point.line || pev->point.lazy_line)
1269 		return true;
1270 
1271 	for (i = 0; i < pev->nargs; i++)
1272 		if (is_c_varname(pev->args[i].var))
1273 			return true;
1274 
1275 	return false;
1276 }
1277 
1278 /* Parse probe_events event into struct probe_point */
1279 static int parse_probe_trace_command(const char *cmd,
1280 				     struct probe_trace_event *tev)
1281 {
1282 	struct probe_trace_point *tp = &tev->point;
1283 	char pr;
1284 	char *p;
1285 	char *argv0_str = NULL, *fmt, *fmt1_str, *fmt2_str, *fmt3_str;
1286 	int ret, i, argc;
1287 	char **argv;
1288 
1289 	pr_debug("Parsing probe_events: %s\n", cmd);
1290 	argv = argv_split(cmd, &argc);
1291 	if (!argv) {
1292 		pr_debug("Failed to split arguments.\n");
1293 		return -ENOMEM;
1294 	}
1295 	if (argc < 2) {
1296 		semantic_error("Too few probe arguments.\n");
1297 		ret = -ERANGE;
1298 		goto out;
1299 	}
1300 
1301 	/* Scan event and group name. */
1302 	argv0_str = strdup(argv[0]);
1303 	if (argv0_str == NULL) {
1304 		ret = -ENOMEM;
1305 		goto out;
1306 	}
1307 	fmt1_str = strtok_r(argv0_str, ":", &fmt);
1308 	fmt2_str = strtok_r(NULL, "/", &fmt);
1309 	fmt3_str = strtok_r(NULL, " \t", &fmt);
1310 	if (fmt1_str == NULL || strlen(fmt1_str) != 1 || fmt2_str == NULL
1311 	    || fmt3_str == NULL) {
1312 		semantic_error("Failed to parse event name: %s\n", argv[0]);
1313 		ret = -EINVAL;
1314 		goto out;
1315 	}
1316 	pr = fmt1_str[0];
1317 	tev->group = strdup(fmt2_str);
1318 	tev->event = strdup(fmt3_str);
1319 	if (tev->group == NULL || tev->event == NULL) {
1320 		ret = -ENOMEM;
1321 		goto out;
1322 	}
1323 	pr_debug("Group:%s Event:%s probe:%c\n", tev->group, tev->event, pr);
1324 
1325 	tp->retprobe = (pr == 'r');
1326 
1327 	/* Scan module name(if there), function name and offset */
1328 	p = strchr(argv[1], ':');
1329 	if (p) {
1330 		tp->module = strndup(argv[1], p - argv[1]);
1331 		p++;
1332 	} else
1333 		p = argv[1];
1334 	fmt1_str = strtok_r(p, "+", &fmt);
1335 	if (fmt1_str[0] == '0')	/* only the address started with 0x */
1336 		tp->address = strtoul(fmt1_str, NULL, 0);
1337 	else {
1338 		/* Only the symbol-based probe has offset */
1339 		tp->symbol = strdup(fmt1_str);
1340 		if (tp->symbol == NULL) {
1341 			ret = -ENOMEM;
1342 			goto out;
1343 		}
1344 		fmt2_str = strtok_r(NULL, "", &fmt);
1345 		if (fmt2_str == NULL)
1346 			tp->offset = 0;
1347 		else
1348 			tp->offset = strtoul(fmt2_str, NULL, 10);
1349 	}
1350 
1351 	tev->nargs = argc - 2;
1352 	tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
1353 	if (tev->args == NULL) {
1354 		ret = -ENOMEM;
1355 		goto out;
1356 	}
1357 	for (i = 0; i < tev->nargs; i++) {
1358 		p = strchr(argv[i + 2], '=');
1359 		if (p)	/* We don't need which register is assigned. */
1360 			*p++ = '\0';
1361 		else
1362 			p = argv[i + 2];
1363 		tev->args[i].name = strdup(argv[i + 2]);
1364 		/* TODO: parse regs and offset */
1365 		tev->args[i].value = strdup(p);
1366 		if (tev->args[i].name == NULL || tev->args[i].value == NULL) {
1367 			ret = -ENOMEM;
1368 			goto out;
1369 		}
1370 	}
1371 	ret = 0;
1372 out:
1373 	free(argv0_str);
1374 	argv_free(argv);
1375 	return ret;
1376 }
1377 
1378 /* Compose only probe arg */
1379 int synthesize_perf_probe_arg(struct perf_probe_arg *pa, char *buf, size_t len)
1380 {
1381 	struct perf_probe_arg_field *field = pa->field;
1382 	int ret;
1383 	char *tmp = buf;
1384 
1385 	if (pa->name && pa->var)
1386 		ret = e_snprintf(tmp, len, "%s=%s", pa->name, pa->var);
1387 	else
1388 		ret = e_snprintf(tmp, len, "%s", pa->name ? pa->name : pa->var);
1389 	if (ret <= 0)
1390 		goto error;
1391 	tmp += ret;
1392 	len -= ret;
1393 
1394 	while (field) {
1395 		if (field->name[0] == '[')
1396 			ret = e_snprintf(tmp, len, "%s", field->name);
1397 		else
1398 			ret = e_snprintf(tmp, len, "%s%s",
1399 					 field->ref ? "->" : ".", field->name);
1400 		if (ret <= 0)
1401 			goto error;
1402 		tmp += ret;
1403 		len -= ret;
1404 		field = field->next;
1405 	}
1406 
1407 	if (pa->type) {
1408 		ret = e_snprintf(tmp, len, ":%s", pa->type);
1409 		if (ret <= 0)
1410 			goto error;
1411 		tmp += ret;
1412 		len -= ret;
1413 	}
1414 
1415 	return tmp - buf;
1416 error:
1417 	pr_debug("Failed to synthesize perf probe argument: %d\n", ret);
1418 	return ret;
1419 }
1420 
1421 /* Compose only probe point (not argument) */
1422 static char *synthesize_perf_probe_point(struct perf_probe_point *pp)
1423 {
1424 	char *buf, *tmp;
1425 	char offs[32] = "", line[32] = "", file[32] = "";
1426 	int ret, len;
1427 
1428 	buf = zalloc(MAX_CMDLEN);
1429 	if (buf == NULL) {
1430 		ret = -ENOMEM;
1431 		goto error;
1432 	}
1433 	if (pp->offset) {
1434 		ret = e_snprintf(offs, 32, "+%lu", pp->offset);
1435 		if (ret <= 0)
1436 			goto error;
1437 	}
1438 	if (pp->line) {
1439 		ret = e_snprintf(line, 32, ":%d", pp->line);
1440 		if (ret <= 0)
1441 			goto error;
1442 	}
1443 	if (pp->file) {
1444 		tmp = pp->file;
1445 		len = strlen(tmp);
1446 		if (len > 30) {
1447 			tmp = strchr(pp->file + len - 30, '/');
1448 			tmp = tmp ? tmp + 1 : pp->file + len - 30;
1449 		}
1450 		ret = e_snprintf(file, 32, "@%s", tmp);
1451 		if (ret <= 0)
1452 			goto error;
1453 	}
1454 
1455 	if (pp->function)
1456 		ret = e_snprintf(buf, MAX_CMDLEN, "%s%s%s%s%s", pp->function,
1457 				 offs, pp->retprobe ? "%return" : "", line,
1458 				 file);
1459 	else
1460 		ret = e_snprintf(buf, MAX_CMDLEN, "%s%s", file, line);
1461 	if (ret <= 0)
1462 		goto error;
1463 
1464 	return buf;
1465 error:
1466 	pr_debug("Failed to synthesize perf probe point: %d\n", ret);
1467 	free(buf);
1468 	return NULL;
1469 }
1470 
1471 #if 0
1472 char *synthesize_perf_probe_command(struct perf_probe_event *pev)
1473 {
1474 	char *buf;
1475 	int i, len, ret;
1476 
1477 	buf = synthesize_perf_probe_point(&pev->point);
1478 	if (!buf)
1479 		return NULL;
1480 
1481 	len = strlen(buf);
1482 	for (i = 0; i < pev->nargs; i++) {
1483 		ret = e_snprintf(&buf[len], MAX_CMDLEN - len, " %s",
1484 				 pev->args[i].name);
1485 		if (ret <= 0) {
1486 			free(buf);
1487 			return NULL;
1488 		}
1489 		len += ret;
1490 	}
1491 
1492 	return buf;
1493 }
1494 #endif
1495 
1496 static int __synthesize_probe_trace_arg_ref(struct probe_trace_arg_ref *ref,
1497 					     char **buf, size_t *buflen,
1498 					     int depth)
1499 {
1500 	int ret;
1501 	if (ref->next) {
1502 		depth = __synthesize_probe_trace_arg_ref(ref->next, buf,
1503 							 buflen, depth + 1);
1504 		if (depth < 0)
1505 			goto out;
1506 	}
1507 
1508 	ret = e_snprintf(*buf, *buflen, "%+ld(", ref->offset);
1509 	if (ret < 0)
1510 		depth = ret;
1511 	else {
1512 		*buf += ret;
1513 		*buflen -= ret;
1514 	}
1515 out:
1516 	return depth;
1517 
1518 }
1519 
1520 static int synthesize_probe_trace_arg(struct probe_trace_arg *arg,
1521 				       char *buf, size_t buflen)
1522 {
1523 	struct probe_trace_arg_ref *ref = arg->ref;
1524 	int ret, depth = 0;
1525 	char *tmp = buf;
1526 
1527 	/* Argument name or separator */
1528 	if (arg->name)
1529 		ret = e_snprintf(buf, buflen, " %s=", arg->name);
1530 	else
1531 		ret = e_snprintf(buf, buflen, " ");
1532 	if (ret < 0)
1533 		return ret;
1534 	buf += ret;
1535 	buflen -= ret;
1536 
1537 	/* Special case: @XXX */
1538 	if (arg->value[0] == '@' && arg->ref)
1539 			ref = ref->next;
1540 
1541 	/* Dereferencing arguments */
1542 	if (ref) {
1543 		depth = __synthesize_probe_trace_arg_ref(ref, &buf,
1544 							  &buflen, 1);
1545 		if (depth < 0)
1546 			return depth;
1547 	}
1548 
1549 	/* Print argument value */
1550 	if (arg->value[0] == '@' && arg->ref)
1551 		ret = e_snprintf(buf, buflen, "%s%+ld", arg->value,
1552 				 arg->ref->offset);
1553 	else
1554 		ret = e_snprintf(buf, buflen, "%s", arg->value);
1555 	if (ret < 0)
1556 		return ret;
1557 	buf += ret;
1558 	buflen -= ret;
1559 
1560 	/* Closing */
1561 	while (depth--) {
1562 		ret = e_snprintf(buf, buflen, ")");
1563 		if (ret < 0)
1564 			return ret;
1565 		buf += ret;
1566 		buflen -= ret;
1567 	}
1568 	/* Print argument type */
1569 	if (arg->type) {
1570 		ret = e_snprintf(buf, buflen, ":%s", arg->type);
1571 		if (ret <= 0)
1572 			return ret;
1573 		buf += ret;
1574 	}
1575 
1576 	return buf - tmp;
1577 }
1578 
1579 char *synthesize_probe_trace_command(struct probe_trace_event *tev)
1580 {
1581 	struct probe_trace_point *tp = &tev->point;
1582 	char *buf;
1583 	int i, len, ret;
1584 
1585 	buf = zalloc(MAX_CMDLEN);
1586 	if (buf == NULL)
1587 		return NULL;
1588 
1589 	len = e_snprintf(buf, MAX_CMDLEN, "%c:%s/%s ", tp->retprobe ? 'r' : 'p',
1590 			 tev->group, tev->event);
1591 	if (len <= 0)
1592 		goto error;
1593 
1594 	/* Uprobes must have tp->address and tp->module */
1595 	if (tev->uprobes && (!tp->address || !tp->module))
1596 		goto error;
1597 
1598 	/* Use the tp->address for uprobes */
1599 	if (tev->uprobes)
1600 		ret = e_snprintf(buf + len, MAX_CMDLEN - len, "%s:0x%lx",
1601 				 tp->module, tp->address);
1602 	else
1603 		ret = e_snprintf(buf + len, MAX_CMDLEN - len, "%s%s%s+%lu",
1604 				 tp->module ?: "", tp->module ? ":" : "",
1605 				 tp->symbol, tp->offset);
1606 
1607 	if (ret <= 0)
1608 		goto error;
1609 	len += ret;
1610 
1611 	for (i = 0; i < tev->nargs; i++) {
1612 		ret = synthesize_probe_trace_arg(&tev->args[i], buf + len,
1613 						  MAX_CMDLEN - len);
1614 		if (ret <= 0)
1615 			goto error;
1616 		len += ret;
1617 	}
1618 
1619 	return buf;
1620 error:
1621 	free(buf);
1622 	return NULL;
1623 }
1624 
1625 static int find_perf_probe_point_from_map(struct probe_trace_point *tp,
1626 					  struct perf_probe_point *pp,
1627 					  bool is_kprobe)
1628 {
1629 	struct symbol *sym = NULL;
1630 	struct map *map;
1631 	u64 addr;
1632 	int ret = -ENOENT;
1633 
1634 	if (!is_kprobe) {
1635 		map = dso__new_map(tp->module);
1636 		if (!map)
1637 			goto out;
1638 		addr = tp->address;
1639 		sym = map__find_symbol(map, addr, NULL);
1640 	} else {
1641 		addr = kernel_get_symbol_address_by_name(tp->symbol, true);
1642 		if (addr) {
1643 			addr += tp->offset;
1644 			sym = __find_kernel_function(addr, &map);
1645 		}
1646 	}
1647 	if (!sym)
1648 		goto out;
1649 
1650 	pp->retprobe = tp->retprobe;
1651 	pp->offset = addr - map->unmap_ip(map, sym->start);
1652 	pp->function = strdup(sym->name);
1653 	ret = pp->function ? 0 : -ENOMEM;
1654 
1655 out:
1656 	if (map && !is_kprobe) {
1657 		dso__delete(map->dso);
1658 		map__delete(map);
1659 	}
1660 
1661 	return ret;
1662 }
1663 
1664 static int convert_to_perf_probe_point(struct probe_trace_point *tp,
1665 					struct perf_probe_point *pp,
1666 					bool is_kprobe)
1667 {
1668 	char buf[128];
1669 	int ret;
1670 
1671 	ret = find_perf_probe_point_from_dwarf(tp, pp, is_kprobe);
1672 	if (!ret)
1673 		return 0;
1674 	ret = find_perf_probe_point_from_map(tp, pp, is_kprobe);
1675 	if (!ret)
1676 		return 0;
1677 
1678 	pr_debug("Failed to find probe point from both of dwarf and map.\n");
1679 
1680 	if (tp->symbol) {
1681 		pp->function = strdup(tp->symbol);
1682 		pp->offset = tp->offset;
1683 	} else if (!tp->module && !is_kprobe) {
1684 		ret = e_snprintf(buf, 128, "0x%" PRIx64, (u64)tp->address);
1685 		if (ret < 0)
1686 			return ret;
1687 		pp->function = strdup(buf);
1688 		pp->offset = 0;
1689 	}
1690 	if (pp->function == NULL)
1691 		return -ENOMEM;
1692 
1693 	pp->retprobe = tp->retprobe;
1694 
1695 	return 0;
1696 }
1697 
1698 static int convert_to_perf_probe_event(struct probe_trace_event *tev,
1699 			       struct perf_probe_event *pev, bool is_kprobe)
1700 {
1701 	char buf[64] = "";
1702 	int i, ret;
1703 
1704 	/* Convert event/group name */
1705 	pev->event = strdup(tev->event);
1706 	pev->group = strdup(tev->group);
1707 	if (pev->event == NULL || pev->group == NULL)
1708 		return -ENOMEM;
1709 
1710 	/* Convert trace_point to probe_point */
1711 	ret = convert_to_perf_probe_point(&tev->point, &pev->point, is_kprobe);
1712 	if (ret < 0)
1713 		return ret;
1714 
1715 	/* Convert trace_arg to probe_arg */
1716 	pev->nargs = tev->nargs;
1717 	pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1718 	if (pev->args == NULL)
1719 		return -ENOMEM;
1720 	for (i = 0; i < tev->nargs && ret >= 0; i++) {
1721 		if (tev->args[i].name)
1722 			pev->args[i].name = strdup(tev->args[i].name);
1723 		else {
1724 			ret = synthesize_probe_trace_arg(&tev->args[i],
1725 							  buf, 64);
1726 			pev->args[i].name = strdup(buf);
1727 		}
1728 		if (pev->args[i].name == NULL && ret >= 0)
1729 			ret = -ENOMEM;
1730 	}
1731 
1732 	if (ret < 0)
1733 		clear_perf_probe_event(pev);
1734 
1735 	return ret;
1736 }
1737 
1738 void clear_perf_probe_event(struct perf_probe_event *pev)
1739 {
1740 	struct perf_probe_point *pp = &pev->point;
1741 	struct perf_probe_arg_field *field, *next;
1742 	int i;
1743 
1744 	free(pev->event);
1745 	free(pev->group);
1746 	free(pp->file);
1747 	free(pp->function);
1748 	free(pp->lazy_line);
1749 
1750 	for (i = 0; i < pev->nargs; i++) {
1751 		free(pev->args[i].name);
1752 		free(pev->args[i].var);
1753 		free(pev->args[i].type);
1754 		field = pev->args[i].field;
1755 		while (field) {
1756 			next = field->next;
1757 			zfree(&field->name);
1758 			free(field);
1759 			field = next;
1760 		}
1761 	}
1762 	free(pev->args);
1763 	memset(pev, 0, sizeof(*pev));
1764 }
1765 
1766 static void clear_probe_trace_event(struct probe_trace_event *tev)
1767 {
1768 	struct probe_trace_arg_ref *ref, *next;
1769 	int i;
1770 
1771 	free(tev->event);
1772 	free(tev->group);
1773 	free(tev->point.symbol);
1774 	free(tev->point.module);
1775 	for (i = 0; i < tev->nargs; i++) {
1776 		free(tev->args[i].name);
1777 		free(tev->args[i].value);
1778 		free(tev->args[i].type);
1779 		ref = tev->args[i].ref;
1780 		while (ref) {
1781 			next = ref->next;
1782 			free(ref);
1783 			ref = next;
1784 		}
1785 	}
1786 	free(tev->args);
1787 	memset(tev, 0, sizeof(*tev));
1788 }
1789 
1790 static void print_open_warning(int err, bool is_kprobe)
1791 {
1792 	char sbuf[STRERR_BUFSIZE];
1793 
1794 	if (err == -ENOENT) {
1795 		const char *config;
1796 
1797 		if (!is_kprobe)
1798 			config = "CONFIG_UPROBE_EVENTS";
1799 		else
1800 			config = "CONFIG_KPROBE_EVENTS";
1801 
1802 		pr_warning("%cprobe_events file does not exist"
1803 			   " - please rebuild kernel with %s.\n",
1804 			   is_kprobe ? 'k' : 'u', config);
1805 	} else if (err == -ENOTSUP)
1806 		pr_warning("Debugfs is not mounted.\n");
1807 	else
1808 		pr_warning("Failed to open %cprobe_events: %s\n",
1809 			   is_kprobe ? 'k' : 'u',
1810 			   strerror_r(-err, sbuf, sizeof(sbuf)));
1811 }
1812 
1813 static void print_both_open_warning(int kerr, int uerr)
1814 {
1815 	/* Both kprobes and uprobes are disabled, warn it. */
1816 	if (kerr == -ENOTSUP && uerr == -ENOTSUP)
1817 		pr_warning("Debugfs is not mounted.\n");
1818 	else if (kerr == -ENOENT && uerr == -ENOENT)
1819 		pr_warning("Please rebuild kernel with CONFIG_KPROBE_EVENTS "
1820 			   "or/and CONFIG_UPROBE_EVENTS.\n");
1821 	else {
1822 		char sbuf[STRERR_BUFSIZE];
1823 		pr_warning("Failed to open kprobe events: %s.\n",
1824 			   strerror_r(-kerr, sbuf, sizeof(sbuf)));
1825 		pr_warning("Failed to open uprobe events: %s.\n",
1826 			   strerror_r(-uerr, sbuf, sizeof(sbuf)));
1827 	}
1828 }
1829 
1830 static int open_probe_events(const char *trace_file, bool readwrite)
1831 {
1832 	char buf[PATH_MAX];
1833 	const char *__debugfs;
1834 	int ret;
1835 
1836 	__debugfs = debugfs_find_mountpoint();
1837 	if (__debugfs == NULL)
1838 		return -ENOTSUP;
1839 
1840 	ret = e_snprintf(buf, PATH_MAX, "%s/%s", __debugfs, trace_file);
1841 	if (ret >= 0) {
1842 		pr_debug("Opening %s write=%d\n", buf, readwrite);
1843 		if (readwrite && !probe_event_dry_run)
1844 			ret = open(buf, O_RDWR, O_APPEND);
1845 		else
1846 			ret = open(buf, O_RDONLY, 0);
1847 
1848 		if (ret < 0)
1849 			ret = -errno;
1850 	}
1851 	return ret;
1852 }
1853 
1854 static int open_kprobe_events(bool readwrite)
1855 {
1856 	return open_probe_events("tracing/kprobe_events", readwrite);
1857 }
1858 
1859 static int open_uprobe_events(bool readwrite)
1860 {
1861 	return open_probe_events("tracing/uprobe_events", readwrite);
1862 }
1863 
1864 /* Get raw string list of current kprobe_events  or uprobe_events */
1865 static struct strlist *get_probe_trace_command_rawlist(int fd)
1866 {
1867 	int ret, idx;
1868 	FILE *fp;
1869 	char buf[MAX_CMDLEN];
1870 	char *p;
1871 	struct strlist *sl;
1872 
1873 	sl = strlist__new(true, NULL);
1874 
1875 	fp = fdopen(dup(fd), "r");
1876 	while (!feof(fp)) {
1877 		p = fgets(buf, MAX_CMDLEN, fp);
1878 		if (!p)
1879 			break;
1880 
1881 		idx = strlen(p) - 1;
1882 		if (p[idx] == '\n')
1883 			p[idx] = '\0';
1884 		ret = strlist__add(sl, buf);
1885 		if (ret < 0) {
1886 			pr_debug("strlist__add failed (%d)\n", ret);
1887 			strlist__delete(sl);
1888 			return NULL;
1889 		}
1890 	}
1891 	fclose(fp);
1892 
1893 	return sl;
1894 }
1895 
1896 /* Show an event */
1897 static int show_perf_probe_event(struct perf_probe_event *pev,
1898 				 const char *module)
1899 {
1900 	int i, ret;
1901 	char buf[128];
1902 	char *place;
1903 
1904 	/* Synthesize only event probe point */
1905 	place = synthesize_perf_probe_point(&pev->point);
1906 	if (!place)
1907 		return -EINVAL;
1908 
1909 	ret = e_snprintf(buf, 128, "%s:%s", pev->group, pev->event);
1910 	if (ret < 0)
1911 		return ret;
1912 
1913 	printf("  %-20s (on %s", buf, place);
1914 	if (module)
1915 		printf(" in %s", module);
1916 
1917 	if (pev->nargs > 0) {
1918 		printf(" with");
1919 		for (i = 0; i < pev->nargs; i++) {
1920 			ret = synthesize_perf_probe_arg(&pev->args[i],
1921 							buf, 128);
1922 			if (ret < 0)
1923 				break;
1924 			printf(" %s", buf);
1925 		}
1926 	}
1927 	printf(")\n");
1928 	free(place);
1929 	return ret;
1930 }
1931 
1932 static int __show_perf_probe_events(int fd, bool is_kprobe)
1933 {
1934 	int ret = 0;
1935 	struct probe_trace_event tev;
1936 	struct perf_probe_event pev;
1937 	struct strlist *rawlist;
1938 	struct str_node *ent;
1939 
1940 	memset(&tev, 0, sizeof(tev));
1941 	memset(&pev, 0, sizeof(pev));
1942 
1943 	rawlist = get_probe_trace_command_rawlist(fd);
1944 	if (!rawlist)
1945 		return -ENOMEM;
1946 
1947 	strlist__for_each(ent, rawlist) {
1948 		ret = parse_probe_trace_command(ent->s, &tev);
1949 		if (ret >= 0) {
1950 			ret = convert_to_perf_probe_event(&tev, &pev,
1951 								is_kprobe);
1952 			if (ret >= 0)
1953 				ret = show_perf_probe_event(&pev,
1954 							    tev.point.module);
1955 		}
1956 		clear_perf_probe_event(&pev);
1957 		clear_probe_trace_event(&tev);
1958 		if (ret < 0)
1959 			break;
1960 	}
1961 	strlist__delete(rawlist);
1962 
1963 	return ret;
1964 }
1965 
1966 /* List up current perf-probe events */
1967 int show_perf_probe_events(void)
1968 {
1969 	int kp_fd, up_fd, ret;
1970 
1971 	setup_pager();
1972 
1973 	ret = init_symbol_maps(false);
1974 	if (ret < 0)
1975 		return ret;
1976 
1977 	kp_fd = open_kprobe_events(false);
1978 	if (kp_fd >= 0) {
1979 		ret = __show_perf_probe_events(kp_fd, true);
1980 		close(kp_fd);
1981 		if (ret < 0)
1982 			goto out;
1983 	}
1984 
1985 	up_fd = open_uprobe_events(false);
1986 	if (kp_fd < 0 && up_fd < 0) {
1987 		print_both_open_warning(kp_fd, up_fd);
1988 		ret = kp_fd;
1989 		goto out;
1990 	}
1991 
1992 	if (up_fd >= 0) {
1993 		ret = __show_perf_probe_events(up_fd, false);
1994 		close(up_fd);
1995 	}
1996 out:
1997 	exit_symbol_maps();
1998 	return ret;
1999 }
2000 
2001 /* Get current perf-probe event names */
2002 static struct strlist *get_probe_trace_event_names(int fd, bool include_group)
2003 {
2004 	char buf[128];
2005 	struct strlist *sl, *rawlist;
2006 	struct str_node *ent;
2007 	struct probe_trace_event tev;
2008 	int ret = 0;
2009 
2010 	memset(&tev, 0, sizeof(tev));
2011 	rawlist = get_probe_trace_command_rawlist(fd);
2012 	if (!rawlist)
2013 		return NULL;
2014 	sl = strlist__new(true, NULL);
2015 	strlist__for_each(ent, rawlist) {
2016 		ret = parse_probe_trace_command(ent->s, &tev);
2017 		if (ret < 0)
2018 			break;
2019 		if (include_group) {
2020 			ret = e_snprintf(buf, 128, "%s:%s", tev.group,
2021 					tev.event);
2022 			if (ret >= 0)
2023 				ret = strlist__add(sl, buf);
2024 		} else
2025 			ret = strlist__add(sl, tev.event);
2026 		clear_probe_trace_event(&tev);
2027 		if (ret < 0)
2028 			break;
2029 	}
2030 	strlist__delete(rawlist);
2031 
2032 	if (ret < 0) {
2033 		strlist__delete(sl);
2034 		return NULL;
2035 	}
2036 	return sl;
2037 }
2038 
2039 static int write_probe_trace_event(int fd, struct probe_trace_event *tev)
2040 {
2041 	int ret = 0;
2042 	char *buf = synthesize_probe_trace_command(tev);
2043 	char sbuf[STRERR_BUFSIZE];
2044 
2045 	if (!buf) {
2046 		pr_debug("Failed to synthesize probe trace event.\n");
2047 		return -EINVAL;
2048 	}
2049 
2050 	pr_debug("Writing event: %s\n", buf);
2051 	if (!probe_event_dry_run) {
2052 		ret = write(fd, buf, strlen(buf));
2053 		if (ret <= 0)
2054 			pr_warning("Failed to write event: %s\n",
2055 				   strerror_r(errno, sbuf, sizeof(sbuf)));
2056 	}
2057 	free(buf);
2058 	return ret;
2059 }
2060 
2061 static int get_new_event_name(char *buf, size_t len, const char *base,
2062 			      struct strlist *namelist, bool allow_suffix)
2063 {
2064 	int i, ret;
2065 
2066 	/* Try no suffix */
2067 	ret = e_snprintf(buf, len, "%s", base);
2068 	if (ret < 0) {
2069 		pr_debug("snprintf() failed: %d\n", ret);
2070 		return ret;
2071 	}
2072 	if (!strlist__has_entry(namelist, buf))
2073 		return 0;
2074 
2075 	if (!allow_suffix) {
2076 		pr_warning("Error: event \"%s\" already exists. "
2077 			   "(Use -f to force duplicates.)\n", base);
2078 		return -EEXIST;
2079 	}
2080 
2081 	/* Try to add suffix */
2082 	for (i = 1; i < MAX_EVENT_INDEX; i++) {
2083 		ret = e_snprintf(buf, len, "%s_%d", base, i);
2084 		if (ret < 0) {
2085 			pr_debug("snprintf() failed: %d\n", ret);
2086 			return ret;
2087 		}
2088 		if (!strlist__has_entry(namelist, buf))
2089 			break;
2090 	}
2091 	if (i == MAX_EVENT_INDEX) {
2092 		pr_warning("Too many events are on the same function.\n");
2093 		ret = -ERANGE;
2094 	}
2095 
2096 	return ret;
2097 }
2098 
2099 static int __add_probe_trace_events(struct perf_probe_event *pev,
2100 				     struct probe_trace_event *tevs,
2101 				     int ntevs, bool allow_suffix)
2102 {
2103 	int i, fd, ret;
2104 	struct probe_trace_event *tev = NULL;
2105 	char buf[64];
2106 	const char *event, *group;
2107 	struct strlist *namelist;
2108 
2109 	if (pev->uprobes)
2110 		fd = open_uprobe_events(true);
2111 	else
2112 		fd = open_kprobe_events(true);
2113 
2114 	if (fd < 0) {
2115 		print_open_warning(fd, !pev->uprobes);
2116 		return fd;
2117 	}
2118 
2119 	/* Get current event names */
2120 	namelist = get_probe_trace_event_names(fd, false);
2121 	if (!namelist) {
2122 		pr_debug("Failed to get current event list.\n");
2123 		return -EIO;
2124 	}
2125 
2126 	ret = 0;
2127 	printf("Added new event%s\n", (ntevs > 1) ? "s:" : ":");
2128 	for (i = 0; i < ntevs; i++) {
2129 		tev = &tevs[i];
2130 		if (pev->event)
2131 			event = pev->event;
2132 		else
2133 			if (pev->point.function)
2134 				event = pev->point.function;
2135 			else
2136 				event = tev->point.symbol;
2137 		if (pev->group)
2138 			group = pev->group;
2139 		else
2140 			group = PERFPROBE_GROUP;
2141 
2142 		/* Get an unused new event name */
2143 		ret = get_new_event_name(buf, 64, event,
2144 					 namelist, allow_suffix);
2145 		if (ret < 0)
2146 			break;
2147 		event = buf;
2148 
2149 		tev->event = strdup(event);
2150 		tev->group = strdup(group);
2151 		if (tev->event == NULL || tev->group == NULL) {
2152 			ret = -ENOMEM;
2153 			break;
2154 		}
2155 		ret = write_probe_trace_event(fd, tev);
2156 		if (ret < 0)
2157 			break;
2158 		/* Add added event name to namelist */
2159 		strlist__add(namelist, event);
2160 
2161 		/* Trick here - save current event/group */
2162 		event = pev->event;
2163 		group = pev->group;
2164 		pev->event = tev->event;
2165 		pev->group = tev->group;
2166 		show_perf_probe_event(pev, tev->point.module);
2167 		/* Trick here - restore current event/group */
2168 		pev->event = (char *)event;
2169 		pev->group = (char *)group;
2170 
2171 		/*
2172 		 * Probes after the first probe which comes from same
2173 		 * user input are always allowed to add suffix, because
2174 		 * there might be several addresses corresponding to
2175 		 * one code line.
2176 		 */
2177 		allow_suffix = true;
2178 	}
2179 
2180 	if (ret >= 0) {
2181 		/* Show how to use the event. */
2182 		printf("\nYou can now use it in all perf tools, such as:\n\n");
2183 		printf("\tperf record -e %s:%s -aR sleep 1\n\n", tev->group,
2184 			 tev->event);
2185 	}
2186 
2187 	strlist__delete(namelist);
2188 	close(fd);
2189 	return ret;
2190 }
2191 
2192 static char *looking_function_name;
2193 static int num_matched_functions;
2194 
2195 static int probe_function_filter(struct map *map __maybe_unused,
2196 				      struct symbol *sym)
2197 {
2198 	if ((sym->binding == STB_GLOBAL || sym->binding == STB_LOCAL) &&
2199 	    strcmp(looking_function_name, sym->name) == 0) {
2200 		num_matched_functions++;
2201 		return 0;
2202 	}
2203 	return 1;
2204 }
2205 
2206 #define strdup_or_goto(str, label)	\
2207 	({ char *__p = strdup(str); if (!__p) goto label; __p; })
2208 
2209 /*
2210  * Find probe function addresses from map.
2211  * Return an error or the number of found probe_trace_event
2212  */
2213 static int find_probe_trace_events_from_map(struct perf_probe_event *pev,
2214 					    struct probe_trace_event **tevs,
2215 					    int max_tevs, const char *target)
2216 {
2217 	struct map *map = NULL;
2218 	struct kmap *kmap = NULL;
2219 	struct ref_reloc_sym *reloc_sym = NULL;
2220 	struct symbol *sym;
2221 	struct rb_node *nd;
2222 	struct probe_trace_event *tev;
2223 	struct perf_probe_point *pp = &pev->point;
2224 	struct probe_trace_point *tp;
2225 	int ret, i;
2226 
2227 	/* Init maps of given executable or kernel */
2228 	if (pev->uprobes)
2229 		map = dso__new_map(target);
2230 	else
2231 		map = kernel_get_module_map(target);
2232 	if (!map) {
2233 		ret = -EINVAL;
2234 		goto out;
2235 	}
2236 
2237 	/*
2238 	 * Load matched symbols: Since the different local symbols may have
2239 	 * same name but different addresses, this lists all the symbols.
2240 	 */
2241 	num_matched_functions = 0;
2242 	looking_function_name = pp->function;
2243 	ret = map__load(map, probe_function_filter);
2244 	if (ret || num_matched_functions == 0) {
2245 		pr_err("Failed to find symbol %s in %s\n", pp->function,
2246 			target ? : "kernel");
2247 		ret = -ENOENT;
2248 		goto out;
2249 	} else if (num_matched_functions > max_tevs) {
2250 		pr_err("Too many functions matched in %s\n",
2251 			target ? : "kernel");
2252 		ret = -E2BIG;
2253 		goto out;
2254 	}
2255 
2256 	if (!pev->uprobes) {
2257 		kmap = map__kmap(map);
2258 		reloc_sym = kmap->ref_reloc_sym;
2259 		if (!reloc_sym) {
2260 			pr_warning("Relocated base symbol is not found!\n");
2261 			ret = -EINVAL;
2262 			goto out;
2263 		}
2264 	}
2265 
2266 	/* Setup result trace-probe-events */
2267 	*tevs = zalloc(sizeof(*tev) * num_matched_functions);
2268 	if (!*tevs) {
2269 		ret = -ENOMEM;
2270 		goto out;
2271 	}
2272 
2273 	ret = 0;
2274 	map__for_each_symbol(map, sym, nd) {
2275 		tev = (*tevs) + ret;
2276 		tp = &tev->point;
2277 		if (ret == num_matched_functions) {
2278 			pr_warning("Too many symbols are listed. Skip it.\n");
2279 			break;
2280 		}
2281 		ret++;
2282 
2283 		if (pp->offset > sym->end - sym->start) {
2284 			pr_warning("Offset %ld is bigger than the size of %s\n",
2285 				   pp->offset, sym->name);
2286 			ret = -ENOENT;
2287 			goto err_out;
2288 		}
2289 		/* Add one probe point */
2290 		tp->address = map->unmap_ip(map, sym->start) + pp->offset;
2291 		if (reloc_sym) {
2292 			tp->symbol = strdup_or_goto(reloc_sym->name, nomem_out);
2293 			tp->offset = tp->address - reloc_sym->addr;
2294 		} else {
2295 			tp->symbol = strdup_or_goto(sym->name, nomem_out);
2296 			tp->offset = pp->offset;
2297 		}
2298 		tp->retprobe = pp->retprobe;
2299 		if (target)
2300 			tev->point.module = strdup_or_goto(target, nomem_out);
2301 		tev->uprobes = pev->uprobes;
2302 		tev->nargs = pev->nargs;
2303 		if (tev->nargs) {
2304 			tev->args = zalloc(sizeof(struct probe_trace_arg) *
2305 					   tev->nargs);
2306 			if (tev->args == NULL)
2307 				goto nomem_out;
2308 		}
2309 		for (i = 0; i < tev->nargs; i++) {
2310 			if (pev->args[i].name)
2311 				tev->args[i].name =
2312 					strdup_or_goto(pev->args[i].name,
2313 							nomem_out);
2314 
2315 			tev->args[i].value = strdup_or_goto(pev->args[i].var,
2316 							    nomem_out);
2317 			if (pev->args[i].type)
2318 				tev->args[i].type =
2319 					strdup_or_goto(pev->args[i].type,
2320 							nomem_out);
2321 		}
2322 	}
2323 
2324 out:
2325 	if (map && pev->uprobes) {
2326 		/* Only when using uprobe(exec) map needs to be released */
2327 		dso__delete(map->dso);
2328 		map__delete(map);
2329 	}
2330 	return ret;
2331 
2332 nomem_out:
2333 	ret = -ENOMEM;
2334 err_out:
2335 	clear_probe_trace_events(*tevs, num_matched_functions);
2336 	zfree(tevs);
2337 	goto out;
2338 }
2339 
2340 static int convert_to_probe_trace_events(struct perf_probe_event *pev,
2341 					  struct probe_trace_event **tevs,
2342 					  int max_tevs, const char *target)
2343 {
2344 	int ret;
2345 
2346 	if (pev->uprobes && !pev->group) {
2347 		/* Replace group name if not given */
2348 		ret = convert_exec_to_group(target, &pev->group);
2349 		if (ret != 0) {
2350 			pr_warning("Failed to make a group name.\n");
2351 			return ret;
2352 		}
2353 	}
2354 
2355 	/* Convert perf_probe_event with debuginfo */
2356 	ret = try_to_find_probe_trace_events(pev, tevs, max_tevs, target);
2357 	if (ret != 0)
2358 		return ret;	/* Found in debuginfo or got an error */
2359 
2360 	return find_probe_trace_events_from_map(pev, tevs, max_tevs, target);
2361 }
2362 
2363 struct __event_package {
2364 	struct perf_probe_event		*pev;
2365 	struct probe_trace_event	*tevs;
2366 	int				ntevs;
2367 };
2368 
2369 int add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
2370 			  int max_tevs, const char *target, bool force_add)
2371 {
2372 	int i, j, ret;
2373 	struct __event_package *pkgs;
2374 
2375 	ret = 0;
2376 	pkgs = zalloc(sizeof(struct __event_package) * npevs);
2377 
2378 	if (pkgs == NULL)
2379 		return -ENOMEM;
2380 
2381 	ret = init_symbol_maps(pevs->uprobes);
2382 	if (ret < 0) {
2383 		free(pkgs);
2384 		return ret;
2385 	}
2386 
2387 	/* Loop 1: convert all events */
2388 	for (i = 0; i < npevs; i++) {
2389 		pkgs[i].pev = &pevs[i];
2390 		/* Convert with or without debuginfo */
2391 		ret  = convert_to_probe_trace_events(pkgs[i].pev,
2392 						     &pkgs[i].tevs,
2393 						     max_tevs,
2394 						     target);
2395 		if (ret < 0)
2396 			goto end;
2397 		pkgs[i].ntevs = ret;
2398 	}
2399 
2400 	/* Loop 2: add all events */
2401 	for (i = 0; i < npevs; i++) {
2402 		ret = __add_probe_trace_events(pkgs[i].pev, pkgs[i].tevs,
2403 						pkgs[i].ntevs, force_add);
2404 		if (ret < 0)
2405 			break;
2406 	}
2407 end:
2408 	/* Loop 3: cleanup and free trace events  */
2409 	for (i = 0; i < npevs; i++) {
2410 		for (j = 0; j < pkgs[i].ntevs; j++)
2411 			clear_probe_trace_event(&pkgs[i].tevs[j]);
2412 		zfree(&pkgs[i].tevs);
2413 	}
2414 	free(pkgs);
2415 	exit_symbol_maps();
2416 
2417 	return ret;
2418 }
2419 
2420 static int __del_trace_probe_event(int fd, struct str_node *ent)
2421 {
2422 	char *p;
2423 	char buf[128];
2424 	int ret;
2425 
2426 	/* Convert from perf-probe event to trace-probe event */
2427 	ret = e_snprintf(buf, 128, "-:%s", ent->s);
2428 	if (ret < 0)
2429 		goto error;
2430 
2431 	p = strchr(buf + 2, ':');
2432 	if (!p) {
2433 		pr_debug("Internal error: %s should have ':' but not.\n",
2434 			 ent->s);
2435 		ret = -ENOTSUP;
2436 		goto error;
2437 	}
2438 	*p = '/';
2439 
2440 	pr_debug("Writing event: %s\n", buf);
2441 	ret = write(fd, buf, strlen(buf));
2442 	if (ret < 0) {
2443 		ret = -errno;
2444 		goto error;
2445 	}
2446 
2447 	printf("Removed event: %s\n", ent->s);
2448 	return 0;
2449 error:
2450 	pr_warning("Failed to delete event: %s\n",
2451 		   strerror_r(-ret, buf, sizeof(buf)));
2452 	return ret;
2453 }
2454 
2455 static int del_trace_probe_event(int fd, const char *buf,
2456 						  struct strlist *namelist)
2457 {
2458 	struct str_node *ent, *n;
2459 	int ret = -1;
2460 
2461 	if (strpbrk(buf, "*?")) { /* Glob-exp */
2462 		strlist__for_each_safe(ent, n, namelist)
2463 			if (strglobmatch(ent->s, buf)) {
2464 				ret = __del_trace_probe_event(fd, ent);
2465 				if (ret < 0)
2466 					break;
2467 				strlist__remove(namelist, ent);
2468 			}
2469 	} else {
2470 		ent = strlist__find(namelist, buf);
2471 		if (ent) {
2472 			ret = __del_trace_probe_event(fd, ent);
2473 			if (ret >= 0)
2474 				strlist__remove(namelist, ent);
2475 		}
2476 	}
2477 
2478 	return ret;
2479 }
2480 
2481 int del_perf_probe_events(struct strlist *dellist)
2482 {
2483 	int ret = -1, ufd = -1, kfd = -1;
2484 	char buf[128];
2485 	const char *group, *event;
2486 	char *p, *str;
2487 	struct str_node *ent;
2488 	struct strlist *namelist = NULL, *unamelist = NULL;
2489 
2490 	/* Get current event names */
2491 	kfd = open_kprobe_events(true);
2492 	if (kfd >= 0)
2493 		namelist = get_probe_trace_event_names(kfd, true);
2494 
2495 	ufd = open_uprobe_events(true);
2496 	if (ufd >= 0)
2497 		unamelist = get_probe_trace_event_names(ufd, true);
2498 
2499 	if (kfd < 0 && ufd < 0) {
2500 		print_both_open_warning(kfd, ufd);
2501 		goto error;
2502 	}
2503 
2504 	if (namelist == NULL && unamelist == NULL)
2505 		goto error;
2506 
2507 	strlist__for_each(ent, dellist) {
2508 		str = strdup(ent->s);
2509 		if (str == NULL) {
2510 			ret = -ENOMEM;
2511 			goto error;
2512 		}
2513 		pr_debug("Parsing: %s\n", str);
2514 		p = strchr(str, ':');
2515 		if (p) {
2516 			group = str;
2517 			*p = '\0';
2518 			event = p + 1;
2519 		} else {
2520 			group = "*";
2521 			event = str;
2522 		}
2523 
2524 		ret = e_snprintf(buf, 128, "%s:%s", group, event);
2525 		if (ret < 0) {
2526 			pr_err("Failed to copy event.");
2527 			free(str);
2528 			goto error;
2529 		}
2530 
2531 		pr_debug("Group: %s, Event: %s\n", group, event);
2532 
2533 		if (namelist)
2534 			ret = del_trace_probe_event(kfd, buf, namelist);
2535 
2536 		if (unamelist && ret != 0)
2537 			ret = del_trace_probe_event(ufd, buf, unamelist);
2538 
2539 		if (ret != 0)
2540 			pr_info("Info: Event \"%s\" does not exist.\n", buf);
2541 
2542 		free(str);
2543 	}
2544 
2545 error:
2546 	if (kfd >= 0) {
2547 		strlist__delete(namelist);
2548 		close(kfd);
2549 	}
2550 
2551 	if (ufd >= 0) {
2552 		strlist__delete(unamelist);
2553 		close(ufd);
2554 	}
2555 
2556 	return ret;
2557 }
2558 
2559 /* TODO: don't use a global variable for filter ... */
2560 static struct strfilter *available_func_filter;
2561 
2562 /*
2563  * If a symbol corresponds to a function with global binding and
2564  * matches filter return 0. For all others return 1.
2565  */
2566 static int filter_available_functions(struct map *map __maybe_unused,
2567 				      struct symbol *sym)
2568 {
2569 	if ((sym->binding == STB_GLOBAL || sym->binding == STB_LOCAL) &&
2570 	    strfilter__compare(available_func_filter, sym->name))
2571 		return 0;
2572 	return 1;
2573 }
2574 
2575 int show_available_funcs(const char *target, struct strfilter *_filter,
2576 					bool user)
2577 {
2578 	struct map *map;
2579 	int ret;
2580 
2581 	ret = init_symbol_maps(user);
2582 	if (ret < 0)
2583 		return ret;
2584 
2585 	/* Get a symbol map */
2586 	if (user)
2587 		map = dso__new_map(target);
2588 	else
2589 		map = kernel_get_module_map(target);
2590 	if (!map) {
2591 		pr_err("Failed to get a map for %s\n", (target) ? : "kernel");
2592 		return -EINVAL;
2593 	}
2594 
2595 	/* Load symbols with given filter */
2596 	available_func_filter = _filter;
2597 	if (map__load(map, filter_available_functions)) {
2598 		pr_err("Failed to load symbols in %s\n", (target) ? : "kernel");
2599 		goto end;
2600 	}
2601 	if (!dso__sorted_by_name(map->dso, map->type))
2602 		dso__sort_by_name(map->dso, map->type);
2603 
2604 	/* Show all (filtered) symbols */
2605 	setup_pager();
2606 	dso__fprintf_symbols_by_name(map->dso, map->type, stdout);
2607 end:
2608 	if (user) {
2609 		dso__delete(map->dso);
2610 		map__delete(map);
2611 	}
2612 	exit_symbol_maps();
2613 
2614 	return ret;
2615 }
2616 
2617