xref: /openbmc/linux/tools/perf/util/probe-event.c (revision 11a163f2)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * probe-event.c : perf-probe definition to probe_events format converter
4  *
5  * Written by Masami Hiramatsu <mhiramat@redhat.com>
6  */
7 
8 #include <inttypes.h>
9 #include <sys/utsname.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #include <fcntl.h>
13 #include <errno.h>
14 #include <stdio.h>
15 #include <unistd.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <stdarg.h>
19 #include <limits.h>
20 #include <elf.h>
21 
22 #include "build-id.h"
23 #include "event.h"
24 #include "namespaces.h"
25 #include "strlist.h"
26 #include "strfilter.h"
27 #include "debug.h"
28 #include "dso.h"
29 #include "color.h"
30 #include "map.h"
31 #include "maps.h"
32 #include "symbol.h"
33 #include <api/fs/fs.h>
34 #include "trace-event.h"	/* For __maybe_unused */
35 #include "probe-event.h"
36 #include "probe-finder.h"
37 #include "probe-file.h"
38 #include "session.h"
39 #include "string2.h"
40 #include "strbuf.h"
41 
42 #include <subcmd/pager.h>
43 #include <linux/ctype.h>
44 #include <linux/zalloc.h>
45 
46 #ifdef HAVE_DEBUGINFOD_SUPPORT
47 #include <elfutils/debuginfod.h>
48 #endif
49 
50 #define PERFPROBE_GROUP "probe"
51 
52 bool probe_event_dry_run;	/* Dry run flag */
53 struct probe_conf probe_conf = { .magic_num = DEFAULT_PROBE_MAGIC_NUM };
54 
55 #define semantic_error(msg ...) pr_err("Semantic error :" msg)
56 
57 int e_snprintf(char *str, size_t size, const char *format, ...)
58 {
59 	int ret;
60 	va_list ap;
61 	va_start(ap, format);
62 	ret = vsnprintf(str, size, format, ap);
63 	va_end(ap);
64 	if (ret >= (int)size)
65 		ret = -E2BIG;
66 	return ret;
67 }
68 
69 static struct machine *host_machine;
70 
71 /* Initialize symbol maps and path of vmlinux/modules */
72 int init_probe_symbol_maps(bool user_only)
73 {
74 	int ret;
75 
76 	symbol_conf.sort_by_name = true;
77 	symbol_conf.allow_aliases = true;
78 	ret = symbol__init(NULL);
79 	if (ret < 0) {
80 		pr_debug("Failed to init symbol map.\n");
81 		goto out;
82 	}
83 
84 	if (host_machine || user_only)	/* already initialized */
85 		return 0;
86 
87 	if (symbol_conf.vmlinux_name)
88 		pr_debug("Use vmlinux: %s\n", symbol_conf.vmlinux_name);
89 
90 	host_machine = machine__new_host();
91 	if (!host_machine) {
92 		pr_debug("machine__new_host() failed.\n");
93 		symbol__exit();
94 		ret = -1;
95 	}
96 out:
97 	if (ret < 0)
98 		pr_warning("Failed to init vmlinux path.\n");
99 	return ret;
100 }
101 
102 void exit_probe_symbol_maps(void)
103 {
104 	machine__delete(host_machine);
105 	host_machine = NULL;
106 	symbol__exit();
107 }
108 
109 static struct ref_reloc_sym *kernel_get_ref_reloc_sym(struct map **pmap)
110 {
111 	/* kmap->ref_reloc_sym should be set if host_machine is initialized */
112 	struct kmap *kmap;
113 	struct map *map = machine__kernel_map(host_machine);
114 
115 	if (map__load(map) < 0)
116 		return NULL;
117 
118 	kmap = map__kmap(map);
119 	if (!kmap)
120 		return NULL;
121 
122 	if (pmap)
123 		*pmap = map;
124 
125 	return kmap->ref_reloc_sym;
126 }
127 
128 static int kernel_get_symbol_address_by_name(const char *name, u64 *addr,
129 					     bool reloc, bool reladdr)
130 {
131 	struct ref_reloc_sym *reloc_sym;
132 	struct symbol *sym;
133 	struct map *map;
134 
135 	/* ref_reloc_sym is just a label. Need a special fix*/
136 	reloc_sym = kernel_get_ref_reloc_sym(&map);
137 	if (reloc_sym && strcmp(name, reloc_sym->name) == 0)
138 		*addr = (!map->reloc || reloc) ? reloc_sym->addr :
139 			reloc_sym->unrelocated_addr;
140 	else {
141 		sym = machine__find_kernel_symbol_by_name(host_machine, name, &map);
142 		if (!sym)
143 			return -ENOENT;
144 		*addr = map->unmap_ip(map, sym->start) -
145 			((reloc) ? 0 : map->reloc) -
146 			((reladdr) ? map->start : 0);
147 	}
148 	return 0;
149 }
150 
151 static struct map *kernel_get_module_map(const char *module)
152 {
153 	struct maps *maps = machine__kernel_maps(host_machine);
154 	struct map *pos;
155 
156 	/* A file path -- this is an offline module */
157 	if (module && strchr(module, '/'))
158 		return dso__new_map(module);
159 
160 	if (!module) {
161 		pos = machine__kernel_map(host_machine);
162 		return map__get(pos);
163 	}
164 
165 	maps__for_each_entry(maps, pos) {
166 		/* short_name is "[module]" */
167 		if (strncmp(pos->dso->short_name + 1, module,
168 			    pos->dso->short_name_len - 2) == 0 &&
169 		    module[pos->dso->short_name_len - 2] == '\0') {
170 			return map__get(pos);
171 		}
172 	}
173 	return NULL;
174 }
175 
176 struct map *get_target_map(const char *target, struct nsinfo *nsi, bool user)
177 {
178 	/* Init maps of given executable or kernel */
179 	if (user) {
180 		struct map *map;
181 
182 		map = dso__new_map(target);
183 		if (map && map->dso)
184 			map->dso->nsinfo = nsinfo__get(nsi);
185 		return map;
186 	} else {
187 		return kernel_get_module_map(target);
188 	}
189 }
190 
191 static int convert_exec_to_group(const char *exec, char **result)
192 {
193 	char *ptr1, *ptr2, *exec_copy;
194 	char buf[64];
195 	int ret;
196 
197 	exec_copy = strdup(exec);
198 	if (!exec_copy)
199 		return -ENOMEM;
200 
201 	ptr1 = basename(exec_copy);
202 	if (!ptr1) {
203 		ret = -EINVAL;
204 		goto out;
205 	}
206 
207 	for (ptr2 = ptr1; *ptr2 != '\0'; ptr2++) {
208 		if (!isalnum(*ptr2) && *ptr2 != '_') {
209 			*ptr2 = '\0';
210 			break;
211 		}
212 	}
213 
214 	ret = e_snprintf(buf, 64, "%s_%s", PERFPROBE_GROUP, ptr1);
215 	if (ret < 0)
216 		goto out;
217 
218 	*result = strdup(buf);
219 	ret = *result ? 0 : -ENOMEM;
220 
221 out:
222 	free(exec_copy);
223 	return ret;
224 }
225 
226 static void clear_perf_probe_point(struct perf_probe_point *pp)
227 {
228 	zfree(&pp->file);
229 	zfree(&pp->function);
230 	zfree(&pp->lazy_line);
231 }
232 
233 static void clear_probe_trace_events(struct probe_trace_event *tevs, int ntevs)
234 {
235 	int i;
236 
237 	for (i = 0; i < ntevs; i++)
238 		clear_probe_trace_event(tevs + i);
239 }
240 
241 static bool kprobe_blacklist__listed(unsigned long address);
242 static bool kprobe_warn_out_range(const char *symbol, unsigned long address)
243 {
244 	struct map *map;
245 	bool ret = false;
246 
247 	map = kernel_get_module_map(NULL);
248 	if (map) {
249 		ret = address <= map->start || map->end < address;
250 		if (ret)
251 			pr_warning("%s is out of .text, skip it.\n", symbol);
252 		map__put(map);
253 	}
254 	if (!ret && kprobe_blacklist__listed(address)) {
255 		pr_warning("%s is blacklisted function, skip it.\n", symbol);
256 		ret = true;
257 	}
258 
259 	return ret;
260 }
261 
262 /*
263  * @module can be module name of module file path. In case of path,
264  * inspect elf and find out what is actual module name.
265  * Caller has to free mod_name after using it.
266  */
267 static char *find_module_name(const char *module)
268 {
269 	int fd;
270 	Elf *elf;
271 	GElf_Ehdr ehdr;
272 	GElf_Shdr shdr;
273 	Elf_Data *data;
274 	Elf_Scn *sec;
275 	char *mod_name = NULL;
276 	int name_offset;
277 
278 	fd = open(module, O_RDONLY);
279 	if (fd < 0)
280 		return NULL;
281 
282 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
283 	if (elf == NULL)
284 		goto elf_err;
285 
286 	if (gelf_getehdr(elf, &ehdr) == NULL)
287 		goto ret_err;
288 
289 	sec = elf_section_by_name(elf, &ehdr, &shdr,
290 			".gnu.linkonce.this_module", NULL);
291 	if (!sec)
292 		goto ret_err;
293 
294 	data = elf_getdata(sec, NULL);
295 	if (!data || !data->d_buf)
296 		goto ret_err;
297 
298 	/*
299 	 * NOTE:
300 	 * '.gnu.linkonce.this_module' section of kernel module elf directly
301 	 * maps to 'struct module' from linux/module.h. This section contains
302 	 * actual module name which will be used by kernel after loading it.
303 	 * But, we cannot use 'struct module' here since linux/module.h is not
304 	 * exposed to user-space. Offset of 'name' has remained same from long
305 	 * time, so hardcoding it here.
306 	 */
307 	if (ehdr.e_ident[EI_CLASS] == ELFCLASS32)
308 		name_offset = 12;
309 	else	/* expect ELFCLASS64 by default */
310 		name_offset = 24;
311 
312 	mod_name = strdup((char *)data->d_buf + name_offset);
313 
314 ret_err:
315 	elf_end(elf);
316 elf_err:
317 	close(fd);
318 	return mod_name;
319 }
320 
321 #ifdef HAVE_DWARF_SUPPORT
322 
323 static int kernel_get_module_dso(const char *module, struct dso **pdso)
324 {
325 	struct dso *dso;
326 	struct map *map;
327 	const char *vmlinux_name;
328 	int ret = 0;
329 
330 	if (module) {
331 		char module_name[128];
332 
333 		snprintf(module_name, sizeof(module_name), "[%s]", module);
334 		map = maps__find_by_name(&host_machine->kmaps, module_name);
335 		if (map) {
336 			dso = map->dso;
337 			goto found;
338 		}
339 		pr_debug("Failed to find module %s.\n", module);
340 		return -ENOENT;
341 	}
342 
343 	map = machine__kernel_map(host_machine);
344 	dso = map->dso;
345 	if (!dso->has_build_id)
346 		dso__read_running_kernel_build_id(dso, host_machine);
347 
348 	vmlinux_name = symbol_conf.vmlinux_name;
349 	dso->load_errno = 0;
350 	if (vmlinux_name)
351 		ret = dso__load_vmlinux(dso, map, vmlinux_name, false);
352 	else
353 		ret = dso__load_vmlinux_path(dso, map);
354 found:
355 	*pdso = dso;
356 	return ret;
357 }
358 
359 /*
360  * Some binaries like glibc have special symbols which are on the symbol
361  * table, but not in the debuginfo. If we can find the address of the
362  * symbol from map, we can translate the address back to the probe point.
363  */
364 static int find_alternative_probe_point(struct debuginfo *dinfo,
365 					struct perf_probe_point *pp,
366 					struct perf_probe_point *result,
367 					const char *target, struct nsinfo *nsi,
368 					bool uprobes)
369 {
370 	struct map *map = NULL;
371 	struct symbol *sym;
372 	u64 address = 0;
373 	int ret = -ENOENT;
374 
375 	/* This can work only for function-name based one */
376 	if (!pp->function || pp->file)
377 		return -ENOTSUP;
378 
379 	map = get_target_map(target, nsi, uprobes);
380 	if (!map)
381 		return -EINVAL;
382 
383 	/* Find the address of given function */
384 	map__for_each_symbol_by_name(map, pp->function, sym) {
385 		if (uprobes) {
386 			address = sym->start;
387 			if (sym->type == STT_GNU_IFUNC)
388 				pr_warning("Warning: The probe function (%s) is a GNU indirect function.\n"
389 					   "Consider identifying the final function used at run time and set the probe directly on that.\n",
390 					   pp->function);
391 		} else
392 			address = map->unmap_ip(map, sym->start) - map->reloc;
393 		break;
394 	}
395 	if (!address) {
396 		ret = -ENOENT;
397 		goto out;
398 	}
399 	pr_debug("Symbol %s address found : %" PRIx64 "\n",
400 			pp->function, address);
401 
402 	ret = debuginfo__find_probe_point(dinfo, (unsigned long)address,
403 					  result);
404 	if (ret <= 0)
405 		ret = (!ret) ? -ENOENT : ret;
406 	else {
407 		result->offset += pp->offset;
408 		result->line += pp->line;
409 		result->retprobe = pp->retprobe;
410 		ret = 0;
411 	}
412 
413 out:
414 	map__put(map);
415 	return ret;
416 
417 }
418 
419 static int get_alternative_probe_event(struct debuginfo *dinfo,
420 				       struct perf_probe_event *pev,
421 				       struct perf_probe_point *tmp)
422 {
423 	int ret;
424 
425 	memcpy(tmp, &pev->point, sizeof(*tmp));
426 	memset(&pev->point, 0, sizeof(pev->point));
427 	ret = find_alternative_probe_point(dinfo, tmp, &pev->point, pev->target,
428 					   pev->nsi, pev->uprobes);
429 	if (ret < 0)
430 		memcpy(&pev->point, tmp, sizeof(*tmp));
431 
432 	return ret;
433 }
434 
435 static int get_alternative_line_range(struct debuginfo *dinfo,
436 				      struct line_range *lr,
437 				      const char *target, bool user)
438 {
439 	struct perf_probe_point pp = { .function = lr->function,
440 				       .file = lr->file,
441 				       .line = lr->start };
442 	struct perf_probe_point result;
443 	int ret, len = 0;
444 
445 	memset(&result, 0, sizeof(result));
446 
447 	if (lr->end != INT_MAX)
448 		len = lr->end - lr->start;
449 	ret = find_alternative_probe_point(dinfo, &pp, &result,
450 					   target, NULL, user);
451 	if (!ret) {
452 		lr->function = result.function;
453 		lr->file = result.file;
454 		lr->start = result.line;
455 		if (lr->end != INT_MAX)
456 			lr->end = lr->start + len;
457 		clear_perf_probe_point(&pp);
458 	}
459 	return ret;
460 }
461 
462 #ifdef HAVE_DEBUGINFOD_SUPPORT
463 static struct debuginfo *open_from_debuginfod(struct dso *dso, struct nsinfo *nsi,
464 					      bool silent)
465 {
466 	debuginfod_client *c = debuginfod_begin();
467 	char sbuild_id[SBUILD_ID_SIZE + 1];
468 	struct debuginfo *ret = NULL;
469 	struct nscookie nsc;
470 	char *path;
471 	int fd;
472 
473 	if (!c)
474 		return NULL;
475 
476 	build_id__sprintf(&dso->bid, sbuild_id);
477 	fd = debuginfod_find_debuginfo(c, (const unsigned char *)sbuild_id,
478 					0, &path);
479 	if (fd >= 0)
480 		close(fd);
481 	debuginfod_end(c);
482 	if (fd < 0) {
483 		if (!silent)
484 			pr_debug("Failed to find debuginfo in debuginfod.\n");
485 		return NULL;
486 	}
487 	if (!silent)
488 		pr_debug("Load debuginfo from debuginfod (%s)\n", path);
489 
490 	nsinfo__mountns_enter(nsi, &nsc);
491 	ret = debuginfo__new((const char *)path);
492 	nsinfo__mountns_exit(&nsc);
493 	return ret;
494 }
495 #else
496 static inline
497 struct debuginfo *open_from_debuginfod(struct dso *dso __maybe_unused,
498 				       struct nsinfo *nsi __maybe_unused,
499 				       bool silent __maybe_unused)
500 {
501 	return NULL;
502 }
503 #endif
504 
505 /* Open new debuginfo of given module */
506 static struct debuginfo *open_debuginfo(const char *module, struct nsinfo *nsi,
507 					bool silent)
508 {
509 	const char *path = module;
510 	char reason[STRERR_BUFSIZE];
511 	struct debuginfo *ret = NULL;
512 	struct dso *dso = NULL;
513 	struct nscookie nsc;
514 	int err;
515 
516 	if (!module || !strchr(module, '/')) {
517 		err = kernel_get_module_dso(module, &dso);
518 		if (err < 0) {
519 			if (!dso || dso->load_errno == 0) {
520 				if (!str_error_r(-err, reason, STRERR_BUFSIZE))
521 					strcpy(reason, "(unknown)");
522 			} else
523 				dso__strerror_load(dso, reason, STRERR_BUFSIZE);
524 			if (dso)
525 				ret = open_from_debuginfod(dso, nsi, silent);
526 			if (ret)
527 				return ret;
528 			if (!silent) {
529 				if (module)
530 					pr_err("Module %s is not loaded, please specify its full path name.\n", module);
531 				else
532 					pr_err("Failed to find the path for the kernel: %s\n", reason);
533 			}
534 			return NULL;
535 		}
536 		path = dso->long_name;
537 	}
538 	nsinfo__mountns_enter(nsi, &nsc);
539 	ret = debuginfo__new(path);
540 	if (!ret && !silent) {
541 		pr_warning("The %s file has no debug information.\n", path);
542 		if (!module || !strtailcmp(path, ".ko"))
543 			pr_warning("Rebuild with CONFIG_DEBUG_INFO=y, ");
544 		else
545 			pr_warning("Rebuild with -g, ");
546 		pr_warning("or install an appropriate debuginfo package.\n");
547 	}
548 	nsinfo__mountns_exit(&nsc);
549 	return ret;
550 }
551 
552 /* For caching the last debuginfo */
553 static struct debuginfo *debuginfo_cache;
554 static char *debuginfo_cache_path;
555 
556 static struct debuginfo *debuginfo_cache__open(const char *module, bool silent)
557 {
558 	const char *path = module;
559 
560 	/* If the module is NULL, it should be the kernel. */
561 	if (!module)
562 		path = "kernel";
563 
564 	if (debuginfo_cache_path && !strcmp(debuginfo_cache_path, path))
565 		goto out;
566 
567 	/* Copy module path */
568 	free(debuginfo_cache_path);
569 	debuginfo_cache_path = strdup(path);
570 	if (!debuginfo_cache_path) {
571 		debuginfo__delete(debuginfo_cache);
572 		debuginfo_cache = NULL;
573 		goto out;
574 	}
575 
576 	debuginfo_cache = open_debuginfo(module, NULL, silent);
577 	if (!debuginfo_cache)
578 		zfree(&debuginfo_cache_path);
579 out:
580 	return debuginfo_cache;
581 }
582 
583 static void debuginfo_cache__exit(void)
584 {
585 	debuginfo__delete(debuginfo_cache);
586 	debuginfo_cache = NULL;
587 	zfree(&debuginfo_cache_path);
588 }
589 
590 
591 static int get_text_start_address(const char *exec, unsigned long *address,
592 				  struct nsinfo *nsi)
593 {
594 	Elf *elf;
595 	GElf_Ehdr ehdr;
596 	GElf_Shdr shdr;
597 	int fd, ret = -ENOENT;
598 	struct nscookie nsc;
599 
600 	nsinfo__mountns_enter(nsi, &nsc);
601 	fd = open(exec, O_RDONLY);
602 	nsinfo__mountns_exit(&nsc);
603 	if (fd < 0)
604 		return -errno;
605 
606 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
607 	if (elf == NULL) {
608 		ret = -EINVAL;
609 		goto out_close;
610 	}
611 
612 	if (gelf_getehdr(elf, &ehdr) == NULL)
613 		goto out;
614 
615 	if (!elf_section_by_name(elf, &ehdr, &shdr, ".text", NULL))
616 		goto out;
617 
618 	*address = shdr.sh_addr - shdr.sh_offset;
619 	ret = 0;
620 out:
621 	elf_end(elf);
622 out_close:
623 	close(fd);
624 
625 	return ret;
626 }
627 
628 /*
629  * Convert trace point to probe point with debuginfo
630  */
631 static int find_perf_probe_point_from_dwarf(struct probe_trace_point *tp,
632 					    struct perf_probe_point *pp,
633 					    bool is_kprobe)
634 {
635 	struct debuginfo *dinfo = NULL;
636 	unsigned long stext = 0;
637 	u64 addr = tp->address;
638 	int ret = -ENOENT;
639 
640 	/* convert the address to dwarf address */
641 	if (!is_kprobe) {
642 		if (!addr) {
643 			ret = -EINVAL;
644 			goto error;
645 		}
646 		ret = get_text_start_address(tp->module, &stext, NULL);
647 		if (ret < 0)
648 			goto error;
649 		addr += stext;
650 	} else if (tp->symbol) {
651 		/* If the module is given, this returns relative address */
652 		ret = kernel_get_symbol_address_by_name(tp->symbol, &addr,
653 							false, !!tp->module);
654 		if (ret != 0)
655 			goto error;
656 		addr += tp->offset;
657 	}
658 
659 	pr_debug("try to find information at %" PRIx64 " in %s\n", addr,
660 		 tp->module ? : "kernel");
661 
662 	dinfo = debuginfo_cache__open(tp->module, verbose <= 0);
663 	if (dinfo)
664 		ret = debuginfo__find_probe_point(dinfo,
665 						 (unsigned long)addr, pp);
666 	else
667 		ret = -ENOENT;
668 
669 	if (ret > 0) {
670 		pp->retprobe = tp->retprobe;
671 		return 0;
672 	}
673 error:
674 	pr_debug("Failed to find corresponding probes from debuginfo.\n");
675 	return ret ? : -ENOENT;
676 }
677 
678 /* Adjust symbol name and address */
679 static int post_process_probe_trace_point(struct probe_trace_point *tp,
680 					   struct map *map, unsigned long offs)
681 {
682 	struct symbol *sym;
683 	u64 addr = tp->address - offs;
684 
685 	sym = map__find_symbol(map, addr);
686 	if (!sym)
687 		return -ENOENT;
688 
689 	if (strcmp(sym->name, tp->symbol)) {
690 		/* If we have no realname, use symbol for it */
691 		if (!tp->realname)
692 			tp->realname = tp->symbol;
693 		else
694 			free(tp->symbol);
695 		tp->symbol = strdup(sym->name);
696 		if (!tp->symbol)
697 			return -ENOMEM;
698 	}
699 	tp->offset = addr - sym->start;
700 	tp->address -= offs;
701 
702 	return 0;
703 }
704 
705 /*
706  * Rename DWARF symbols to ELF symbols -- gcc sometimes optimizes functions
707  * and generate new symbols with suffixes such as .constprop.N or .isra.N
708  * etc. Since those symbols are not recorded in DWARF, we have to find
709  * correct generated symbols from offline ELF binary.
710  * For online kernel or uprobes we don't need this because those are
711  * rebased on _text, or already a section relative address.
712  */
713 static int
714 post_process_offline_probe_trace_events(struct probe_trace_event *tevs,
715 					int ntevs, const char *pathname)
716 {
717 	struct map *map;
718 	unsigned long stext = 0;
719 	int i, ret = 0;
720 
721 	/* Prepare a map for offline binary */
722 	map = dso__new_map(pathname);
723 	if (!map || get_text_start_address(pathname, &stext, NULL) < 0) {
724 		pr_warning("Failed to get ELF symbols for %s\n", pathname);
725 		return -EINVAL;
726 	}
727 
728 	for (i = 0; i < ntevs; i++) {
729 		ret = post_process_probe_trace_point(&tevs[i].point,
730 						     map, stext);
731 		if (ret < 0)
732 			break;
733 	}
734 	map__put(map);
735 
736 	return ret;
737 }
738 
739 static int add_exec_to_probe_trace_events(struct probe_trace_event *tevs,
740 					  int ntevs, const char *exec,
741 					  struct nsinfo *nsi)
742 {
743 	int i, ret = 0;
744 	unsigned long stext = 0;
745 
746 	if (!exec)
747 		return 0;
748 
749 	ret = get_text_start_address(exec, &stext, nsi);
750 	if (ret < 0)
751 		return ret;
752 
753 	for (i = 0; i < ntevs && ret >= 0; i++) {
754 		/* point.address is the address of point.symbol + point.offset */
755 		tevs[i].point.address -= stext;
756 		tevs[i].point.module = strdup(exec);
757 		if (!tevs[i].point.module) {
758 			ret = -ENOMEM;
759 			break;
760 		}
761 		tevs[i].uprobes = true;
762 	}
763 
764 	return ret;
765 }
766 
767 static int
768 post_process_module_probe_trace_events(struct probe_trace_event *tevs,
769 				       int ntevs, const char *module,
770 				       struct debuginfo *dinfo)
771 {
772 	Dwarf_Addr text_offs = 0;
773 	int i, ret = 0;
774 	char *mod_name = NULL;
775 	struct map *map;
776 
777 	if (!module)
778 		return 0;
779 
780 	map = get_target_map(module, NULL, false);
781 	if (!map || debuginfo__get_text_offset(dinfo, &text_offs, true) < 0) {
782 		pr_warning("Failed to get ELF symbols for %s\n", module);
783 		return -EINVAL;
784 	}
785 
786 	mod_name = find_module_name(module);
787 	for (i = 0; i < ntevs; i++) {
788 		ret = post_process_probe_trace_point(&tevs[i].point,
789 						map, (unsigned long)text_offs);
790 		if (ret < 0)
791 			break;
792 		tevs[i].point.module =
793 			strdup(mod_name ? mod_name : module);
794 		if (!tevs[i].point.module) {
795 			ret = -ENOMEM;
796 			break;
797 		}
798 	}
799 
800 	free(mod_name);
801 	map__put(map);
802 
803 	return ret;
804 }
805 
806 static int
807 post_process_kernel_probe_trace_events(struct probe_trace_event *tevs,
808 				       int ntevs)
809 {
810 	struct ref_reloc_sym *reloc_sym;
811 	struct map *map;
812 	char *tmp;
813 	int i, skipped = 0;
814 
815 	/* Skip post process if the target is an offline kernel */
816 	if (symbol_conf.ignore_vmlinux_buildid)
817 		return post_process_offline_probe_trace_events(tevs, ntevs,
818 						symbol_conf.vmlinux_name);
819 
820 	reloc_sym = kernel_get_ref_reloc_sym(&map);
821 	if (!reloc_sym) {
822 		pr_warning("Relocated base symbol is not found!\n");
823 		return -EINVAL;
824 	}
825 
826 	for (i = 0; i < ntevs; i++) {
827 		if (!tevs[i].point.address)
828 			continue;
829 		if (tevs[i].point.retprobe && !kretprobe_offset_is_supported())
830 			continue;
831 		/*
832 		 * If we found a wrong one, mark it by NULL symbol.
833 		 * Since addresses in debuginfo is same as objdump, we need
834 		 * to convert it to addresses on memory.
835 		 */
836 		if (kprobe_warn_out_range(tevs[i].point.symbol,
837 			map__objdump_2mem(map, tevs[i].point.address))) {
838 			tmp = NULL;
839 			skipped++;
840 		} else {
841 			tmp = strdup(reloc_sym->name);
842 			if (!tmp)
843 				return -ENOMEM;
844 		}
845 		/* If we have no realname, use symbol for it */
846 		if (!tevs[i].point.realname)
847 			tevs[i].point.realname = tevs[i].point.symbol;
848 		else
849 			free(tevs[i].point.symbol);
850 		tevs[i].point.symbol = tmp;
851 		tevs[i].point.offset = tevs[i].point.address -
852 			(map->reloc ? reloc_sym->unrelocated_addr :
853 				      reloc_sym->addr);
854 	}
855 	return skipped;
856 }
857 
858 void __weak
859 arch__post_process_probe_trace_events(struct perf_probe_event *pev __maybe_unused,
860 				      int ntevs __maybe_unused)
861 {
862 }
863 
864 /* Post processing the probe events */
865 static int post_process_probe_trace_events(struct perf_probe_event *pev,
866 					   struct probe_trace_event *tevs,
867 					   int ntevs, const char *module,
868 					   bool uprobe, struct debuginfo *dinfo)
869 {
870 	int ret;
871 
872 	if (uprobe)
873 		ret = add_exec_to_probe_trace_events(tevs, ntevs, module,
874 						     pev->nsi);
875 	else if (module)
876 		/* Currently ref_reloc_sym based probe is not for drivers */
877 		ret = post_process_module_probe_trace_events(tevs, ntevs,
878 							     module, dinfo);
879 	else
880 		ret = post_process_kernel_probe_trace_events(tevs, ntevs);
881 
882 	if (ret >= 0)
883 		arch__post_process_probe_trace_events(pev, ntevs);
884 
885 	return ret;
886 }
887 
888 /* Try to find perf_probe_event with debuginfo */
889 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
890 					  struct probe_trace_event **tevs)
891 {
892 	bool need_dwarf = perf_probe_event_need_dwarf(pev);
893 	struct perf_probe_point tmp;
894 	struct debuginfo *dinfo;
895 	int ntevs, ret = 0;
896 
897 	dinfo = open_debuginfo(pev->target, pev->nsi, !need_dwarf);
898 	if (!dinfo) {
899 		if (need_dwarf)
900 			return -ENOENT;
901 		pr_debug("Could not open debuginfo. Try to use symbols.\n");
902 		return 0;
903 	}
904 
905 	pr_debug("Try to find probe point from debuginfo.\n");
906 	/* Searching trace events corresponding to a probe event */
907 	ntevs = debuginfo__find_trace_events(dinfo, pev, tevs);
908 
909 	if (ntevs == 0)	{  /* Not found, retry with an alternative */
910 		ret = get_alternative_probe_event(dinfo, pev, &tmp);
911 		if (!ret) {
912 			ntevs = debuginfo__find_trace_events(dinfo, pev, tevs);
913 			/*
914 			 * Write back to the original probe_event for
915 			 * setting appropriate (user given) event name
916 			 */
917 			clear_perf_probe_point(&pev->point);
918 			memcpy(&pev->point, &tmp, sizeof(tmp));
919 		}
920 	}
921 
922 	if (ntevs > 0) {	/* Succeeded to find trace events */
923 		pr_debug("Found %d probe_trace_events.\n", ntevs);
924 		ret = post_process_probe_trace_events(pev, *tevs, ntevs,
925 					pev->target, pev->uprobes, dinfo);
926 		if (ret < 0 || ret == ntevs) {
927 			pr_debug("Post processing failed or all events are skipped. (%d)\n", ret);
928 			clear_probe_trace_events(*tevs, ntevs);
929 			zfree(tevs);
930 			ntevs = 0;
931 		}
932 	}
933 
934 	debuginfo__delete(dinfo);
935 
936 	if (ntevs == 0)	{	/* No error but failed to find probe point. */
937 		pr_warning("Probe point '%s' not found.\n",
938 			   synthesize_perf_probe_point(&pev->point));
939 		return -ENOENT;
940 	} else if (ntevs < 0) {
941 		/* Error path : ntevs < 0 */
942 		pr_debug("An error occurred in debuginfo analysis (%d).\n", ntevs);
943 		if (ntevs == -EBADF)
944 			pr_warning("Warning: No dwarf info found in the vmlinux - "
945 				"please rebuild kernel with CONFIG_DEBUG_INFO=y.\n");
946 		if (!need_dwarf) {
947 			pr_debug("Trying to use symbols.\n");
948 			return 0;
949 		}
950 	}
951 	return ntevs;
952 }
953 
954 #define LINEBUF_SIZE 256
955 #define NR_ADDITIONAL_LINES 2
956 
957 static int __show_one_line(FILE *fp, int l, bool skip, bool show_num)
958 {
959 	char buf[LINEBUF_SIZE], sbuf[STRERR_BUFSIZE];
960 	const char *color = show_num ? "" : PERF_COLOR_BLUE;
961 	const char *prefix = NULL;
962 
963 	do {
964 		if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
965 			goto error;
966 		if (skip)
967 			continue;
968 		if (!prefix) {
969 			prefix = show_num ? "%7d  " : "         ";
970 			color_fprintf(stdout, color, prefix, l);
971 		}
972 		color_fprintf(stdout, color, "%s", buf);
973 
974 	} while (strchr(buf, '\n') == NULL);
975 
976 	return 1;
977 error:
978 	if (ferror(fp)) {
979 		pr_warning("File read error: %s\n",
980 			   str_error_r(errno, sbuf, sizeof(sbuf)));
981 		return -1;
982 	}
983 	return 0;
984 }
985 
986 static int _show_one_line(FILE *fp, int l, bool skip, bool show_num)
987 {
988 	int rv = __show_one_line(fp, l, skip, show_num);
989 	if (rv == 0) {
990 		pr_warning("Source file is shorter than expected.\n");
991 		rv = -1;
992 	}
993 	return rv;
994 }
995 
996 #define show_one_line_with_num(f,l)	_show_one_line(f,l,false,true)
997 #define show_one_line(f,l)		_show_one_line(f,l,false,false)
998 #define skip_one_line(f,l)		_show_one_line(f,l,true,false)
999 #define show_one_line_or_eof(f,l)	__show_one_line(f,l,false,false)
1000 
1001 /*
1002  * Show line-range always requires debuginfo to find source file and
1003  * line number.
1004  */
1005 static int __show_line_range(struct line_range *lr, const char *module,
1006 			     bool user)
1007 {
1008 	struct build_id bid;
1009 	int l = 1;
1010 	struct int_node *ln;
1011 	struct debuginfo *dinfo;
1012 	FILE *fp;
1013 	int ret;
1014 	char *tmp;
1015 	char sbuf[STRERR_BUFSIZE];
1016 	char sbuild_id[SBUILD_ID_SIZE] = "";
1017 
1018 	/* Search a line range */
1019 	dinfo = open_debuginfo(module, NULL, false);
1020 	if (!dinfo)
1021 		return -ENOENT;
1022 
1023 	ret = debuginfo__find_line_range(dinfo, lr);
1024 	if (!ret) {	/* Not found, retry with an alternative */
1025 		ret = get_alternative_line_range(dinfo, lr, module, user);
1026 		if (!ret)
1027 			ret = debuginfo__find_line_range(dinfo, lr);
1028 	}
1029 	if (dinfo->build_id) {
1030 		build_id__init(&bid, dinfo->build_id, BUILD_ID_SIZE);
1031 		build_id__sprintf(&bid, sbuild_id);
1032 	}
1033 	debuginfo__delete(dinfo);
1034 	if (ret == 0 || ret == -ENOENT) {
1035 		pr_warning("Specified source line is not found.\n");
1036 		return -ENOENT;
1037 	} else if (ret < 0) {
1038 		pr_warning("Debuginfo analysis failed.\n");
1039 		return ret;
1040 	}
1041 
1042 	/* Convert source file path */
1043 	tmp = lr->path;
1044 	ret = find_source_path(tmp, sbuild_id, lr->comp_dir, &lr->path);
1045 
1046 	/* Free old path when new path is assigned */
1047 	if (tmp != lr->path)
1048 		free(tmp);
1049 
1050 	if (ret < 0) {
1051 		pr_warning("Failed to find source file path.\n");
1052 		return ret;
1053 	}
1054 
1055 	setup_pager();
1056 
1057 	if (lr->function)
1058 		fprintf(stdout, "<%s@%s:%d>\n", lr->function, lr->path,
1059 			lr->start - lr->offset);
1060 	else
1061 		fprintf(stdout, "<%s:%d>\n", lr->path, lr->start);
1062 
1063 	fp = fopen(lr->path, "r");
1064 	if (fp == NULL) {
1065 		pr_warning("Failed to open %s: %s\n", lr->path,
1066 			   str_error_r(errno, sbuf, sizeof(sbuf)));
1067 		return -errno;
1068 	}
1069 	/* Skip to starting line number */
1070 	while (l < lr->start) {
1071 		ret = skip_one_line(fp, l++);
1072 		if (ret < 0)
1073 			goto end;
1074 	}
1075 
1076 	intlist__for_each_entry(ln, lr->line_list) {
1077 		for (; ln->i > l; l++) {
1078 			ret = show_one_line(fp, l - lr->offset);
1079 			if (ret < 0)
1080 				goto end;
1081 		}
1082 		ret = show_one_line_with_num(fp, l++ - lr->offset);
1083 		if (ret < 0)
1084 			goto end;
1085 	}
1086 
1087 	if (lr->end == INT_MAX)
1088 		lr->end = l + NR_ADDITIONAL_LINES;
1089 	while (l <= lr->end) {
1090 		ret = show_one_line_or_eof(fp, l++ - lr->offset);
1091 		if (ret <= 0)
1092 			break;
1093 	}
1094 end:
1095 	fclose(fp);
1096 	return ret;
1097 }
1098 
1099 int show_line_range(struct line_range *lr, const char *module,
1100 		    struct nsinfo *nsi, bool user)
1101 {
1102 	int ret;
1103 	struct nscookie nsc;
1104 
1105 	ret = init_probe_symbol_maps(user);
1106 	if (ret < 0)
1107 		return ret;
1108 	nsinfo__mountns_enter(nsi, &nsc);
1109 	ret = __show_line_range(lr, module, user);
1110 	nsinfo__mountns_exit(&nsc);
1111 	exit_probe_symbol_maps();
1112 
1113 	return ret;
1114 }
1115 
1116 static int show_available_vars_at(struct debuginfo *dinfo,
1117 				  struct perf_probe_event *pev,
1118 				  struct strfilter *_filter)
1119 {
1120 	char *buf;
1121 	int ret, i, nvars;
1122 	struct str_node *node;
1123 	struct variable_list *vls = NULL, *vl;
1124 	struct perf_probe_point tmp;
1125 	const char *var;
1126 
1127 	buf = synthesize_perf_probe_point(&pev->point);
1128 	if (!buf)
1129 		return -EINVAL;
1130 	pr_debug("Searching variables at %s\n", buf);
1131 
1132 	ret = debuginfo__find_available_vars_at(dinfo, pev, &vls);
1133 	if (!ret) {  /* Not found, retry with an alternative */
1134 		ret = get_alternative_probe_event(dinfo, pev, &tmp);
1135 		if (!ret) {
1136 			ret = debuginfo__find_available_vars_at(dinfo, pev,
1137 								&vls);
1138 			/* Release the old probe_point */
1139 			clear_perf_probe_point(&tmp);
1140 		}
1141 	}
1142 	if (ret <= 0) {
1143 		if (ret == 0 || ret == -ENOENT) {
1144 			pr_err("Failed to find the address of %s\n", buf);
1145 			ret = -ENOENT;
1146 		} else
1147 			pr_warning("Debuginfo analysis failed.\n");
1148 		goto end;
1149 	}
1150 
1151 	/* Some variables are found */
1152 	fprintf(stdout, "Available variables at %s\n", buf);
1153 	for (i = 0; i < ret; i++) {
1154 		vl = &vls[i];
1155 		/*
1156 		 * A probe point might be converted to
1157 		 * several trace points.
1158 		 */
1159 		fprintf(stdout, "\t@<%s+%lu>\n", vl->point.symbol,
1160 			vl->point.offset);
1161 		zfree(&vl->point.symbol);
1162 		nvars = 0;
1163 		if (vl->vars) {
1164 			strlist__for_each_entry(node, vl->vars) {
1165 				var = strchr(node->s, '\t') + 1;
1166 				if (strfilter__compare(_filter, var)) {
1167 					fprintf(stdout, "\t\t%s\n", node->s);
1168 					nvars++;
1169 				}
1170 			}
1171 			strlist__delete(vl->vars);
1172 		}
1173 		if (nvars == 0)
1174 			fprintf(stdout, "\t\t(No matched variables)\n");
1175 	}
1176 	free(vls);
1177 end:
1178 	free(buf);
1179 	return ret;
1180 }
1181 
1182 /* Show available variables on given probe point */
1183 int show_available_vars(struct perf_probe_event *pevs, int npevs,
1184 			struct strfilter *_filter)
1185 {
1186 	int i, ret = 0;
1187 	struct debuginfo *dinfo;
1188 
1189 	ret = init_probe_symbol_maps(pevs->uprobes);
1190 	if (ret < 0)
1191 		return ret;
1192 
1193 	dinfo = open_debuginfo(pevs->target, pevs->nsi, false);
1194 	if (!dinfo) {
1195 		ret = -ENOENT;
1196 		goto out;
1197 	}
1198 
1199 	setup_pager();
1200 
1201 	for (i = 0; i < npevs && ret >= 0; i++)
1202 		ret = show_available_vars_at(dinfo, &pevs[i], _filter);
1203 
1204 	debuginfo__delete(dinfo);
1205 out:
1206 	exit_probe_symbol_maps();
1207 	return ret;
1208 }
1209 
1210 #else	/* !HAVE_DWARF_SUPPORT */
1211 
1212 static void debuginfo_cache__exit(void)
1213 {
1214 }
1215 
1216 static int
1217 find_perf_probe_point_from_dwarf(struct probe_trace_point *tp __maybe_unused,
1218 				 struct perf_probe_point *pp __maybe_unused,
1219 				 bool is_kprobe __maybe_unused)
1220 {
1221 	return -ENOSYS;
1222 }
1223 
1224 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
1225 				struct probe_trace_event **tevs __maybe_unused)
1226 {
1227 	if (perf_probe_event_need_dwarf(pev)) {
1228 		pr_warning("Debuginfo-analysis is not supported.\n");
1229 		return -ENOSYS;
1230 	}
1231 
1232 	return 0;
1233 }
1234 
1235 int show_line_range(struct line_range *lr __maybe_unused,
1236 		    const char *module __maybe_unused,
1237 		    struct nsinfo *nsi __maybe_unused,
1238 		    bool user __maybe_unused)
1239 {
1240 	pr_warning("Debuginfo-analysis is not supported.\n");
1241 	return -ENOSYS;
1242 }
1243 
1244 int show_available_vars(struct perf_probe_event *pevs __maybe_unused,
1245 			int npevs __maybe_unused,
1246 			struct strfilter *filter __maybe_unused)
1247 {
1248 	pr_warning("Debuginfo-analysis is not supported.\n");
1249 	return -ENOSYS;
1250 }
1251 #endif
1252 
1253 void line_range__clear(struct line_range *lr)
1254 {
1255 	zfree(&lr->function);
1256 	zfree(&lr->file);
1257 	zfree(&lr->path);
1258 	zfree(&lr->comp_dir);
1259 	intlist__delete(lr->line_list);
1260 }
1261 
1262 int line_range__init(struct line_range *lr)
1263 {
1264 	memset(lr, 0, sizeof(*lr));
1265 	lr->line_list = intlist__new(NULL);
1266 	if (!lr->line_list)
1267 		return -ENOMEM;
1268 	else
1269 		return 0;
1270 }
1271 
1272 static int parse_line_num(char **ptr, int *val, const char *what)
1273 {
1274 	const char *start = *ptr;
1275 
1276 	errno = 0;
1277 	*val = strtol(*ptr, ptr, 0);
1278 	if (errno || *ptr == start) {
1279 		semantic_error("'%s' is not a valid number.\n", what);
1280 		return -EINVAL;
1281 	}
1282 	return 0;
1283 }
1284 
1285 /* Check the name is good for event, group or function */
1286 static bool is_c_func_name(const char *name)
1287 {
1288 	if (!isalpha(*name) && *name != '_')
1289 		return false;
1290 	while (*++name != '\0') {
1291 		if (!isalpha(*name) && !isdigit(*name) && *name != '_')
1292 			return false;
1293 	}
1294 	return true;
1295 }
1296 
1297 /*
1298  * Stuff 'lr' according to the line range described by 'arg'.
1299  * The line range syntax is described by:
1300  *
1301  *         SRC[:SLN[+NUM|-ELN]]
1302  *         FNC[@SRC][:SLN[+NUM|-ELN]]
1303  */
1304 int parse_line_range_desc(const char *arg, struct line_range *lr)
1305 {
1306 	char *range, *file, *name = strdup(arg);
1307 	int err;
1308 
1309 	if (!name)
1310 		return -ENOMEM;
1311 
1312 	lr->start = 0;
1313 	lr->end = INT_MAX;
1314 
1315 	range = strchr(name, ':');
1316 	if (range) {
1317 		*range++ = '\0';
1318 
1319 		err = parse_line_num(&range, &lr->start, "start line");
1320 		if (err)
1321 			goto err;
1322 
1323 		if (*range == '+' || *range == '-') {
1324 			const char c = *range++;
1325 
1326 			err = parse_line_num(&range, &lr->end, "end line");
1327 			if (err)
1328 				goto err;
1329 
1330 			if (c == '+') {
1331 				lr->end += lr->start;
1332 				/*
1333 				 * Adjust the number of lines here.
1334 				 * If the number of lines == 1, the
1335 				 * the end of line should be equal to
1336 				 * the start of line.
1337 				 */
1338 				lr->end--;
1339 			}
1340 		}
1341 
1342 		pr_debug("Line range is %d to %d\n", lr->start, lr->end);
1343 
1344 		err = -EINVAL;
1345 		if (lr->start > lr->end) {
1346 			semantic_error("Start line must be smaller"
1347 				       " than end line.\n");
1348 			goto err;
1349 		}
1350 		if (*range != '\0') {
1351 			semantic_error("Tailing with invalid str '%s'.\n", range);
1352 			goto err;
1353 		}
1354 	}
1355 
1356 	file = strchr(name, '@');
1357 	if (file) {
1358 		*file = '\0';
1359 		lr->file = strdup(++file);
1360 		if (lr->file == NULL) {
1361 			err = -ENOMEM;
1362 			goto err;
1363 		}
1364 		lr->function = name;
1365 	} else if (strchr(name, '/') || strchr(name, '.'))
1366 		lr->file = name;
1367 	else if (is_c_func_name(name))/* We reuse it for checking funcname */
1368 		lr->function = name;
1369 	else {	/* Invalid name */
1370 		semantic_error("'%s' is not a valid function name.\n", name);
1371 		err = -EINVAL;
1372 		goto err;
1373 	}
1374 
1375 	return 0;
1376 err:
1377 	free(name);
1378 	return err;
1379 }
1380 
1381 static int parse_perf_probe_event_name(char **arg, struct perf_probe_event *pev)
1382 {
1383 	char *ptr;
1384 
1385 	ptr = strpbrk_esc(*arg, ":");
1386 	if (ptr) {
1387 		*ptr = '\0';
1388 		if (!pev->sdt && !is_c_func_name(*arg))
1389 			goto ng_name;
1390 		pev->group = strdup_esc(*arg);
1391 		if (!pev->group)
1392 			return -ENOMEM;
1393 		*arg = ptr + 1;
1394 	} else
1395 		pev->group = NULL;
1396 
1397 	pev->event = strdup_esc(*arg);
1398 	if (pev->event == NULL)
1399 		return -ENOMEM;
1400 
1401 	if (!pev->sdt && !is_c_func_name(pev->event)) {
1402 		zfree(&pev->event);
1403 ng_name:
1404 		zfree(&pev->group);
1405 		semantic_error("%s is bad for event name -it must "
1406 			       "follow C symbol-naming rule.\n", *arg);
1407 		return -EINVAL;
1408 	}
1409 	return 0;
1410 }
1411 
1412 /* Parse probepoint definition. */
1413 static int parse_perf_probe_point(char *arg, struct perf_probe_event *pev)
1414 {
1415 	struct perf_probe_point *pp = &pev->point;
1416 	char *ptr, *tmp;
1417 	char c, nc = 0;
1418 	bool file_spec = false;
1419 	int ret;
1420 
1421 	/*
1422 	 * <Syntax>
1423 	 * perf probe [GRP:][EVENT=]SRC[:LN|;PTN]
1424 	 * perf probe [GRP:][EVENT=]FUNC[@SRC][+OFFS|%return|:LN|;PAT]
1425 	 * perf probe %[GRP:]SDT_EVENT
1426 	 */
1427 	if (!arg)
1428 		return -EINVAL;
1429 
1430 	if (is_sdt_event(arg)) {
1431 		pev->sdt = true;
1432 		if (arg[0] == '%')
1433 			arg++;
1434 	}
1435 
1436 	ptr = strpbrk_esc(arg, ";=@+%");
1437 	if (pev->sdt) {
1438 		if (ptr) {
1439 			if (*ptr != '@') {
1440 				semantic_error("%s must be an SDT name.\n",
1441 					       arg);
1442 				return -EINVAL;
1443 			}
1444 			/* This must be a target file name or build id */
1445 			tmp = build_id_cache__complement(ptr + 1);
1446 			if (tmp) {
1447 				pev->target = build_id_cache__origname(tmp);
1448 				free(tmp);
1449 			} else
1450 				pev->target = strdup_esc(ptr + 1);
1451 			if (!pev->target)
1452 				return -ENOMEM;
1453 			*ptr = '\0';
1454 		}
1455 		ret = parse_perf_probe_event_name(&arg, pev);
1456 		if (ret == 0) {
1457 			if (asprintf(&pev->point.function, "%%%s", pev->event) < 0)
1458 				ret = -errno;
1459 		}
1460 		return ret;
1461 	}
1462 
1463 	if (ptr && *ptr == '=') {	/* Event name */
1464 		*ptr = '\0';
1465 		tmp = ptr + 1;
1466 		ret = parse_perf_probe_event_name(&arg, pev);
1467 		if (ret < 0)
1468 			return ret;
1469 
1470 		arg = tmp;
1471 	}
1472 
1473 	/*
1474 	 * Check arg is function or file name and copy it.
1475 	 *
1476 	 * We consider arg to be a file spec if and only if it satisfies
1477 	 * all of the below criteria::
1478 	 * - it does not include any of "+@%",
1479 	 * - it includes one of ":;", and
1480 	 * - it has a period '.' in the name.
1481 	 *
1482 	 * Otherwise, we consider arg to be a function specification.
1483 	 */
1484 	if (!strpbrk_esc(arg, "+@%")) {
1485 		ptr = strpbrk_esc(arg, ";:");
1486 		/* This is a file spec if it includes a '.' before ; or : */
1487 		if (ptr && memchr(arg, '.', ptr - arg))
1488 			file_spec = true;
1489 	}
1490 
1491 	ptr = strpbrk_esc(arg, ";:+@%");
1492 	if (ptr) {
1493 		nc = *ptr;
1494 		*ptr++ = '\0';
1495 	}
1496 
1497 	if (arg[0] == '\0')
1498 		tmp = NULL;
1499 	else {
1500 		tmp = strdup_esc(arg);
1501 		if (tmp == NULL)
1502 			return -ENOMEM;
1503 	}
1504 
1505 	if (file_spec)
1506 		pp->file = tmp;
1507 	else {
1508 		pp->function = tmp;
1509 
1510 		/*
1511 		 * Keep pp->function even if this is absolute address,
1512 		 * so it can mark whether abs_address is valid.
1513 		 * Which make 'perf probe lib.bin 0x0' possible.
1514 		 *
1515 		 * Note that checking length of tmp is not needed
1516 		 * because when we access tmp[1] we know tmp[0] is '0',
1517 		 * so tmp[1] should always valid (but could be '\0').
1518 		 */
1519 		if (tmp && !strncmp(tmp, "0x", 2)) {
1520 			pp->abs_address = strtoul(pp->function, &tmp, 0);
1521 			if (*tmp != '\0') {
1522 				semantic_error("Invalid absolute address.\n");
1523 				return -EINVAL;
1524 			}
1525 		}
1526 	}
1527 
1528 	/* Parse other options */
1529 	while (ptr) {
1530 		arg = ptr;
1531 		c = nc;
1532 		if (c == ';') {	/* Lazy pattern must be the last part */
1533 			pp->lazy_line = strdup(arg); /* let leave escapes */
1534 			if (pp->lazy_line == NULL)
1535 				return -ENOMEM;
1536 			break;
1537 		}
1538 		ptr = strpbrk_esc(arg, ";:+@%");
1539 		if (ptr) {
1540 			nc = *ptr;
1541 			*ptr++ = '\0';
1542 		}
1543 		switch (c) {
1544 		case ':':	/* Line number */
1545 			pp->line = strtoul(arg, &tmp, 0);
1546 			if (*tmp != '\0') {
1547 				semantic_error("There is non-digit char"
1548 					       " in line number.\n");
1549 				return -EINVAL;
1550 			}
1551 			break;
1552 		case '+':	/* Byte offset from a symbol */
1553 			pp->offset = strtoul(arg, &tmp, 0);
1554 			if (*tmp != '\0') {
1555 				semantic_error("There is non-digit character"
1556 						" in offset.\n");
1557 				return -EINVAL;
1558 			}
1559 			break;
1560 		case '@':	/* File name */
1561 			if (pp->file) {
1562 				semantic_error("SRC@SRC is not allowed.\n");
1563 				return -EINVAL;
1564 			}
1565 			pp->file = strdup_esc(arg);
1566 			if (pp->file == NULL)
1567 				return -ENOMEM;
1568 			break;
1569 		case '%':	/* Probe places */
1570 			if (strcmp(arg, "return") == 0) {
1571 				pp->retprobe = 1;
1572 			} else {	/* Others not supported yet */
1573 				semantic_error("%%%s is not supported.\n", arg);
1574 				return -ENOTSUP;
1575 			}
1576 			break;
1577 		default:	/* Buggy case */
1578 			pr_err("This program has a bug at %s:%d.\n",
1579 				__FILE__, __LINE__);
1580 			return -ENOTSUP;
1581 			break;
1582 		}
1583 	}
1584 
1585 	/* Exclusion check */
1586 	if (pp->lazy_line && pp->line) {
1587 		semantic_error("Lazy pattern can't be used with"
1588 			       " line number.\n");
1589 		return -EINVAL;
1590 	}
1591 
1592 	if (pp->lazy_line && pp->offset) {
1593 		semantic_error("Lazy pattern can't be used with offset.\n");
1594 		return -EINVAL;
1595 	}
1596 
1597 	if (pp->line && pp->offset) {
1598 		semantic_error("Offset can't be used with line number.\n");
1599 		return -EINVAL;
1600 	}
1601 
1602 	if (!pp->line && !pp->lazy_line && pp->file && !pp->function) {
1603 		semantic_error("File always requires line number or "
1604 			       "lazy pattern.\n");
1605 		return -EINVAL;
1606 	}
1607 
1608 	if (pp->offset && !pp->function) {
1609 		semantic_error("Offset requires an entry function.\n");
1610 		return -EINVAL;
1611 	}
1612 
1613 	if ((pp->offset || pp->line || pp->lazy_line) && pp->retprobe) {
1614 		semantic_error("Offset/Line/Lazy pattern can't be used with "
1615 			       "return probe.\n");
1616 		return -EINVAL;
1617 	}
1618 
1619 	pr_debug("symbol:%s file:%s line:%d offset:%lu return:%d lazy:%s\n",
1620 		 pp->function, pp->file, pp->line, pp->offset, pp->retprobe,
1621 		 pp->lazy_line);
1622 	return 0;
1623 }
1624 
1625 /* Parse perf-probe event argument */
1626 static int parse_perf_probe_arg(char *str, struct perf_probe_arg *arg)
1627 {
1628 	char *tmp, *goodname;
1629 	struct perf_probe_arg_field **fieldp;
1630 
1631 	pr_debug("parsing arg: %s into ", str);
1632 
1633 	tmp = strchr(str, '=');
1634 	if (tmp) {
1635 		arg->name = strndup(str, tmp - str);
1636 		if (arg->name == NULL)
1637 			return -ENOMEM;
1638 		pr_debug("name:%s ", arg->name);
1639 		str = tmp + 1;
1640 	}
1641 
1642 	tmp = strchr(str, '@');
1643 	if (tmp && tmp != str && !strcmp(tmp + 1, "user")) { /* user attr */
1644 		if (!user_access_is_supported()) {
1645 			semantic_error("ftrace does not support user access\n");
1646 			return -EINVAL;
1647 		}
1648 		*tmp = '\0';
1649 		arg->user_access = true;
1650 		pr_debug("user_access ");
1651 	}
1652 
1653 	tmp = strchr(str, ':');
1654 	if (tmp) {	/* Type setting */
1655 		*tmp = '\0';
1656 		arg->type = strdup(tmp + 1);
1657 		if (arg->type == NULL)
1658 			return -ENOMEM;
1659 		pr_debug("type:%s ", arg->type);
1660 	}
1661 
1662 	tmp = strpbrk(str, "-.[");
1663 	if (!is_c_varname(str) || !tmp) {
1664 		/* A variable, register, symbol or special value */
1665 		arg->var = strdup(str);
1666 		if (arg->var == NULL)
1667 			return -ENOMEM;
1668 		pr_debug("%s\n", arg->var);
1669 		return 0;
1670 	}
1671 
1672 	/* Structure fields or array element */
1673 	arg->var = strndup(str, tmp - str);
1674 	if (arg->var == NULL)
1675 		return -ENOMEM;
1676 	goodname = arg->var;
1677 	pr_debug("%s, ", arg->var);
1678 	fieldp = &arg->field;
1679 
1680 	do {
1681 		*fieldp = zalloc(sizeof(struct perf_probe_arg_field));
1682 		if (*fieldp == NULL)
1683 			return -ENOMEM;
1684 		if (*tmp == '[') {	/* Array */
1685 			str = tmp;
1686 			(*fieldp)->index = strtol(str + 1, &tmp, 0);
1687 			(*fieldp)->ref = true;
1688 			if (*tmp != ']' || tmp == str + 1) {
1689 				semantic_error("Array index must be a"
1690 						" number.\n");
1691 				return -EINVAL;
1692 			}
1693 			tmp++;
1694 			if (*tmp == '\0')
1695 				tmp = NULL;
1696 		} else {		/* Structure */
1697 			if (*tmp == '.') {
1698 				str = tmp + 1;
1699 				(*fieldp)->ref = false;
1700 			} else if (tmp[1] == '>') {
1701 				str = tmp + 2;
1702 				(*fieldp)->ref = true;
1703 			} else {
1704 				semantic_error("Argument parse error: %s\n",
1705 					       str);
1706 				return -EINVAL;
1707 			}
1708 			tmp = strpbrk(str, "-.[");
1709 		}
1710 		if (tmp) {
1711 			(*fieldp)->name = strndup(str, tmp - str);
1712 			if ((*fieldp)->name == NULL)
1713 				return -ENOMEM;
1714 			if (*str != '[')
1715 				goodname = (*fieldp)->name;
1716 			pr_debug("%s(%d), ", (*fieldp)->name, (*fieldp)->ref);
1717 			fieldp = &(*fieldp)->next;
1718 		}
1719 	} while (tmp);
1720 	(*fieldp)->name = strdup(str);
1721 	if ((*fieldp)->name == NULL)
1722 		return -ENOMEM;
1723 	if (*str != '[')
1724 		goodname = (*fieldp)->name;
1725 	pr_debug("%s(%d)\n", (*fieldp)->name, (*fieldp)->ref);
1726 
1727 	/* If no name is specified, set the last field name (not array index)*/
1728 	if (!arg->name) {
1729 		arg->name = strdup(goodname);
1730 		if (arg->name == NULL)
1731 			return -ENOMEM;
1732 	}
1733 	return 0;
1734 }
1735 
1736 /* Parse perf-probe event command */
1737 int parse_perf_probe_command(const char *cmd, struct perf_probe_event *pev)
1738 {
1739 	char **argv;
1740 	int argc, i, ret = 0;
1741 
1742 	argv = argv_split(cmd, &argc);
1743 	if (!argv) {
1744 		pr_debug("Failed to split arguments.\n");
1745 		return -ENOMEM;
1746 	}
1747 	if (argc - 1 > MAX_PROBE_ARGS) {
1748 		semantic_error("Too many probe arguments (%d).\n", argc - 1);
1749 		ret = -ERANGE;
1750 		goto out;
1751 	}
1752 	/* Parse probe point */
1753 	ret = parse_perf_probe_point(argv[0], pev);
1754 	if (ret < 0)
1755 		goto out;
1756 
1757 	/* Generate event name if needed */
1758 	if (!pev->event && pev->point.function && pev->point.line
1759 			&& !pev->point.lazy_line && !pev->point.offset) {
1760 		if (asprintf(&pev->event, "%s_L%d", pev->point.function,
1761 			pev->point.line) < 0)
1762 			return -ENOMEM;
1763 	}
1764 
1765 	/* Copy arguments and ensure return probe has no C argument */
1766 	pev->nargs = argc - 1;
1767 	pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1768 	if (pev->args == NULL) {
1769 		ret = -ENOMEM;
1770 		goto out;
1771 	}
1772 	for (i = 0; i < pev->nargs && ret >= 0; i++) {
1773 		ret = parse_perf_probe_arg(argv[i + 1], &pev->args[i]);
1774 		if (ret >= 0 &&
1775 		    is_c_varname(pev->args[i].var) && pev->point.retprobe) {
1776 			semantic_error("You can't specify local variable for"
1777 				       " kretprobe.\n");
1778 			ret = -EINVAL;
1779 		}
1780 	}
1781 out:
1782 	argv_free(argv);
1783 
1784 	return ret;
1785 }
1786 
1787 /* Returns true if *any* ARG is either C variable, $params or $vars. */
1788 bool perf_probe_with_var(struct perf_probe_event *pev)
1789 {
1790 	int i = 0;
1791 
1792 	for (i = 0; i < pev->nargs; i++)
1793 		if (is_c_varname(pev->args[i].var)              ||
1794 		    !strcmp(pev->args[i].var, PROBE_ARG_PARAMS) ||
1795 		    !strcmp(pev->args[i].var, PROBE_ARG_VARS))
1796 			return true;
1797 	return false;
1798 }
1799 
1800 /* Return true if this perf_probe_event requires debuginfo */
1801 bool perf_probe_event_need_dwarf(struct perf_probe_event *pev)
1802 {
1803 	if (pev->point.file || pev->point.line || pev->point.lazy_line)
1804 		return true;
1805 
1806 	if (perf_probe_with_var(pev))
1807 		return true;
1808 
1809 	return false;
1810 }
1811 
1812 /* Parse probe_events event into struct probe_point */
1813 int parse_probe_trace_command(const char *cmd, struct probe_trace_event *tev)
1814 {
1815 	struct probe_trace_point *tp = &tev->point;
1816 	char pr;
1817 	char *p;
1818 	char *argv0_str = NULL, *fmt, *fmt1_str, *fmt2_str, *fmt3_str;
1819 	int ret, i, argc;
1820 	char **argv;
1821 
1822 	pr_debug("Parsing probe_events: %s\n", cmd);
1823 	argv = argv_split(cmd, &argc);
1824 	if (!argv) {
1825 		pr_debug("Failed to split arguments.\n");
1826 		return -ENOMEM;
1827 	}
1828 	if (argc < 2) {
1829 		semantic_error("Too few probe arguments.\n");
1830 		ret = -ERANGE;
1831 		goto out;
1832 	}
1833 
1834 	/* Scan event and group name. */
1835 	argv0_str = strdup(argv[0]);
1836 	if (argv0_str == NULL) {
1837 		ret = -ENOMEM;
1838 		goto out;
1839 	}
1840 	fmt1_str = strtok_r(argv0_str, ":", &fmt);
1841 	fmt2_str = strtok_r(NULL, "/", &fmt);
1842 	fmt3_str = strtok_r(NULL, " \t", &fmt);
1843 	if (fmt1_str == NULL || fmt2_str == NULL || fmt3_str == NULL) {
1844 		semantic_error("Failed to parse event name: %s\n", argv[0]);
1845 		ret = -EINVAL;
1846 		goto out;
1847 	}
1848 	pr = fmt1_str[0];
1849 	tev->group = strdup(fmt2_str);
1850 	tev->event = strdup(fmt3_str);
1851 	if (tev->group == NULL || tev->event == NULL) {
1852 		ret = -ENOMEM;
1853 		goto out;
1854 	}
1855 	pr_debug("Group:%s Event:%s probe:%c\n", tev->group, tev->event, pr);
1856 
1857 	tp->retprobe = (pr == 'r');
1858 
1859 	/* Scan module name(if there), function name and offset */
1860 	p = strchr(argv[1], ':');
1861 	if (p) {
1862 		tp->module = strndup(argv[1], p - argv[1]);
1863 		if (!tp->module) {
1864 			ret = -ENOMEM;
1865 			goto out;
1866 		}
1867 		tev->uprobes = (tp->module[0] == '/');
1868 		p++;
1869 	} else
1870 		p = argv[1];
1871 	fmt1_str = strtok_r(p, "+", &fmt);
1872 	/* only the address started with 0x */
1873 	if (fmt1_str[0] == '0')	{
1874 		/*
1875 		 * Fix a special case:
1876 		 * if address == 0, kernel reports something like:
1877 		 * p:probe_libc/abs_0 /lib/libc-2.18.so:0x          (null) arg1=%ax
1878 		 * Newer kernel may fix that, but we want to
1879 		 * support old kernel also.
1880 		 */
1881 		if (strcmp(fmt1_str, "0x") == 0) {
1882 			if (!argv[2] || strcmp(argv[2], "(null)")) {
1883 				ret = -EINVAL;
1884 				goto out;
1885 			}
1886 			tp->address = 0;
1887 
1888 			free(argv[2]);
1889 			for (i = 2; argv[i + 1] != NULL; i++)
1890 				argv[i] = argv[i + 1];
1891 
1892 			argv[i] = NULL;
1893 			argc -= 1;
1894 		} else
1895 			tp->address = strtoul(fmt1_str, NULL, 0);
1896 	} else {
1897 		/* Only the symbol-based probe has offset */
1898 		tp->symbol = strdup(fmt1_str);
1899 		if (tp->symbol == NULL) {
1900 			ret = -ENOMEM;
1901 			goto out;
1902 		}
1903 		fmt2_str = strtok_r(NULL, "", &fmt);
1904 		if (fmt2_str == NULL)
1905 			tp->offset = 0;
1906 		else
1907 			tp->offset = strtoul(fmt2_str, NULL, 10);
1908 	}
1909 
1910 	if (tev->uprobes) {
1911 		fmt2_str = strchr(p, '(');
1912 		if (fmt2_str)
1913 			tp->ref_ctr_offset = strtoul(fmt2_str + 1, NULL, 0);
1914 	}
1915 
1916 	tev->nargs = argc - 2;
1917 	tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
1918 	if (tev->args == NULL) {
1919 		ret = -ENOMEM;
1920 		goto out;
1921 	}
1922 	for (i = 0; i < tev->nargs; i++) {
1923 		p = strchr(argv[i + 2], '=');
1924 		if (p)	/* We don't need which register is assigned. */
1925 			*p++ = '\0';
1926 		else
1927 			p = argv[i + 2];
1928 		tev->args[i].name = strdup(argv[i + 2]);
1929 		/* TODO: parse regs and offset */
1930 		tev->args[i].value = strdup(p);
1931 		if (tev->args[i].name == NULL || tev->args[i].value == NULL) {
1932 			ret = -ENOMEM;
1933 			goto out;
1934 		}
1935 	}
1936 	ret = 0;
1937 out:
1938 	free(argv0_str);
1939 	argv_free(argv);
1940 	return ret;
1941 }
1942 
1943 /* Compose only probe arg */
1944 char *synthesize_perf_probe_arg(struct perf_probe_arg *pa)
1945 {
1946 	struct perf_probe_arg_field *field = pa->field;
1947 	struct strbuf buf;
1948 	char *ret = NULL;
1949 	int err;
1950 
1951 	if (strbuf_init(&buf, 64) < 0)
1952 		return NULL;
1953 
1954 	if (pa->name && pa->var)
1955 		err = strbuf_addf(&buf, "%s=%s", pa->name, pa->var);
1956 	else
1957 		err = strbuf_addstr(&buf, pa->name ?: pa->var);
1958 	if (err)
1959 		goto out;
1960 
1961 	while (field) {
1962 		if (field->name[0] == '[')
1963 			err = strbuf_addstr(&buf, field->name);
1964 		else
1965 			err = strbuf_addf(&buf, "%s%s", field->ref ? "->" : ".",
1966 					  field->name);
1967 		field = field->next;
1968 		if (err)
1969 			goto out;
1970 	}
1971 
1972 	if (pa->type)
1973 		if (strbuf_addf(&buf, ":%s", pa->type) < 0)
1974 			goto out;
1975 
1976 	ret = strbuf_detach(&buf, NULL);
1977 out:
1978 	strbuf_release(&buf);
1979 	return ret;
1980 }
1981 
1982 /* Compose only probe point (not argument) */
1983 char *synthesize_perf_probe_point(struct perf_probe_point *pp)
1984 {
1985 	struct strbuf buf;
1986 	char *tmp, *ret = NULL;
1987 	int len, err = 0;
1988 
1989 	if (strbuf_init(&buf, 64) < 0)
1990 		return NULL;
1991 
1992 	if (pp->function) {
1993 		if (strbuf_addstr(&buf, pp->function) < 0)
1994 			goto out;
1995 		if (pp->offset)
1996 			err = strbuf_addf(&buf, "+%lu", pp->offset);
1997 		else if (pp->line)
1998 			err = strbuf_addf(&buf, ":%d", pp->line);
1999 		else if (pp->retprobe)
2000 			err = strbuf_addstr(&buf, "%return");
2001 		if (err)
2002 			goto out;
2003 	}
2004 	if (pp->file) {
2005 		tmp = pp->file;
2006 		len = strlen(tmp);
2007 		if (len > 30) {
2008 			tmp = strchr(pp->file + len - 30, '/');
2009 			tmp = tmp ? tmp + 1 : pp->file + len - 30;
2010 		}
2011 		err = strbuf_addf(&buf, "@%s", tmp);
2012 		if (!err && !pp->function && pp->line)
2013 			err = strbuf_addf(&buf, ":%d", pp->line);
2014 	}
2015 	if (!err)
2016 		ret = strbuf_detach(&buf, NULL);
2017 out:
2018 	strbuf_release(&buf);
2019 	return ret;
2020 }
2021 
2022 char *synthesize_perf_probe_command(struct perf_probe_event *pev)
2023 {
2024 	struct strbuf buf;
2025 	char *tmp, *ret = NULL;
2026 	int i;
2027 
2028 	if (strbuf_init(&buf, 64))
2029 		return NULL;
2030 	if (pev->event)
2031 		if (strbuf_addf(&buf, "%s:%s=", pev->group ?: PERFPROBE_GROUP,
2032 				pev->event) < 0)
2033 			goto out;
2034 
2035 	tmp = synthesize_perf_probe_point(&pev->point);
2036 	if (!tmp || strbuf_addstr(&buf, tmp) < 0)
2037 		goto out;
2038 	free(tmp);
2039 
2040 	for (i = 0; i < pev->nargs; i++) {
2041 		tmp = synthesize_perf_probe_arg(pev->args + i);
2042 		if (!tmp || strbuf_addf(&buf, " %s", tmp) < 0)
2043 			goto out;
2044 		free(tmp);
2045 	}
2046 
2047 	ret = strbuf_detach(&buf, NULL);
2048 out:
2049 	strbuf_release(&buf);
2050 	return ret;
2051 }
2052 
2053 static int __synthesize_probe_trace_arg_ref(struct probe_trace_arg_ref *ref,
2054 					    struct strbuf *buf, int depth)
2055 {
2056 	int err;
2057 	if (ref->next) {
2058 		depth = __synthesize_probe_trace_arg_ref(ref->next, buf,
2059 							 depth + 1);
2060 		if (depth < 0)
2061 			return depth;
2062 	}
2063 	if (ref->user_access)
2064 		err = strbuf_addf(buf, "%s%ld(", "+u", ref->offset);
2065 	else
2066 		err = strbuf_addf(buf, "%+ld(", ref->offset);
2067 	return (err < 0) ? err : depth;
2068 }
2069 
2070 static int synthesize_probe_trace_arg(struct probe_trace_arg *arg,
2071 				      struct strbuf *buf)
2072 {
2073 	struct probe_trace_arg_ref *ref = arg->ref;
2074 	int depth = 0, err;
2075 
2076 	/* Argument name or separator */
2077 	if (arg->name)
2078 		err = strbuf_addf(buf, " %s=", arg->name);
2079 	else
2080 		err = strbuf_addch(buf, ' ');
2081 	if (err)
2082 		return err;
2083 
2084 	/* Special case: @XXX */
2085 	if (arg->value[0] == '@' && arg->ref)
2086 			ref = ref->next;
2087 
2088 	/* Dereferencing arguments */
2089 	if (ref) {
2090 		depth = __synthesize_probe_trace_arg_ref(ref, buf, 1);
2091 		if (depth < 0)
2092 			return depth;
2093 	}
2094 
2095 	/* Print argument value */
2096 	if (arg->value[0] == '@' && arg->ref)
2097 		err = strbuf_addf(buf, "%s%+ld", arg->value, arg->ref->offset);
2098 	else
2099 		err = strbuf_addstr(buf, arg->value);
2100 
2101 	/* Closing */
2102 	while (!err && depth--)
2103 		err = strbuf_addch(buf, ')');
2104 
2105 	/* Print argument type */
2106 	if (!err && arg->type)
2107 		err = strbuf_addf(buf, ":%s", arg->type);
2108 
2109 	return err;
2110 }
2111 
2112 static int
2113 synthesize_uprobe_trace_def(struct probe_trace_event *tev, struct strbuf *buf)
2114 {
2115 	struct probe_trace_point *tp = &tev->point;
2116 	int err;
2117 
2118 	err = strbuf_addf(buf, "%s:0x%lx", tp->module, tp->address);
2119 
2120 	if (err >= 0 && tp->ref_ctr_offset) {
2121 		if (!uprobe_ref_ctr_is_supported())
2122 			return -1;
2123 		err = strbuf_addf(buf, "(0x%lx)", tp->ref_ctr_offset);
2124 	}
2125 	return err >= 0 ? 0 : -1;
2126 }
2127 
2128 char *synthesize_probe_trace_command(struct probe_trace_event *tev)
2129 {
2130 	struct probe_trace_point *tp = &tev->point;
2131 	struct strbuf buf;
2132 	char *ret = NULL;
2133 	int i, err;
2134 
2135 	/* Uprobes must have tp->module */
2136 	if (tev->uprobes && !tp->module)
2137 		return NULL;
2138 
2139 	if (strbuf_init(&buf, 32) < 0)
2140 		return NULL;
2141 
2142 	if (strbuf_addf(&buf, "%c:%s/%s ", tp->retprobe ? 'r' : 'p',
2143 			tev->group, tev->event) < 0)
2144 		goto error;
2145 	/*
2146 	 * If tp->address == 0, then this point must be a
2147 	 * absolute address uprobe.
2148 	 * try_to_find_absolute_address() should have made
2149 	 * tp->symbol to "0x0".
2150 	 */
2151 	if (tev->uprobes && !tp->address) {
2152 		if (!tp->symbol || strcmp(tp->symbol, "0x0"))
2153 			goto error;
2154 	}
2155 
2156 	/* Use the tp->address for uprobes */
2157 	if (tev->uprobes) {
2158 		err = synthesize_uprobe_trace_def(tev, &buf);
2159 	} else if (!strncmp(tp->symbol, "0x", 2)) {
2160 		/* Absolute address. See try_to_find_absolute_address() */
2161 		err = strbuf_addf(&buf, "%s%s0x%lx", tp->module ?: "",
2162 				  tp->module ? ":" : "", tp->address);
2163 	} else {
2164 		err = strbuf_addf(&buf, "%s%s%s+%lu", tp->module ?: "",
2165 				tp->module ? ":" : "", tp->symbol, tp->offset);
2166 	}
2167 
2168 	if (err)
2169 		goto error;
2170 
2171 	for (i = 0; i < tev->nargs; i++)
2172 		if (synthesize_probe_trace_arg(&tev->args[i], &buf) < 0)
2173 			goto error;
2174 
2175 	ret = strbuf_detach(&buf, NULL);
2176 error:
2177 	strbuf_release(&buf);
2178 	return ret;
2179 }
2180 
2181 static int find_perf_probe_point_from_map(struct probe_trace_point *tp,
2182 					  struct perf_probe_point *pp,
2183 					  bool is_kprobe)
2184 {
2185 	struct symbol *sym = NULL;
2186 	struct map *map = NULL;
2187 	u64 addr = tp->address;
2188 	int ret = -ENOENT;
2189 
2190 	if (!is_kprobe) {
2191 		map = dso__new_map(tp->module);
2192 		if (!map)
2193 			goto out;
2194 		sym = map__find_symbol(map, addr);
2195 	} else {
2196 		if (tp->symbol && !addr) {
2197 			if (kernel_get_symbol_address_by_name(tp->symbol,
2198 						&addr, true, false) < 0)
2199 				goto out;
2200 		}
2201 		if (addr) {
2202 			addr += tp->offset;
2203 			sym = machine__find_kernel_symbol(host_machine, addr, &map);
2204 		}
2205 	}
2206 
2207 	if (!sym)
2208 		goto out;
2209 
2210 	pp->retprobe = tp->retprobe;
2211 	pp->offset = addr - map->unmap_ip(map, sym->start);
2212 	pp->function = strdup(sym->name);
2213 	ret = pp->function ? 0 : -ENOMEM;
2214 
2215 out:
2216 	if (map && !is_kprobe) {
2217 		map__put(map);
2218 	}
2219 
2220 	return ret;
2221 }
2222 
2223 static int convert_to_perf_probe_point(struct probe_trace_point *tp,
2224 				       struct perf_probe_point *pp,
2225 				       bool is_kprobe)
2226 {
2227 	char buf[128];
2228 	int ret;
2229 
2230 	ret = find_perf_probe_point_from_dwarf(tp, pp, is_kprobe);
2231 	if (!ret)
2232 		return 0;
2233 	ret = find_perf_probe_point_from_map(tp, pp, is_kprobe);
2234 	if (!ret)
2235 		return 0;
2236 
2237 	pr_debug("Failed to find probe point from both of dwarf and map.\n");
2238 
2239 	if (tp->symbol) {
2240 		pp->function = strdup(tp->symbol);
2241 		pp->offset = tp->offset;
2242 	} else {
2243 		ret = e_snprintf(buf, 128, "0x%" PRIx64, (u64)tp->address);
2244 		if (ret < 0)
2245 			return ret;
2246 		pp->function = strdup(buf);
2247 		pp->offset = 0;
2248 	}
2249 	if (pp->function == NULL)
2250 		return -ENOMEM;
2251 
2252 	pp->retprobe = tp->retprobe;
2253 
2254 	return 0;
2255 }
2256 
2257 static int convert_to_perf_probe_event(struct probe_trace_event *tev,
2258 			       struct perf_probe_event *pev, bool is_kprobe)
2259 {
2260 	struct strbuf buf = STRBUF_INIT;
2261 	int i, ret;
2262 
2263 	/* Convert event/group name */
2264 	pev->event = strdup(tev->event);
2265 	pev->group = strdup(tev->group);
2266 	if (pev->event == NULL || pev->group == NULL)
2267 		return -ENOMEM;
2268 
2269 	/* Convert trace_point to probe_point */
2270 	ret = convert_to_perf_probe_point(&tev->point, &pev->point, is_kprobe);
2271 	if (ret < 0)
2272 		return ret;
2273 
2274 	/* Convert trace_arg to probe_arg */
2275 	pev->nargs = tev->nargs;
2276 	pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
2277 	if (pev->args == NULL)
2278 		return -ENOMEM;
2279 	for (i = 0; i < tev->nargs && ret >= 0; i++) {
2280 		if (tev->args[i].name)
2281 			pev->args[i].name = strdup(tev->args[i].name);
2282 		else {
2283 			if ((ret = strbuf_init(&buf, 32)) < 0)
2284 				goto error;
2285 			ret = synthesize_probe_trace_arg(&tev->args[i], &buf);
2286 			pev->args[i].name = strbuf_detach(&buf, NULL);
2287 		}
2288 		if (pev->args[i].name == NULL && ret >= 0)
2289 			ret = -ENOMEM;
2290 	}
2291 error:
2292 	if (ret < 0)
2293 		clear_perf_probe_event(pev);
2294 
2295 	return ret;
2296 }
2297 
2298 void clear_perf_probe_event(struct perf_probe_event *pev)
2299 {
2300 	struct perf_probe_arg_field *field, *next;
2301 	int i;
2302 
2303 	zfree(&pev->event);
2304 	zfree(&pev->group);
2305 	zfree(&pev->target);
2306 	clear_perf_probe_point(&pev->point);
2307 
2308 	for (i = 0; i < pev->nargs; i++) {
2309 		zfree(&pev->args[i].name);
2310 		zfree(&pev->args[i].var);
2311 		zfree(&pev->args[i].type);
2312 		field = pev->args[i].field;
2313 		while (field) {
2314 			next = field->next;
2315 			zfree(&field->name);
2316 			free(field);
2317 			field = next;
2318 		}
2319 	}
2320 	pev->nargs = 0;
2321 	zfree(&pev->args);
2322 }
2323 
2324 #define strdup_or_goto(str, label)	\
2325 ({ char *__p = NULL; if (str && !(__p = strdup(str))) goto label; __p; })
2326 
2327 static int perf_probe_point__copy(struct perf_probe_point *dst,
2328 				  struct perf_probe_point *src)
2329 {
2330 	dst->file = strdup_or_goto(src->file, out_err);
2331 	dst->function = strdup_or_goto(src->function, out_err);
2332 	dst->lazy_line = strdup_or_goto(src->lazy_line, out_err);
2333 	dst->line = src->line;
2334 	dst->retprobe = src->retprobe;
2335 	dst->offset = src->offset;
2336 	return 0;
2337 
2338 out_err:
2339 	clear_perf_probe_point(dst);
2340 	return -ENOMEM;
2341 }
2342 
2343 static int perf_probe_arg__copy(struct perf_probe_arg *dst,
2344 				struct perf_probe_arg *src)
2345 {
2346 	struct perf_probe_arg_field *field, **ppfield;
2347 
2348 	dst->name = strdup_or_goto(src->name, out_err);
2349 	dst->var = strdup_or_goto(src->var, out_err);
2350 	dst->type = strdup_or_goto(src->type, out_err);
2351 
2352 	field = src->field;
2353 	ppfield = &(dst->field);
2354 	while (field) {
2355 		*ppfield = zalloc(sizeof(*field));
2356 		if (!*ppfield)
2357 			goto out_err;
2358 		(*ppfield)->name = strdup_or_goto(field->name, out_err);
2359 		(*ppfield)->index = field->index;
2360 		(*ppfield)->ref = field->ref;
2361 		field = field->next;
2362 		ppfield = &((*ppfield)->next);
2363 	}
2364 	return 0;
2365 out_err:
2366 	return -ENOMEM;
2367 }
2368 
2369 int perf_probe_event__copy(struct perf_probe_event *dst,
2370 			   struct perf_probe_event *src)
2371 {
2372 	int i;
2373 
2374 	dst->event = strdup_or_goto(src->event, out_err);
2375 	dst->group = strdup_or_goto(src->group, out_err);
2376 	dst->target = strdup_or_goto(src->target, out_err);
2377 	dst->uprobes = src->uprobes;
2378 
2379 	if (perf_probe_point__copy(&dst->point, &src->point) < 0)
2380 		goto out_err;
2381 
2382 	dst->args = zalloc(sizeof(struct perf_probe_arg) * src->nargs);
2383 	if (!dst->args)
2384 		goto out_err;
2385 	dst->nargs = src->nargs;
2386 
2387 	for (i = 0; i < src->nargs; i++)
2388 		if (perf_probe_arg__copy(&dst->args[i], &src->args[i]) < 0)
2389 			goto out_err;
2390 	return 0;
2391 
2392 out_err:
2393 	clear_perf_probe_event(dst);
2394 	return -ENOMEM;
2395 }
2396 
2397 void clear_probe_trace_event(struct probe_trace_event *tev)
2398 {
2399 	struct probe_trace_arg_ref *ref, *next;
2400 	int i;
2401 
2402 	zfree(&tev->event);
2403 	zfree(&tev->group);
2404 	zfree(&tev->point.symbol);
2405 	zfree(&tev->point.realname);
2406 	zfree(&tev->point.module);
2407 	for (i = 0; i < tev->nargs; i++) {
2408 		zfree(&tev->args[i].name);
2409 		zfree(&tev->args[i].value);
2410 		zfree(&tev->args[i].type);
2411 		ref = tev->args[i].ref;
2412 		while (ref) {
2413 			next = ref->next;
2414 			free(ref);
2415 			ref = next;
2416 		}
2417 	}
2418 	zfree(&tev->args);
2419 	tev->nargs = 0;
2420 }
2421 
2422 struct kprobe_blacklist_node {
2423 	struct list_head list;
2424 	unsigned long start;
2425 	unsigned long end;
2426 	char *symbol;
2427 };
2428 
2429 static void kprobe_blacklist__delete(struct list_head *blacklist)
2430 {
2431 	struct kprobe_blacklist_node *node;
2432 
2433 	while (!list_empty(blacklist)) {
2434 		node = list_first_entry(blacklist,
2435 					struct kprobe_blacklist_node, list);
2436 		list_del_init(&node->list);
2437 		zfree(&node->symbol);
2438 		free(node);
2439 	}
2440 }
2441 
2442 static int kprobe_blacklist__load(struct list_head *blacklist)
2443 {
2444 	struct kprobe_blacklist_node *node;
2445 	const char *__debugfs = debugfs__mountpoint();
2446 	char buf[PATH_MAX], *p;
2447 	FILE *fp;
2448 	int ret;
2449 
2450 	if (__debugfs == NULL)
2451 		return -ENOTSUP;
2452 
2453 	ret = e_snprintf(buf, PATH_MAX, "%s/kprobes/blacklist", __debugfs);
2454 	if (ret < 0)
2455 		return ret;
2456 
2457 	fp = fopen(buf, "r");
2458 	if (!fp)
2459 		return -errno;
2460 
2461 	ret = 0;
2462 	while (fgets(buf, PATH_MAX, fp)) {
2463 		node = zalloc(sizeof(*node));
2464 		if (!node) {
2465 			ret = -ENOMEM;
2466 			break;
2467 		}
2468 		INIT_LIST_HEAD(&node->list);
2469 		list_add_tail(&node->list, blacklist);
2470 		if (sscanf(buf, "0x%lx-0x%lx", &node->start, &node->end) != 2) {
2471 			ret = -EINVAL;
2472 			break;
2473 		}
2474 		p = strchr(buf, '\t');
2475 		if (p) {
2476 			p++;
2477 			if (p[strlen(p) - 1] == '\n')
2478 				p[strlen(p) - 1] = '\0';
2479 		} else
2480 			p = (char *)"unknown";
2481 		node->symbol = strdup(p);
2482 		if (!node->symbol) {
2483 			ret = -ENOMEM;
2484 			break;
2485 		}
2486 		pr_debug2("Blacklist: 0x%lx-0x%lx, %s\n",
2487 			  node->start, node->end, node->symbol);
2488 		ret++;
2489 	}
2490 	if (ret < 0)
2491 		kprobe_blacklist__delete(blacklist);
2492 	fclose(fp);
2493 
2494 	return ret;
2495 }
2496 
2497 static struct kprobe_blacklist_node *
2498 kprobe_blacklist__find_by_address(struct list_head *blacklist,
2499 				  unsigned long address)
2500 {
2501 	struct kprobe_blacklist_node *node;
2502 
2503 	list_for_each_entry(node, blacklist, list) {
2504 		if (node->start <= address && address < node->end)
2505 			return node;
2506 	}
2507 
2508 	return NULL;
2509 }
2510 
2511 static LIST_HEAD(kprobe_blacklist);
2512 
2513 static void kprobe_blacklist__init(void)
2514 {
2515 	if (!list_empty(&kprobe_blacklist))
2516 		return;
2517 
2518 	if (kprobe_blacklist__load(&kprobe_blacklist) < 0)
2519 		pr_debug("No kprobe blacklist support, ignored\n");
2520 }
2521 
2522 static void kprobe_blacklist__release(void)
2523 {
2524 	kprobe_blacklist__delete(&kprobe_blacklist);
2525 }
2526 
2527 static bool kprobe_blacklist__listed(unsigned long address)
2528 {
2529 	return !!kprobe_blacklist__find_by_address(&kprobe_blacklist, address);
2530 }
2531 
2532 static int perf_probe_event__sprintf(const char *group, const char *event,
2533 				     struct perf_probe_event *pev,
2534 				     const char *module,
2535 				     struct strbuf *result)
2536 {
2537 	int i, ret;
2538 	char *buf;
2539 
2540 	if (asprintf(&buf, "%s:%s", group, event) < 0)
2541 		return -errno;
2542 	ret = strbuf_addf(result, "  %-20s (on ", buf);
2543 	free(buf);
2544 	if (ret)
2545 		return ret;
2546 
2547 	/* Synthesize only event probe point */
2548 	buf = synthesize_perf_probe_point(&pev->point);
2549 	if (!buf)
2550 		return -ENOMEM;
2551 	ret = strbuf_addstr(result, buf);
2552 	free(buf);
2553 
2554 	if (!ret && module)
2555 		ret = strbuf_addf(result, " in %s", module);
2556 
2557 	if (!ret && pev->nargs > 0) {
2558 		ret = strbuf_add(result, " with", 5);
2559 		for (i = 0; !ret && i < pev->nargs; i++) {
2560 			buf = synthesize_perf_probe_arg(&pev->args[i]);
2561 			if (!buf)
2562 				return -ENOMEM;
2563 			ret = strbuf_addf(result, " %s", buf);
2564 			free(buf);
2565 		}
2566 	}
2567 	if (!ret)
2568 		ret = strbuf_addch(result, ')');
2569 
2570 	return ret;
2571 }
2572 
2573 /* Show an event */
2574 int show_perf_probe_event(const char *group, const char *event,
2575 			  struct perf_probe_event *pev,
2576 			  const char *module, bool use_stdout)
2577 {
2578 	struct strbuf buf = STRBUF_INIT;
2579 	int ret;
2580 
2581 	ret = perf_probe_event__sprintf(group, event, pev, module, &buf);
2582 	if (ret >= 0) {
2583 		if (use_stdout)
2584 			printf("%s\n", buf.buf);
2585 		else
2586 			pr_info("%s\n", buf.buf);
2587 	}
2588 	strbuf_release(&buf);
2589 
2590 	return ret;
2591 }
2592 
2593 static bool filter_probe_trace_event(struct probe_trace_event *tev,
2594 				     struct strfilter *filter)
2595 {
2596 	char tmp[128];
2597 
2598 	/* At first, check the event name itself */
2599 	if (strfilter__compare(filter, tev->event))
2600 		return true;
2601 
2602 	/* Next, check the combination of name and group */
2603 	if (e_snprintf(tmp, 128, "%s:%s", tev->group, tev->event) < 0)
2604 		return false;
2605 	return strfilter__compare(filter, tmp);
2606 }
2607 
2608 static int __show_perf_probe_events(int fd, bool is_kprobe,
2609 				    struct strfilter *filter)
2610 {
2611 	int ret = 0;
2612 	struct probe_trace_event tev;
2613 	struct perf_probe_event pev;
2614 	struct strlist *rawlist;
2615 	struct str_node *ent;
2616 
2617 	memset(&tev, 0, sizeof(tev));
2618 	memset(&pev, 0, sizeof(pev));
2619 
2620 	rawlist = probe_file__get_rawlist(fd);
2621 	if (!rawlist)
2622 		return -ENOMEM;
2623 
2624 	strlist__for_each_entry(ent, rawlist) {
2625 		ret = parse_probe_trace_command(ent->s, &tev);
2626 		if (ret >= 0) {
2627 			if (!filter_probe_trace_event(&tev, filter))
2628 				goto next;
2629 			ret = convert_to_perf_probe_event(&tev, &pev,
2630 								is_kprobe);
2631 			if (ret < 0)
2632 				goto next;
2633 			ret = show_perf_probe_event(pev.group, pev.event,
2634 						    &pev, tev.point.module,
2635 						    true);
2636 		}
2637 next:
2638 		clear_perf_probe_event(&pev);
2639 		clear_probe_trace_event(&tev);
2640 		if (ret < 0)
2641 			break;
2642 	}
2643 	strlist__delete(rawlist);
2644 	/* Cleanup cached debuginfo if needed */
2645 	debuginfo_cache__exit();
2646 
2647 	return ret;
2648 }
2649 
2650 /* List up current perf-probe events */
2651 int show_perf_probe_events(struct strfilter *filter)
2652 {
2653 	int kp_fd, up_fd, ret;
2654 
2655 	setup_pager();
2656 
2657 	if (probe_conf.cache)
2658 		return probe_cache__show_all_caches(filter);
2659 
2660 	ret = init_probe_symbol_maps(false);
2661 	if (ret < 0)
2662 		return ret;
2663 
2664 	ret = probe_file__open_both(&kp_fd, &up_fd, 0);
2665 	if (ret < 0)
2666 		return ret;
2667 
2668 	if (kp_fd >= 0)
2669 		ret = __show_perf_probe_events(kp_fd, true, filter);
2670 	if (up_fd >= 0 && ret >= 0)
2671 		ret = __show_perf_probe_events(up_fd, false, filter);
2672 	if (kp_fd > 0)
2673 		close(kp_fd);
2674 	if (up_fd > 0)
2675 		close(up_fd);
2676 	exit_probe_symbol_maps();
2677 
2678 	return ret;
2679 }
2680 
2681 static int get_new_event_name(char *buf, size_t len, const char *base,
2682 			      struct strlist *namelist, bool ret_event,
2683 			      bool allow_suffix)
2684 {
2685 	int i, ret;
2686 	char *p, *nbase;
2687 
2688 	if (*base == '.')
2689 		base++;
2690 	nbase = strdup(base);
2691 	if (!nbase)
2692 		return -ENOMEM;
2693 
2694 	/* Cut off the dot suffixes (e.g. .const, .isra) and version suffixes */
2695 	p = strpbrk(nbase, ".@");
2696 	if (p && p != nbase)
2697 		*p = '\0';
2698 
2699 	/* Try no suffix number */
2700 	ret = e_snprintf(buf, len, "%s%s", nbase, ret_event ? "__return" : "");
2701 	if (ret < 0) {
2702 		pr_debug("snprintf() failed: %d\n", ret);
2703 		goto out;
2704 	}
2705 	if (!strlist__has_entry(namelist, buf))
2706 		goto out;
2707 
2708 	if (!allow_suffix) {
2709 		pr_warning("Error: event \"%s\" already exists.\n"
2710 			   " Hint: Remove existing event by 'perf probe -d'\n"
2711 			   "       or force duplicates by 'perf probe -f'\n"
2712 			   "       or set 'force=yes' in BPF source.\n",
2713 			   buf);
2714 		ret = -EEXIST;
2715 		goto out;
2716 	}
2717 
2718 	/* Try to add suffix */
2719 	for (i = 1; i < MAX_EVENT_INDEX; i++) {
2720 		ret = e_snprintf(buf, len, "%s_%d", nbase, i);
2721 		if (ret < 0) {
2722 			pr_debug("snprintf() failed: %d\n", ret);
2723 			goto out;
2724 		}
2725 		if (!strlist__has_entry(namelist, buf))
2726 			break;
2727 	}
2728 	if (i == MAX_EVENT_INDEX) {
2729 		pr_warning("Too many events are on the same function.\n");
2730 		ret = -ERANGE;
2731 	}
2732 
2733 out:
2734 	free(nbase);
2735 
2736 	/* Final validation */
2737 	if (ret >= 0 && !is_c_func_name(buf)) {
2738 		pr_warning("Internal error: \"%s\" is an invalid event name.\n",
2739 			   buf);
2740 		ret = -EINVAL;
2741 	}
2742 
2743 	return ret;
2744 }
2745 
2746 /* Warn if the current kernel's uprobe implementation is old */
2747 static void warn_uprobe_event_compat(struct probe_trace_event *tev)
2748 {
2749 	int i;
2750 	char *buf = synthesize_probe_trace_command(tev);
2751 	struct probe_trace_point *tp = &tev->point;
2752 
2753 	if (tp->ref_ctr_offset && !uprobe_ref_ctr_is_supported()) {
2754 		pr_warning("A semaphore is associated with %s:%s and "
2755 			   "seems your kernel doesn't support it.\n",
2756 			   tev->group, tev->event);
2757 	}
2758 
2759 	/* Old uprobe event doesn't support memory dereference */
2760 	if (!tev->uprobes || tev->nargs == 0 || !buf)
2761 		goto out;
2762 
2763 	for (i = 0; i < tev->nargs; i++)
2764 		if (strglobmatch(tev->args[i].value, "[$@+-]*")) {
2765 			pr_warning("Please upgrade your kernel to at least "
2766 				   "3.14 to have access to feature %s\n",
2767 				   tev->args[i].value);
2768 			break;
2769 		}
2770 out:
2771 	free(buf);
2772 }
2773 
2774 /* Set new name from original perf_probe_event and namelist */
2775 static int probe_trace_event__set_name(struct probe_trace_event *tev,
2776 				       struct perf_probe_event *pev,
2777 				       struct strlist *namelist,
2778 				       bool allow_suffix)
2779 {
2780 	const char *event, *group;
2781 	char buf[64];
2782 	int ret;
2783 
2784 	/* If probe_event or trace_event already have the name, reuse it */
2785 	if (pev->event && !pev->sdt)
2786 		event = pev->event;
2787 	else if (tev->event)
2788 		event = tev->event;
2789 	else {
2790 		/* Or generate new one from probe point */
2791 		if (pev->point.function &&
2792 			(strncmp(pev->point.function, "0x", 2) != 0) &&
2793 			!strisglob(pev->point.function))
2794 			event = pev->point.function;
2795 		else
2796 			event = tev->point.realname;
2797 	}
2798 	if (pev->group && !pev->sdt)
2799 		group = pev->group;
2800 	else if (tev->group)
2801 		group = tev->group;
2802 	else
2803 		group = PERFPROBE_GROUP;
2804 
2805 	/* Get an unused new event name */
2806 	ret = get_new_event_name(buf, 64, event, namelist,
2807 				 tev->point.retprobe, allow_suffix);
2808 	if (ret < 0)
2809 		return ret;
2810 
2811 	event = buf;
2812 
2813 	tev->event = strdup(event);
2814 	tev->group = strdup(group);
2815 	if (tev->event == NULL || tev->group == NULL)
2816 		return -ENOMEM;
2817 
2818 	/*
2819 	 * Add new event name to namelist if multiprobe event is NOT
2820 	 * supported, since we have to use new event name for following
2821 	 * probes in that case.
2822 	 */
2823 	if (!multiprobe_event_is_supported())
2824 		strlist__add(namelist, event);
2825 	return 0;
2826 }
2827 
2828 static int __open_probe_file_and_namelist(bool uprobe,
2829 					  struct strlist **namelist)
2830 {
2831 	int fd;
2832 
2833 	fd = probe_file__open(PF_FL_RW | (uprobe ? PF_FL_UPROBE : 0));
2834 	if (fd < 0)
2835 		return fd;
2836 
2837 	/* Get current event names */
2838 	*namelist = probe_file__get_namelist(fd);
2839 	if (!(*namelist)) {
2840 		pr_debug("Failed to get current event list.\n");
2841 		close(fd);
2842 		return -ENOMEM;
2843 	}
2844 	return fd;
2845 }
2846 
2847 static int __add_probe_trace_events(struct perf_probe_event *pev,
2848 				     struct probe_trace_event *tevs,
2849 				     int ntevs, bool allow_suffix)
2850 {
2851 	int i, fd[2] = {-1, -1}, up, ret;
2852 	struct probe_trace_event *tev = NULL;
2853 	struct probe_cache *cache = NULL;
2854 	struct strlist *namelist[2] = {NULL, NULL};
2855 	struct nscookie nsc;
2856 
2857 	up = pev->uprobes ? 1 : 0;
2858 	fd[up] = __open_probe_file_and_namelist(up, &namelist[up]);
2859 	if (fd[up] < 0)
2860 		return fd[up];
2861 
2862 	ret = 0;
2863 	for (i = 0; i < ntevs; i++) {
2864 		tev = &tevs[i];
2865 		up = tev->uprobes ? 1 : 0;
2866 		if (fd[up] == -1) {	/* Open the kprobe/uprobe_events */
2867 			fd[up] = __open_probe_file_and_namelist(up,
2868 								&namelist[up]);
2869 			if (fd[up] < 0)
2870 				goto close_out;
2871 		}
2872 		/* Skip if the symbol is out of .text or blacklisted */
2873 		if (!tev->point.symbol && !pev->uprobes)
2874 			continue;
2875 
2876 		/* Set new name for tev (and update namelist) */
2877 		ret = probe_trace_event__set_name(tev, pev, namelist[up],
2878 						  allow_suffix);
2879 		if (ret < 0)
2880 			break;
2881 
2882 		nsinfo__mountns_enter(pev->nsi, &nsc);
2883 		ret = probe_file__add_event(fd[up], tev);
2884 		nsinfo__mountns_exit(&nsc);
2885 		if (ret < 0)
2886 			break;
2887 
2888 		/*
2889 		 * Probes after the first probe which comes from same
2890 		 * user input are always allowed to add suffix, because
2891 		 * there might be several addresses corresponding to
2892 		 * one code line.
2893 		 */
2894 		allow_suffix = true;
2895 	}
2896 	if (ret == -EINVAL && pev->uprobes)
2897 		warn_uprobe_event_compat(tev);
2898 	if (ret == 0 && probe_conf.cache) {
2899 		cache = probe_cache__new(pev->target, pev->nsi);
2900 		if (!cache ||
2901 		    probe_cache__add_entry(cache, pev, tevs, ntevs) < 0 ||
2902 		    probe_cache__commit(cache) < 0)
2903 			pr_warning("Failed to add event to probe cache\n");
2904 		probe_cache__delete(cache);
2905 	}
2906 
2907 close_out:
2908 	for (up = 0; up < 2; up++) {
2909 		strlist__delete(namelist[up]);
2910 		if (fd[up] >= 0)
2911 			close(fd[up]);
2912 	}
2913 	return ret;
2914 }
2915 
2916 static int find_probe_functions(struct map *map, char *name,
2917 				struct symbol **syms)
2918 {
2919 	int found = 0;
2920 	struct symbol *sym;
2921 	struct rb_node *tmp;
2922 	const char *norm, *ver;
2923 	char *buf = NULL;
2924 	bool cut_version = true;
2925 
2926 	if (map__load(map) < 0)
2927 		return 0;
2928 
2929 	/* If user gives a version, don't cut off the version from symbols */
2930 	if (strchr(name, '@'))
2931 		cut_version = false;
2932 
2933 	map__for_each_symbol(map, sym, tmp) {
2934 		norm = arch__normalize_symbol_name(sym->name);
2935 		if (!norm)
2936 			continue;
2937 
2938 		if (cut_version) {
2939 			/* We don't care about default symbol or not */
2940 			ver = strchr(norm, '@');
2941 			if (ver) {
2942 				buf = strndup(norm, ver - norm);
2943 				if (!buf)
2944 					return -ENOMEM;
2945 				norm = buf;
2946 			}
2947 		}
2948 
2949 		if (strglobmatch(norm, name)) {
2950 			found++;
2951 			if (syms && found < probe_conf.max_probes)
2952 				syms[found - 1] = sym;
2953 		}
2954 		if (buf)
2955 			zfree(&buf);
2956 	}
2957 
2958 	return found;
2959 }
2960 
2961 void __weak arch__fix_tev_from_maps(struct perf_probe_event *pev __maybe_unused,
2962 				struct probe_trace_event *tev __maybe_unused,
2963 				struct map *map __maybe_unused,
2964 				struct symbol *sym __maybe_unused) { }
2965 
2966 /*
2967  * Find probe function addresses from map.
2968  * Return an error or the number of found probe_trace_event
2969  */
2970 static int find_probe_trace_events_from_map(struct perf_probe_event *pev,
2971 					    struct probe_trace_event **tevs)
2972 {
2973 	struct map *map = NULL;
2974 	struct ref_reloc_sym *reloc_sym = NULL;
2975 	struct symbol *sym;
2976 	struct symbol **syms = NULL;
2977 	struct probe_trace_event *tev;
2978 	struct perf_probe_point *pp = &pev->point;
2979 	struct probe_trace_point *tp;
2980 	int num_matched_functions;
2981 	int ret, i, j, skipped = 0;
2982 	char *mod_name;
2983 
2984 	map = get_target_map(pev->target, pev->nsi, pev->uprobes);
2985 	if (!map) {
2986 		ret = -EINVAL;
2987 		goto out;
2988 	}
2989 
2990 	syms = malloc(sizeof(struct symbol *) * probe_conf.max_probes);
2991 	if (!syms) {
2992 		ret = -ENOMEM;
2993 		goto out;
2994 	}
2995 
2996 	/*
2997 	 * Load matched symbols: Since the different local symbols may have
2998 	 * same name but different addresses, this lists all the symbols.
2999 	 */
3000 	num_matched_functions = find_probe_functions(map, pp->function, syms);
3001 	if (num_matched_functions <= 0) {
3002 		pr_err("Failed to find symbol %s in %s\n", pp->function,
3003 			pev->target ? : "kernel");
3004 		ret = -ENOENT;
3005 		goto out;
3006 	} else if (num_matched_functions > probe_conf.max_probes) {
3007 		pr_err("Too many functions matched in %s\n",
3008 			pev->target ? : "kernel");
3009 		ret = -E2BIG;
3010 		goto out;
3011 	}
3012 
3013 	/* Note that the symbols in the kmodule are not relocated */
3014 	if (!pev->uprobes && !pev->target &&
3015 			(!pp->retprobe || kretprobe_offset_is_supported())) {
3016 		reloc_sym = kernel_get_ref_reloc_sym(NULL);
3017 		if (!reloc_sym) {
3018 			pr_warning("Relocated base symbol is not found!\n");
3019 			ret = -EINVAL;
3020 			goto out;
3021 		}
3022 	}
3023 
3024 	/* Setup result trace-probe-events */
3025 	*tevs = zalloc(sizeof(*tev) * num_matched_functions);
3026 	if (!*tevs) {
3027 		ret = -ENOMEM;
3028 		goto out;
3029 	}
3030 
3031 	ret = 0;
3032 
3033 	for (j = 0; j < num_matched_functions; j++) {
3034 		sym = syms[j];
3035 
3036 		/* There can be duplicated symbols in the map */
3037 		for (i = 0; i < j; i++)
3038 			if (sym->start == syms[i]->start) {
3039 				pr_debug("Found duplicated symbol %s @ %" PRIx64 "\n",
3040 					 sym->name, sym->start);
3041 				break;
3042 			}
3043 		if (i != j)
3044 			continue;
3045 
3046 		tev = (*tevs) + ret;
3047 		tp = &tev->point;
3048 		if (ret == num_matched_functions) {
3049 			pr_warning("Too many symbols are listed. Skip it.\n");
3050 			break;
3051 		}
3052 		ret++;
3053 
3054 		if (pp->offset > sym->end - sym->start) {
3055 			pr_warning("Offset %ld is bigger than the size of %s\n",
3056 				   pp->offset, sym->name);
3057 			ret = -ENOENT;
3058 			goto err_out;
3059 		}
3060 		/* Add one probe point */
3061 		tp->address = map->unmap_ip(map, sym->start) + pp->offset;
3062 
3063 		/* Check the kprobe (not in module) is within .text  */
3064 		if (!pev->uprobes && !pev->target &&
3065 		    kprobe_warn_out_range(sym->name, tp->address)) {
3066 			tp->symbol = NULL;	/* Skip it */
3067 			skipped++;
3068 		} else if (reloc_sym) {
3069 			tp->symbol = strdup_or_goto(reloc_sym->name, nomem_out);
3070 			tp->offset = tp->address - reloc_sym->addr;
3071 		} else {
3072 			tp->symbol = strdup_or_goto(sym->name, nomem_out);
3073 			tp->offset = pp->offset;
3074 		}
3075 		tp->realname = strdup_or_goto(sym->name, nomem_out);
3076 
3077 		tp->retprobe = pp->retprobe;
3078 		if (pev->target) {
3079 			if (pev->uprobes) {
3080 				tev->point.module = strdup_or_goto(pev->target,
3081 								   nomem_out);
3082 			} else {
3083 				mod_name = find_module_name(pev->target);
3084 				tev->point.module =
3085 					strdup(mod_name ? mod_name : pev->target);
3086 				free(mod_name);
3087 				if (!tev->point.module)
3088 					goto nomem_out;
3089 			}
3090 		}
3091 		tev->uprobes = pev->uprobes;
3092 		tev->nargs = pev->nargs;
3093 		if (tev->nargs) {
3094 			tev->args = zalloc(sizeof(struct probe_trace_arg) *
3095 					   tev->nargs);
3096 			if (tev->args == NULL)
3097 				goto nomem_out;
3098 		}
3099 		for (i = 0; i < tev->nargs; i++) {
3100 			if (pev->args[i].name)
3101 				tev->args[i].name =
3102 					strdup_or_goto(pev->args[i].name,
3103 							nomem_out);
3104 
3105 			tev->args[i].value = strdup_or_goto(pev->args[i].var,
3106 							    nomem_out);
3107 			if (pev->args[i].type)
3108 				tev->args[i].type =
3109 					strdup_or_goto(pev->args[i].type,
3110 							nomem_out);
3111 		}
3112 		arch__fix_tev_from_maps(pev, tev, map, sym);
3113 	}
3114 	if (ret == skipped) {
3115 		ret = -ENOENT;
3116 		goto err_out;
3117 	}
3118 
3119 out:
3120 	map__put(map);
3121 	free(syms);
3122 	return ret;
3123 
3124 nomem_out:
3125 	ret = -ENOMEM;
3126 err_out:
3127 	clear_probe_trace_events(*tevs, num_matched_functions);
3128 	zfree(tevs);
3129 	goto out;
3130 }
3131 
3132 static int try_to_find_absolute_address(struct perf_probe_event *pev,
3133 					struct probe_trace_event **tevs)
3134 {
3135 	struct perf_probe_point *pp = &pev->point;
3136 	struct probe_trace_event *tev;
3137 	struct probe_trace_point *tp;
3138 	int i, err;
3139 
3140 	if (!(pev->point.function && !strncmp(pev->point.function, "0x", 2)))
3141 		return -EINVAL;
3142 	if (perf_probe_event_need_dwarf(pev))
3143 		return -EINVAL;
3144 
3145 	/*
3146 	 * This is 'perf probe /lib/libc.so 0xabcd'. Try to probe at
3147 	 * absolute address.
3148 	 *
3149 	 * Only one tev can be generated by this.
3150 	 */
3151 	*tevs = zalloc(sizeof(*tev));
3152 	if (!*tevs)
3153 		return -ENOMEM;
3154 
3155 	tev = *tevs;
3156 	tp = &tev->point;
3157 
3158 	/*
3159 	 * Don't use tp->offset, use address directly, because
3160 	 * in synthesize_probe_trace_command() address cannot be
3161 	 * zero.
3162 	 */
3163 	tp->address = pev->point.abs_address;
3164 	tp->retprobe = pp->retprobe;
3165 	tev->uprobes = pev->uprobes;
3166 
3167 	err = -ENOMEM;
3168 	/*
3169 	 * Give it a '0x' leading symbol name.
3170 	 * In __add_probe_trace_events, a NULL symbol is interpreted as
3171 	 * invalid.
3172 	 */
3173 	if (asprintf(&tp->symbol, "0x%lx", tp->address) < 0)
3174 		goto errout;
3175 
3176 	/* For kprobe, check range */
3177 	if ((!tev->uprobes) &&
3178 	    (kprobe_warn_out_range(tev->point.symbol,
3179 				   tev->point.address))) {
3180 		err = -EACCES;
3181 		goto errout;
3182 	}
3183 
3184 	if (asprintf(&tp->realname, "abs_%lx", tp->address) < 0)
3185 		goto errout;
3186 
3187 	if (pev->target) {
3188 		tp->module = strdup(pev->target);
3189 		if (!tp->module)
3190 			goto errout;
3191 	}
3192 
3193 	if (tev->group) {
3194 		tev->group = strdup(pev->group);
3195 		if (!tev->group)
3196 			goto errout;
3197 	}
3198 
3199 	if (pev->event) {
3200 		tev->event = strdup(pev->event);
3201 		if (!tev->event)
3202 			goto errout;
3203 	}
3204 
3205 	tev->nargs = pev->nargs;
3206 	tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
3207 	if (!tev->args)
3208 		goto errout;
3209 
3210 	for (i = 0; i < tev->nargs; i++)
3211 		copy_to_probe_trace_arg(&tev->args[i], &pev->args[i]);
3212 
3213 	return 1;
3214 
3215 errout:
3216 	clear_probe_trace_events(*tevs, 1);
3217 	*tevs = NULL;
3218 	return err;
3219 }
3220 
3221 /* Concatinate two arrays */
3222 static void *memcat(void *a, size_t sz_a, void *b, size_t sz_b)
3223 {
3224 	void *ret;
3225 
3226 	ret = malloc(sz_a + sz_b);
3227 	if (ret) {
3228 		memcpy(ret, a, sz_a);
3229 		memcpy(ret + sz_a, b, sz_b);
3230 	}
3231 	return ret;
3232 }
3233 
3234 static int
3235 concat_probe_trace_events(struct probe_trace_event **tevs, int *ntevs,
3236 			  struct probe_trace_event **tevs2, int ntevs2)
3237 {
3238 	struct probe_trace_event *new_tevs;
3239 	int ret = 0;
3240 
3241 	if (*ntevs == 0) {
3242 		*tevs = *tevs2;
3243 		*ntevs = ntevs2;
3244 		*tevs2 = NULL;
3245 		return 0;
3246 	}
3247 
3248 	if (*ntevs + ntevs2 > probe_conf.max_probes)
3249 		ret = -E2BIG;
3250 	else {
3251 		/* Concatinate the array of probe_trace_event */
3252 		new_tevs = memcat(*tevs, (*ntevs) * sizeof(**tevs),
3253 				  *tevs2, ntevs2 * sizeof(**tevs2));
3254 		if (!new_tevs)
3255 			ret = -ENOMEM;
3256 		else {
3257 			free(*tevs);
3258 			*tevs = new_tevs;
3259 			*ntevs += ntevs2;
3260 		}
3261 	}
3262 	if (ret < 0)
3263 		clear_probe_trace_events(*tevs2, ntevs2);
3264 	zfree(tevs2);
3265 
3266 	return ret;
3267 }
3268 
3269 /*
3270  * Try to find probe_trace_event from given probe caches. Return the number
3271  * of cached events found, if an error occurs return the error.
3272  */
3273 static int find_cached_events(struct perf_probe_event *pev,
3274 			      struct probe_trace_event **tevs,
3275 			      const char *target)
3276 {
3277 	struct probe_cache *cache;
3278 	struct probe_cache_entry *entry;
3279 	struct probe_trace_event *tmp_tevs = NULL;
3280 	int ntevs = 0;
3281 	int ret = 0;
3282 
3283 	cache = probe_cache__new(target, pev->nsi);
3284 	/* Return 0 ("not found") if the target has no probe cache. */
3285 	if (!cache)
3286 		return 0;
3287 
3288 	for_each_probe_cache_entry(entry, cache) {
3289 		/* Skip the cache entry which has no name */
3290 		if (!entry->pev.event || !entry->pev.group)
3291 			continue;
3292 		if ((!pev->group || strglobmatch(entry->pev.group, pev->group)) &&
3293 		    strglobmatch(entry->pev.event, pev->event)) {
3294 			ret = probe_cache_entry__get_event(entry, &tmp_tevs);
3295 			if (ret > 0)
3296 				ret = concat_probe_trace_events(tevs, &ntevs,
3297 								&tmp_tevs, ret);
3298 			if (ret < 0)
3299 				break;
3300 		}
3301 	}
3302 	probe_cache__delete(cache);
3303 	if (ret < 0) {
3304 		clear_probe_trace_events(*tevs, ntevs);
3305 		zfree(tevs);
3306 	} else {
3307 		ret = ntevs;
3308 		if (ntevs > 0 && target && target[0] == '/')
3309 			pev->uprobes = true;
3310 	}
3311 
3312 	return ret;
3313 }
3314 
3315 /* Try to find probe_trace_event from all probe caches */
3316 static int find_cached_events_all(struct perf_probe_event *pev,
3317 				   struct probe_trace_event **tevs)
3318 {
3319 	struct probe_trace_event *tmp_tevs = NULL;
3320 	struct strlist *bidlist;
3321 	struct str_node *nd;
3322 	char *pathname;
3323 	int ntevs = 0;
3324 	int ret;
3325 
3326 	/* Get the buildid list of all valid caches */
3327 	bidlist = build_id_cache__list_all(true);
3328 	if (!bidlist) {
3329 		ret = -errno;
3330 		pr_debug("Failed to get buildids: %d\n", ret);
3331 		return ret;
3332 	}
3333 
3334 	ret = 0;
3335 	strlist__for_each_entry(nd, bidlist) {
3336 		pathname = build_id_cache__origname(nd->s);
3337 		ret = find_cached_events(pev, &tmp_tevs, pathname);
3338 		/* In the case of cnt == 0, we just skip it */
3339 		if (ret > 0)
3340 			ret = concat_probe_trace_events(tevs, &ntevs,
3341 							&tmp_tevs, ret);
3342 		free(pathname);
3343 		if (ret < 0)
3344 			break;
3345 	}
3346 	strlist__delete(bidlist);
3347 
3348 	if (ret < 0) {
3349 		clear_probe_trace_events(*tevs, ntevs);
3350 		zfree(tevs);
3351 	} else
3352 		ret = ntevs;
3353 
3354 	return ret;
3355 }
3356 
3357 static int find_probe_trace_events_from_cache(struct perf_probe_event *pev,
3358 					      struct probe_trace_event **tevs)
3359 {
3360 	struct probe_cache *cache;
3361 	struct probe_cache_entry *entry;
3362 	struct probe_trace_event *tev;
3363 	struct str_node *node;
3364 	int ret, i;
3365 
3366 	if (pev->sdt) {
3367 		/* For SDT/cached events, we use special search functions */
3368 		if (!pev->target)
3369 			return find_cached_events_all(pev, tevs);
3370 		else
3371 			return find_cached_events(pev, tevs, pev->target);
3372 	}
3373 	cache = probe_cache__new(pev->target, pev->nsi);
3374 	if (!cache)
3375 		return 0;
3376 
3377 	entry = probe_cache__find(cache, pev);
3378 	if (!entry) {
3379 		/* SDT must be in the cache */
3380 		ret = pev->sdt ? -ENOENT : 0;
3381 		goto out;
3382 	}
3383 
3384 	ret = strlist__nr_entries(entry->tevlist);
3385 	if (ret > probe_conf.max_probes) {
3386 		pr_debug("Too many entries matched in the cache of %s\n",
3387 			 pev->target ? : "kernel");
3388 		ret = -E2BIG;
3389 		goto out;
3390 	}
3391 
3392 	*tevs = zalloc(ret * sizeof(*tev));
3393 	if (!*tevs) {
3394 		ret = -ENOMEM;
3395 		goto out;
3396 	}
3397 
3398 	i = 0;
3399 	strlist__for_each_entry(node, entry->tevlist) {
3400 		tev = &(*tevs)[i++];
3401 		ret = parse_probe_trace_command(node->s, tev);
3402 		if (ret < 0)
3403 			goto out;
3404 		/* Set the uprobes attribute as same as original */
3405 		tev->uprobes = pev->uprobes;
3406 	}
3407 	ret = i;
3408 
3409 out:
3410 	probe_cache__delete(cache);
3411 	return ret;
3412 }
3413 
3414 static int convert_to_probe_trace_events(struct perf_probe_event *pev,
3415 					 struct probe_trace_event **tevs)
3416 {
3417 	int ret;
3418 
3419 	if (!pev->group && !pev->sdt) {
3420 		/* Set group name if not given */
3421 		if (!pev->uprobes) {
3422 			pev->group = strdup(PERFPROBE_GROUP);
3423 			ret = pev->group ? 0 : -ENOMEM;
3424 		} else
3425 			ret = convert_exec_to_group(pev->target, &pev->group);
3426 		if (ret != 0) {
3427 			pr_warning("Failed to make a group name.\n");
3428 			return ret;
3429 		}
3430 	}
3431 
3432 	ret = try_to_find_absolute_address(pev, tevs);
3433 	if (ret > 0)
3434 		return ret;
3435 
3436 	/* At first, we need to lookup cache entry */
3437 	ret = find_probe_trace_events_from_cache(pev, tevs);
3438 	if (ret > 0 || pev->sdt)	/* SDT can be found only in the cache */
3439 		return ret == 0 ? -ENOENT : ret; /* Found in probe cache */
3440 
3441 	/* Convert perf_probe_event with debuginfo */
3442 	ret = try_to_find_probe_trace_events(pev, tevs);
3443 	if (ret != 0)
3444 		return ret;	/* Found in debuginfo or got an error */
3445 
3446 	return find_probe_trace_events_from_map(pev, tevs);
3447 }
3448 
3449 int convert_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3450 {
3451 	int i, ret;
3452 
3453 	/* Loop 1: convert all events */
3454 	for (i = 0; i < npevs; i++) {
3455 		/* Init kprobe blacklist if needed */
3456 		if (!pevs[i].uprobes)
3457 			kprobe_blacklist__init();
3458 		/* Convert with or without debuginfo */
3459 		ret  = convert_to_probe_trace_events(&pevs[i], &pevs[i].tevs);
3460 		if (ret < 0)
3461 			return ret;
3462 		pevs[i].ntevs = ret;
3463 	}
3464 	/* This just release blacklist only if allocated */
3465 	kprobe_blacklist__release();
3466 
3467 	return 0;
3468 }
3469 
3470 static int show_probe_trace_event(struct probe_trace_event *tev)
3471 {
3472 	char *buf = synthesize_probe_trace_command(tev);
3473 
3474 	if (!buf) {
3475 		pr_debug("Failed to synthesize probe trace event.\n");
3476 		return -EINVAL;
3477 	}
3478 
3479 	/* Showing definition always go stdout */
3480 	printf("%s\n", buf);
3481 	free(buf);
3482 
3483 	return 0;
3484 }
3485 
3486 int show_probe_trace_events(struct perf_probe_event *pevs, int npevs)
3487 {
3488 	struct strlist *namelist = strlist__new(NULL, NULL);
3489 	struct probe_trace_event *tev;
3490 	struct perf_probe_event *pev;
3491 	int i, j, ret = 0;
3492 
3493 	if (!namelist)
3494 		return -ENOMEM;
3495 
3496 	for (j = 0; j < npevs && !ret; j++) {
3497 		pev = &pevs[j];
3498 		for (i = 0; i < pev->ntevs && !ret; i++) {
3499 			tev = &pev->tevs[i];
3500 			/* Skip if the symbol is out of .text or blacklisted */
3501 			if (!tev->point.symbol && !pev->uprobes)
3502 				continue;
3503 
3504 			/* Set new name for tev (and update namelist) */
3505 			ret = probe_trace_event__set_name(tev, pev,
3506 							  namelist, true);
3507 			if (!ret)
3508 				ret = show_probe_trace_event(tev);
3509 		}
3510 	}
3511 	strlist__delete(namelist);
3512 
3513 	return ret;
3514 }
3515 
3516 int apply_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3517 {
3518 	int i, ret = 0;
3519 
3520 	/* Loop 2: add all events */
3521 	for (i = 0; i < npevs; i++) {
3522 		ret = __add_probe_trace_events(&pevs[i], pevs[i].tevs,
3523 					       pevs[i].ntevs,
3524 					       probe_conf.force_add);
3525 		if (ret < 0)
3526 			break;
3527 	}
3528 	return ret;
3529 }
3530 
3531 void cleanup_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3532 {
3533 	int i, j;
3534 	struct perf_probe_event *pev;
3535 
3536 	/* Loop 3: cleanup and free trace events  */
3537 	for (i = 0; i < npevs; i++) {
3538 		pev = &pevs[i];
3539 		for (j = 0; j < pevs[i].ntevs; j++)
3540 			clear_probe_trace_event(&pevs[i].tevs[j]);
3541 		zfree(&pevs[i].tevs);
3542 		pevs[i].ntevs = 0;
3543 		nsinfo__zput(pev->nsi);
3544 		clear_perf_probe_event(&pevs[i]);
3545 	}
3546 }
3547 
3548 int add_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3549 {
3550 	int ret;
3551 
3552 	ret = init_probe_symbol_maps(pevs->uprobes);
3553 	if (ret < 0)
3554 		return ret;
3555 
3556 	ret = convert_perf_probe_events(pevs, npevs);
3557 	if (ret == 0)
3558 		ret = apply_perf_probe_events(pevs, npevs);
3559 
3560 	cleanup_perf_probe_events(pevs, npevs);
3561 
3562 	exit_probe_symbol_maps();
3563 	return ret;
3564 }
3565 
3566 int del_perf_probe_events(struct strfilter *filter)
3567 {
3568 	int ret, ret2, ufd = -1, kfd = -1;
3569 	char *str = strfilter__string(filter);
3570 
3571 	if (!str)
3572 		return -EINVAL;
3573 
3574 	/* Get current event names */
3575 	ret = probe_file__open_both(&kfd, &ufd, PF_FL_RW);
3576 	if (ret < 0)
3577 		goto out;
3578 
3579 	ret = probe_file__del_events(kfd, filter);
3580 	if (ret < 0 && ret != -ENOENT)
3581 		goto error;
3582 
3583 	ret2 = probe_file__del_events(ufd, filter);
3584 	if (ret2 < 0 && ret2 != -ENOENT) {
3585 		ret = ret2;
3586 		goto error;
3587 	}
3588 	ret = 0;
3589 
3590 error:
3591 	if (kfd >= 0)
3592 		close(kfd);
3593 	if (ufd >= 0)
3594 		close(ufd);
3595 out:
3596 	free(str);
3597 
3598 	return ret;
3599 }
3600 
3601 int show_available_funcs(const char *target, struct nsinfo *nsi,
3602 			 struct strfilter *_filter, bool user)
3603 {
3604         struct rb_node *nd;
3605 	struct map *map;
3606 	int ret;
3607 
3608 	ret = init_probe_symbol_maps(user);
3609 	if (ret < 0)
3610 		return ret;
3611 
3612 	/* Get a symbol map */
3613 	map = get_target_map(target, nsi, user);
3614 	if (!map) {
3615 		pr_err("Failed to get a map for %s\n", (target) ? : "kernel");
3616 		return -EINVAL;
3617 	}
3618 
3619 	ret = map__load(map);
3620 	if (ret) {
3621 		if (ret == -2) {
3622 			char *str = strfilter__string(_filter);
3623 			pr_err("Failed to find symbols matched to \"%s\"\n",
3624 			       str);
3625 			free(str);
3626 		} else
3627 			pr_err("Failed to load symbols in %s\n",
3628 			       (target) ? : "kernel");
3629 		goto end;
3630 	}
3631 	if (!dso__sorted_by_name(map->dso))
3632 		dso__sort_by_name(map->dso);
3633 
3634 	/* Show all (filtered) symbols */
3635 	setup_pager();
3636 
3637 	for (nd = rb_first_cached(&map->dso->symbol_names); nd;
3638 	     nd = rb_next(nd)) {
3639 		struct symbol_name_rb_node *pos = rb_entry(nd, struct symbol_name_rb_node, rb_node);
3640 
3641 		if (strfilter__compare(_filter, pos->sym.name))
3642 			printf("%s\n", pos->sym.name);
3643 	}
3644 end:
3645 	map__put(map);
3646 	exit_probe_symbol_maps();
3647 
3648 	return ret;
3649 }
3650 
3651 int copy_to_probe_trace_arg(struct probe_trace_arg *tvar,
3652 			    struct perf_probe_arg *pvar)
3653 {
3654 	tvar->value = strdup(pvar->var);
3655 	if (tvar->value == NULL)
3656 		return -ENOMEM;
3657 	if (pvar->type) {
3658 		tvar->type = strdup(pvar->type);
3659 		if (tvar->type == NULL)
3660 			return -ENOMEM;
3661 	}
3662 	if (pvar->name) {
3663 		tvar->name = strdup(pvar->name);
3664 		if (tvar->name == NULL)
3665 			return -ENOMEM;
3666 	} else
3667 		tvar->name = NULL;
3668 	return 0;
3669 }
3670