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