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