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