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