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