Merge tag 'block-5.11-2021-01-10' of git://git.kernel.dk/linux-block
[linux/fpc-iii.git] / tools / perf / util / probe-event.c
blob8eae2afff71a90103f71056c7bc2e8a85b7c2d3e
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * probe-event.c : perf-probe definition to probe_events format converter
5 * Written by Masami Hiramatsu <mhiramat@redhat.com>
6 */
8 #include <inttypes.h>
9 #include <sys/utsname.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #include <fcntl.h>
13 #include <errno.h>
14 #include <stdio.h>
15 #include <unistd.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <stdarg.h>
19 #include <limits.h>
20 #include <elf.h>
22 #include "build-id.h"
23 #include "event.h"
24 #include "namespaces.h"
25 #include "strlist.h"
26 #include "strfilter.h"
27 #include "debug.h"
28 #include "dso.h"
29 #include "color.h"
30 #include "map.h"
31 #include "maps.h"
32 #include "symbol.h"
33 #include <api/fs/fs.h>
34 #include "trace-event.h" /* For __maybe_unused */
35 #include "probe-event.h"
36 #include "probe-finder.h"
37 #include "probe-file.h"
38 #include "session.h"
39 #include "string2.h"
40 #include "strbuf.h"
42 #include <subcmd/pager.h>
43 #include <linux/ctype.h>
44 #include <linux/zalloc.h>
46 #ifdef HAVE_DEBUGINFOD_SUPPORT
47 #include <elfutils/debuginfod.h>
48 #endif
50 #define PERFPROBE_GROUP "probe"
52 bool probe_event_dry_run; /* Dry run flag */
53 struct probe_conf probe_conf = { .magic_num = DEFAULT_PROBE_MAGIC_NUM };
55 #define semantic_error(msg ...) pr_err("Semantic error :" msg)
57 int e_snprintf(char *str, size_t size, const char *format, ...)
59 int ret;
60 va_list ap;
61 va_start(ap, format);
62 ret = vsnprintf(str, size, format, ap);
63 va_end(ap);
64 if (ret >= (int)size)
65 ret = -E2BIG;
66 return ret;
69 static struct machine *host_machine;
71 /* Initialize symbol maps and path of vmlinux/modules */
72 int init_probe_symbol_maps(bool user_only)
74 int ret;
76 symbol_conf.sort_by_name = true;
77 symbol_conf.allow_aliases = true;
78 ret = symbol__init(NULL);
79 if (ret < 0) {
80 pr_debug("Failed to init symbol map.\n");
81 goto out;
84 if (host_machine || user_only) /* already initialized */
85 return 0;
87 if (symbol_conf.vmlinux_name)
88 pr_debug("Use vmlinux: %s\n", symbol_conf.vmlinux_name);
90 host_machine = machine__new_host();
91 if (!host_machine) {
92 pr_debug("machine__new_host() failed.\n");
93 symbol__exit();
94 ret = -1;
96 out:
97 if (ret < 0)
98 pr_warning("Failed to init vmlinux path.\n");
99 return ret;
102 void exit_probe_symbol_maps(void)
104 machine__delete(host_machine);
105 host_machine = NULL;
106 symbol__exit();
109 static struct ref_reloc_sym *kernel_get_ref_reloc_sym(struct map **pmap)
111 /* kmap->ref_reloc_sym should be set if host_machine is initialized */
112 struct kmap *kmap;
113 struct map *map = machine__kernel_map(host_machine);
115 if (map__load(map) < 0)
116 return NULL;
118 kmap = map__kmap(map);
119 if (!kmap)
120 return NULL;
122 if (pmap)
123 *pmap = map;
125 return kmap->ref_reloc_sym;
128 static int kernel_get_symbol_address_by_name(const char *name, u64 *addr,
129 bool reloc, bool reladdr)
131 struct ref_reloc_sym *reloc_sym;
132 struct symbol *sym;
133 struct map *map;
135 /* ref_reloc_sym is just a label. Need a special fix*/
136 reloc_sym = kernel_get_ref_reloc_sym(&map);
137 if (reloc_sym && strcmp(name, reloc_sym->name) == 0)
138 *addr = (!map->reloc || reloc) ? reloc_sym->addr :
139 reloc_sym->unrelocated_addr;
140 else {
141 sym = machine__find_kernel_symbol_by_name(host_machine, name, &map);
142 if (!sym)
143 return -ENOENT;
144 *addr = map->unmap_ip(map, sym->start) -
145 ((reloc) ? 0 : map->reloc) -
146 ((reladdr) ? map->start : 0);
148 return 0;
151 static struct map *kernel_get_module_map(const char *module)
153 struct maps *maps = machine__kernel_maps(host_machine);
154 struct map *pos;
156 /* A file path -- this is an offline module */
157 if (module && strchr(module, '/'))
158 return dso__new_map(module);
160 if (!module) {
161 pos = machine__kernel_map(host_machine);
162 return map__get(pos);
165 maps__for_each_entry(maps, pos) {
166 /* short_name is "[module]" */
167 if (strncmp(pos->dso->short_name + 1, module,
168 pos->dso->short_name_len - 2) == 0 &&
169 module[pos->dso->short_name_len - 2] == '\0') {
170 return map__get(pos);
173 return NULL;
176 struct map *get_target_map(const char *target, struct nsinfo *nsi, bool user)
178 /* Init maps of given executable or kernel */
179 if (user) {
180 struct map *map;
182 map = dso__new_map(target);
183 if (map && map->dso)
184 map->dso->nsinfo = nsinfo__get(nsi);
185 return map;
186 } else {
187 return kernel_get_module_map(target);
191 static int convert_exec_to_group(const char *exec, char **result)
193 char *ptr1, *ptr2, *exec_copy;
194 char buf[64];
195 int ret;
197 exec_copy = strdup(exec);
198 if (!exec_copy)
199 return -ENOMEM;
201 ptr1 = basename(exec_copy);
202 if (!ptr1) {
203 ret = -EINVAL;
204 goto out;
207 for (ptr2 = ptr1; *ptr2 != '\0'; ptr2++) {
208 if (!isalnum(*ptr2) && *ptr2 != '_') {
209 *ptr2 = '\0';
210 break;
214 ret = e_snprintf(buf, 64, "%s_%s", PERFPROBE_GROUP, ptr1);
215 if (ret < 0)
216 goto out;
218 *result = strdup(buf);
219 ret = *result ? 0 : -ENOMEM;
221 out:
222 free(exec_copy);
223 return ret;
226 static void clear_perf_probe_point(struct perf_probe_point *pp)
228 zfree(&pp->file);
229 zfree(&pp->function);
230 zfree(&pp->lazy_line);
233 static void clear_probe_trace_events(struct probe_trace_event *tevs, int ntevs)
235 int i;
237 for (i = 0; i < ntevs; i++)
238 clear_probe_trace_event(tevs + i);
241 static bool kprobe_blacklist__listed(unsigned long address);
242 static bool kprobe_warn_out_range(const char *symbol, unsigned long address)
244 struct map *map;
245 bool ret = false;
247 map = kernel_get_module_map(NULL);
248 if (map) {
249 ret = address <= map->start || map->end < address;
250 if (ret)
251 pr_warning("%s is out of .text, skip it.\n", symbol);
252 map__put(map);
254 if (!ret && kprobe_blacklist__listed(address)) {
255 pr_warning("%s is blacklisted function, skip it.\n", symbol);
256 ret = true;
259 return ret;
263 * @module can be module name of module file path. In case of path,
264 * inspect elf and find out what is actual module name.
265 * Caller has to free mod_name after using it.
267 static char *find_module_name(const char *module)
269 int fd;
270 Elf *elf;
271 GElf_Ehdr ehdr;
272 GElf_Shdr shdr;
273 Elf_Data *data;
274 Elf_Scn *sec;
275 char *mod_name = NULL;
276 int name_offset;
278 fd = open(module, O_RDONLY);
279 if (fd < 0)
280 return NULL;
282 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
283 if (elf == NULL)
284 goto elf_err;
286 if (gelf_getehdr(elf, &ehdr) == NULL)
287 goto ret_err;
289 sec = elf_section_by_name(elf, &ehdr, &shdr,
290 ".gnu.linkonce.this_module", NULL);
291 if (!sec)
292 goto ret_err;
294 data = elf_getdata(sec, NULL);
295 if (!data || !data->d_buf)
296 goto ret_err;
299 * NOTE:
300 * '.gnu.linkonce.this_module' section of kernel module elf directly
301 * maps to 'struct module' from linux/module.h. This section contains
302 * actual module name which will be used by kernel after loading it.
303 * But, we cannot use 'struct module' here since linux/module.h is not
304 * exposed to user-space. Offset of 'name' has remained same from long
305 * time, so hardcoding it here.
307 if (ehdr.e_ident[EI_CLASS] == ELFCLASS32)
308 name_offset = 12;
309 else /* expect ELFCLASS64 by default */
310 name_offset = 24;
312 mod_name = strdup((char *)data->d_buf + name_offset);
314 ret_err:
315 elf_end(elf);
316 elf_err:
317 close(fd);
318 return mod_name;
321 #ifdef HAVE_DWARF_SUPPORT
323 static int kernel_get_module_dso(const char *module, struct dso **pdso)
325 struct dso *dso;
326 struct map *map;
327 const char *vmlinux_name;
328 int ret = 0;
330 if (module) {
331 char module_name[128];
333 snprintf(module_name, sizeof(module_name), "[%s]", module);
334 map = maps__find_by_name(&host_machine->kmaps, module_name);
335 if (map) {
336 dso = map->dso;
337 goto found;
339 pr_debug("Failed to find module %s.\n", module);
340 return -ENOENT;
343 map = machine__kernel_map(host_machine);
344 dso = map->dso;
345 if (!dso->has_build_id)
346 dso__read_running_kernel_build_id(dso, host_machine);
348 vmlinux_name = symbol_conf.vmlinux_name;
349 dso->load_errno = 0;
350 if (vmlinux_name)
351 ret = dso__load_vmlinux(dso, map, vmlinux_name, false);
352 else
353 ret = dso__load_vmlinux_path(dso, map);
354 found:
355 *pdso = dso;
356 return ret;
360 * Some binaries like glibc have special symbols which are on the symbol
361 * table, but not in the debuginfo. If we can find the address of the
362 * symbol from map, we can translate the address back to the probe point.
364 static int find_alternative_probe_point(struct debuginfo *dinfo,
365 struct perf_probe_point *pp,
366 struct perf_probe_point *result,
367 const char *target, struct nsinfo *nsi,
368 bool uprobes)
370 struct map *map = NULL;
371 struct symbol *sym;
372 u64 address = 0;
373 int ret = -ENOENT;
375 /* This can work only for function-name based one */
376 if (!pp->function || pp->file)
377 return -ENOTSUP;
379 map = get_target_map(target, nsi, uprobes);
380 if (!map)
381 return -EINVAL;
383 /* Find the address of given function */
384 map__for_each_symbol_by_name(map, pp->function, sym) {
385 if (uprobes) {
386 address = sym->start;
387 if (sym->type == STT_GNU_IFUNC)
388 pr_warning("Warning: The probe function (%s) is a GNU indirect function.\n"
389 "Consider identifying the final function used at run time and set the probe directly on that.\n",
390 pp->function);
391 } else
392 address = map->unmap_ip(map, sym->start) - map->reloc;
393 break;
395 if (!address) {
396 ret = -ENOENT;
397 goto out;
399 pr_debug("Symbol %s address found : %" PRIx64 "\n",
400 pp->function, address);
402 ret = debuginfo__find_probe_point(dinfo, (unsigned long)address,
403 result);
404 if (ret <= 0)
405 ret = (!ret) ? -ENOENT : ret;
406 else {
407 result->offset += pp->offset;
408 result->line += pp->line;
409 result->retprobe = pp->retprobe;
410 ret = 0;
413 out:
414 map__put(map);
415 return ret;
419 static int get_alternative_probe_event(struct debuginfo *dinfo,
420 struct perf_probe_event *pev,
421 struct perf_probe_point *tmp)
423 int ret;
425 memcpy(tmp, &pev->point, sizeof(*tmp));
426 memset(&pev->point, 0, sizeof(pev->point));
427 ret = find_alternative_probe_point(dinfo, tmp, &pev->point, pev->target,
428 pev->nsi, pev->uprobes);
429 if (ret < 0)
430 memcpy(&pev->point, tmp, sizeof(*tmp));
432 return ret;
435 static int get_alternative_line_range(struct debuginfo *dinfo,
436 struct line_range *lr,
437 const char *target, bool user)
439 struct perf_probe_point pp = { .function = lr->function,
440 .file = lr->file,
441 .line = lr->start };
442 struct perf_probe_point result;
443 int ret, len = 0;
445 memset(&result, 0, sizeof(result));
447 if (lr->end != INT_MAX)
448 len = lr->end - lr->start;
449 ret = find_alternative_probe_point(dinfo, &pp, &result,
450 target, NULL, user);
451 if (!ret) {
452 lr->function = result.function;
453 lr->file = result.file;
454 lr->start = result.line;
455 if (lr->end != INT_MAX)
456 lr->end = lr->start + len;
457 clear_perf_probe_point(&pp);
459 return ret;
462 #ifdef HAVE_DEBUGINFOD_SUPPORT
463 static struct debuginfo *open_from_debuginfod(struct dso *dso, struct nsinfo *nsi,
464 bool silent)
466 debuginfod_client *c = debuginfod_begin();
467 char sbuild_id[SBUILD_ID_SIZE + 1];
468 struct debuginfo *ret = NULL;
469 struct nscookie nsc;
470 char *path;
471 int fd;
473 if (!c)
474 return NULL;
476 build_id__sprintf(&dso->bid, sbuild_id);
477 fd = debuginfod_find_debuginfo(c, (const unsigned char *)sbuild_id,
478 0, &path);
479 if (fd >= 0)
480 close(fd);
481 debuginfod_end(c);
482 if (fd < 0) {
483 if (!silent)
484 pr_debug("Failed to find debuginfo in debuginfod.\n");
485 return NULL;
487 if (!silent)
488 pr_debug("Load debuginfo from debuginfod (%s)\n", path);
490 nsinfo__mountns_enter(nsi, &nsc);
491 ret = debuginfo__new((const char *)path);
492 nsinfo__mountns_exit(&nsc);
493 return ret;
495 #else
496 static inline
497 struct debuginfo *open_from_debuginfod(struct dso *dso __maybe_unused,
498 struct nsinfo *nsi __maybe_unused,
499 bool silent __maybe_unused)
501 return NULL;
503 #endif
505 /* Open new debuginfo of given module */
506 static struct debuginfo *open_debuginfo(const char *module, struct nsinfo *nsi,
507 bool silent)
509 const char *path = module;
510 char reason[STRERR_BUFSIZE];
511 struct debuginfo *ret = NULL;
512 struct dso *dso = NULL;
513 struct nscookie nsc;
514 int err;
516 if (!module || !strchr(module, '/')) {
517 err = kernel_get_module_dso(module, &dso);
518 if (err < 0) {
519 if (!dso || dso->load_errno == 0) {
520 if (!str_error_r(-err, reason, STRERR_BUFSIZE))
521 strcpy(reason, "(unknown)");
522 } else
523 dso__strerror_load(dso, reason, STRERR_BUFSIZE);
524 if (dso)
525 ret = open_from_debuginfod(dso, nsi, silent);
526 if (ret)
527 return ret;
528 if (!silent) {
529 if (module)
530 pr_err("Module %s is not loaded, please specify its full path name.\n", module);
531 else
532 pr_err("Failed to find the path for the kernel: %s\n", reason);
534 return NULL;
536 path = dso->long_name;
538 nsinfo__mountns_enter(nsi, &nsc);
539 ret = debuginfo__new(path);
540 if (!ret && !silent) {
541 pr_warning("The %s file has no debug information.\n", path);
542 if (!module || !strtailcmp(path, ".ko"))
543 pr_warning("Rebuild with CONFIG_DEBUG_INFO=y, ");
544 else
545 pr_warning("Rebuild with -g, ");
546 pr_warning("or install an appropriate debuginfo package.\n");
548 nsinfo__mountns_exit(&nsc);
549 return ret;
552 /* For caching the last debuginfo */
553 static struct debuginfo *debuginfo_cache;
554 static char *debuginfo_cache_path;
556 static struct debuginfo *debuginfo_cache__open(const char *module, bool silent)
558 const char *path = module;
560 /* If the module is NULL, it should be the kernel. */
561 if (!module)
562 path = "kernel";
564 if (debuginfo_cache_path && !strcmp(debuginfo_cache_path, path))
565 goto out;
567 /* Copy module path */
568 free(debuginfo_cache_path);
569 debuginfo_cache_path = strdup(path);
570 if (!debuginfo_cache_path) {
571 debuginfo__delete(debuginfo_cache);
572 debuginfo_cache = NULL;
573 goto out;
576 debuginfo_cache = open_debuginfo(module, NULL, silent);
577 if (!debuginfo_cache)
578 zfree(&debuginfo_cache_path);
579 out:
580 return debuginfo_cache;
583 static void debuginfo_cache__exit(void)
585 debuginfo__delete(debuginfo_cache);
586 debuginfo_cache = NULL;
587 zfree(&debuginfo_cache_path);
591 static int get_text_start_address(const char *exec, unsigned long *address,
592 struct nsinfo *nsi)
594 Elf *elf;
595 GElf_Ehdr ehdr;
596 GElf_Shdr shdr;
597 int fd, ret = -ENOENT;
598 struct nscookie nsc;
600 nsinfo__mountns_enter(nsi, &nsc);
601 fd = open(exec, O_RDONLY);
602 nsinfo__mountns_exit(&nsc);
603 if (fd < 0)
604 return -errno;
606 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
607 if (elf == NULL) {
608 ret = -EINVAL;
609 goto out_close;
612 if (gelf_getehdr(elf, &ehdr) == NULL)
613 goto out;
615 if (!elf_section_by_name(elf, &ehdr, &shdr, ".text", NULL))
616 goto out;
618 *address = shdr.sh_addr - shdr.sh_offset;
619 ret = 0;
620 out:
621 elf_end(elf);
622 out_close:
623 close(fd);
625 return ret;
629 * Convert trace point to probe point with debuginfo
631 static int find_perf_probe_point_from_dwarf(struct probe_trace_point *tp,
632 struct perf_probe_point *pp,
633 bool is_kprobe)
635 struct debuginfo *dinfo = NULL;
636 unsigned long stext = 0;
637 u64 addr = tp->address;
638 int ret = -ENOENT;
640 /* convert the address to dwarf address */
641 if (!is_kprobe) {
642 if (!addr) {
643 ret = -EINVAL;
644 goto error;
646 ret = get_text_start_address(tp->module, &stext, NULL);
647 if (ret < 0)
648 goto error;
649 addr += stext;
650 } else if (tp->symbol) {
651 /* If the module is given, this returns relative address */
652 ret = kernel_get_symbol_address_by_name(tp->symbol, &addr,
653 false, !!tp->module);
654 if (ret != 0)
655 goto error;
656 addr += tp->offset;
659 pr_debug("try to find information at %" PRIx64 " in %s\n", addr,
660 tp->module ? : "kernel");
662 dinfo = debuginfo_cache__open(tp->module, verbose <= 0);
663 if (dinfo)
664 ret = debuginfo__find_probe_point(dinfo,
665 (unsigned long)addr, pp);
666 else
667 ret = -ENOENT;
669 if (ret > 0) {
670 pp->retprobe = tp->retprobe;
671 return 0;
673 error:
674 pr_debug("Failed to find corresponding probes from debuginfo.\n");
675 return ret ? : -ENOENT;
678 /* Adjust symbol name and address */
679 static int post_process_probe_trace_point(struct probe_trace_point *tp,
680 struct map *map, unsigned long offs)
682 struct symbol *sym;
683 u64 addr = tp->address - offs;
685 sym = map__find_symbol(map, addr);
686 if (!sym)
687 return -ENOENT;
689 if (strcmp(sym->name, tp->symbol)) {
690 /* If we have no realname, use symbol for it */
691 if (!tp->realname)
692 tp->realname = tp->symbol;
693 else
694 free(tp->symbol);
695 tp->symbol = strdup(sym->name);
696 if (!tp->symbol)
697 return -ENOMEM;
699 tp->offset = addr - sym->start;
700 tp->address -= offs;
702 return 0;
706 * Rename DWARF symbols to ELF symbols -- gcc sometimes optimizes functions
707 * and generate new symbols with suffixes such as .constprop.N or .isra.N
708 * etc. Since those symbols are not recorded in DWARF, we have to find
709 * correct generated symbols from offline ELF binary.
710 * For online kernel or uprobes we don't need this because those are
711 * rebased on _text, or already a section relative address.
713 static int
714 post_process_offline_probe_trace_events(struct probe_trace_event *tevs,
715 int ntevs, const char *pathname)
717 struct map *map;
718 unsigned long stext = 0;
719 int i, ret = 0;
721 /* Prepare a map for offline binary */
722 map = dso__new_map(pathname);
723 if (!map || get_text_start_address(pathname, &stext, NULL) < 0) {
724 pr_warning("Failed to get ELF symbols for %s\n", pathname);
725 return -EINVAL;
728 for (i = 0; i < ntevs; i++) {
729 ret = post_process_probe_trace_point(&tevs[i].point,
730 map, stext);
731 if (ret < 0)
732 break;
734 map__put(map);
736 return ret;
739 static int add_exec_to_probe_trace_events(struct probe_trace_event *tevs,
740 int ntevs, const char *exec,
741 struct nsinfo *nsi)
743 int i, ret = 0;
744 unsigned long stext = 0;
746 if (!exec)
747 return 0;
749 ret = get_text_start_address(exec, &stext, nsi);
750 if (ret < 0)
751 return ret;
753 for (i = 0; i < ntevs && ret >= 0; i++) {
754 /* point.address is the address of point.symbol + point.offset */
755 tevs[i].point.address -= stext;
756 tevs[i].point.module = strdup(exec);
757 if (!tevs[i].point.module) {
758 ret = -ENOMEM;
759 break;
761 tevs[i].uprobes = true;
764 return ret;
767 static int
768 post_process_module_probe_trace_events(struct probe_trace_event *tevs,
769 int ntevs, const char *module,
770 struct debuginfo *dinfo)
772 Dwarf_Addr text_offs = 0;
773 int i, ret = 0;
774 char *mod_name = NULL;
775 struct map *map;
777 if (!module)
778 return 0;
780 map = get_target_map(module, NULL, false);
781 if (!map || debuginfo__get_text_offset(dinfo, &text_offs, true) < 0) {
782 pr_warning("Failed to get ELF symbols for %s\n", module);
783 return -EINVAL;
786 mod_name = find_module_name(module);
787 for (i = 0; i < ntevs; i++) {
788 ret = post_process_probe_trace_point(&tevs[i].point,
789 map, (unsigned long)text_offs);
790 if (ret < 0)
791 break;
792 tevs[i].point.module =
793 strdup(mod_name ? mod_name : module);
794 if (!tevs[i].point.module) {
795 ret = -ENOMEM;
796 break;
800 free(mod_name);
801 map__put(map);
803 return ret;
806 static int
807 post_process_kernel_probe_trace_events(struct probe_trace_event *tevs,
808 int ntevs)
810 struct ref_reloc_sym *reloc_sym;
811 struct map *map;
812 char *tmp;
813 int i, skipped = 0;
815 /* Skip post process if the target is an offline kernel */
816 if (symbol_conf.ignore_vmlinux_buildid)
817 return post_process_offline_probe_trace_events(tevs, ntevs,
818 symbol_conf.vmlinux_name);
820 reloc_sym = kernel_get_ref_reloc_sym(&map);
821 if (!reloc_sym) {
822 pr_warning("Relocated base symbol is not found!\n");
823 return -EINVAL;
826 for (i = 0; i < ntevs; i++) {
827 if (!tevs[i].point.address)
828 continue;
829 if (tevs[i].point.retprobe && !kretprobe_offset_is_supported())
830 continue;
832 * If we found a wrong one, mark it by NULL symbol.
833 * Since addresses in debuginfo is same as objdump, we need
834 * to convert it to addresses on memory.
836 if (kprobe_warn_out_range(tevs[i].point.symbol,
837 map__objdump_2mem(map, tevs[i].point.address))) {
838 tmp = NULL;
839 skipped++;
840 } else {
841 tmp = strdup(reloc_sym->name);
842 if (!tmp)
843 return -ENOMEM;
845 /* If we have no realname, use symbol for it */
846 if (!tevs[i].point.realname)
847 tevs[i].point.realname = tevs[i].point.symbol;
848 else
849 free(tevs[i].point.symbol);
850 tevs[i].point.symbol = tmp;
851 tevs[i].point.offset = tevs[i].point.address -
852 (map->reloc ? reloc_sym->unrelocated_addr :
853 reloc_sym->addr);
855 return skipped;
858 void __weak
859 arch__post_process_probe_trace_events(struct perf_probe_event *pev __maybe_unused,
860 int ntevs __maybe_unused)
864 /* Post processing the probe events */
865 static int post_process_probe_trace_events(struct perf_probe_event *pev,
866 struct probe_trace_event *tevs,
867 int ntevs, const char *module,
868 bool uprobe, struct debuginfo *dinfo)
870 int ret;
872 if (uprobe)
873 ret = add_exec_to_probe_trace_events(tevs, ntevs, module,
874 pev->nsi);
875 else if (module)
876 /* Currently ref_reloc_sym based probe is not for drivers */
877 ret = post_process_module_probe_trace_events(tevs, ntevs,
878 module, dinfo);
879 else
880 ret = post_process_kernel_probe_trace_events(tevs, ntevs);
882 if (ret >= 0)
883 arch__post_process_probe_trace_events(pev, ntevs);
885 return ret;
888 /* Try to find perf_probe_event with debuginfo */
889 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
890 struct probe_trace_event **tevs)
892 bool need_dwarf = perf_probe_event_need_dwarf(pev);
893 struct perf_probe_point tmp;
894 struct debuginfo *dinfo;
895 int ntevs, ret = 0;
897 dinfo = open_debuginfo(pev->target, pev->nsi, !need_dwarf);
898 if (!dinfo) {
899 if (need_dwarf)
900 return -ENOENT;
901 pr_debug("Could not open debuginfo. Try to use symbols.\n");
902 return 0;
905 pr_debug("Try to find probe point from debuginfo.\n");
906 /* Searching trace events corresponding to a probe event */
907 ntevs = debuginfo__find_trace_events(dinfo, pev, tevs);
909 if (ntevs == 0) { /* Not found, retry with an alternative */
910 ret = get_alternative_probe_event(dinfo, pev, &tmp);
911 if (!ret) {
912 ntevs = debuginfo__find_trace_events(dinfo, pev, tevs);
914 * Write back to the original probe_event for
915 * setting appropriate (user given) event name
917 clear_perf_probe_point(&pev->point);
918 memcpy(&pev->point, &tmp, sizeof(tmp));
922 if (ntevs > 0) { /* Succeeded to find trace events */
923 pr_debug("Found %d probe_trace_events.\n", ntevs);
924 ret = post_process_probe_trace_events(pev, *tevs, ntevs,
925 pev->target, pev->uprobes, dinfo);
926 if (ret < 0 || ret == ntevs) {
927 pr_debug("Post processing failed or all events are skipped. (%d)\n", ret);
928 clear_probe_trace_events(*tevs, ntevs);
929 zfree(tevs);
930 ntevs = 0;
934 debuginfo__delete(dinfo);
936 if (ntevs == 0) { /* No error but failed to find probe point. */
937 pr_warning("Probe point '%s' not found.\n",
938 synthesize_perf_probe_point(&pev->point));
939 return -ENOENT;
940 } else if (ntevs < 0) {
941 /* Error path : ntevs < 0 */
942 pr_debug("An error occurred in debuginfo analysis (%d).\n", ntevs);
943 if (ntevs == -EBADF)
944 pr_warning("Warning: No dwarf info found in the vmlinux - "
945 "please rebuild kernel with CONFIG_DEBUG_INFO=y.\n");
946 if (!need_dwarf) {
947 pr_debug("Trying to use symbols.\n");
948 return 0;
951 return ntevs;
954 #define LINEBUF_SIZE 256
955 #define NR_ADDITIONAL_LINES 2
957 static int __show_one_line(FILE *fp, int l, bool skip, bool show_num)
959 char buf[LINEBUF_SIZE], sbuf[STRERR_BUFSIZE];
960 const char *color = show_num ? "" : PERF_COLOR_BLUE;
961 const char *prefix = NULL;
963 do {
964 if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
965 goto error;
966 if (skip)
967 continue;
968 if (!prefix) {
969 prefix = show_num ? "%7d " : " ";
970 color_fprintf(stdout, color, prefix, l);
972 color_fprintf(stdout, color, "%s", buf);
974 } while (strchr(buf, '\n') == NULL);
976 return 1;
977 error:
978 if (ferror(fp)) {
979 pr_warning("File read error: %s\n",
980 str_error_r(errno, sbuf, sizeof(sbuf)));
981 return -1;
983 return 0;
986 static int _show_one_line(FILE *fp, int l, bool skip, bool show_num)
988 int rv = __show_one_line(fp, l, skip, show_num);
989 if (rv == 0) {
990 pr_warning("Source file is shorter than expected.\n");
991 rv = -1;
993 return rv;
996 #define show_one_line_with_num(f,l) _show_one_line(f,l,false,true)
997 #define show_one_line(f,l) _show_one_line(f,l,false,false)
998 #define skip_one_line(f,l) _show_one_line(f,l,true,false)
999 #define show_one_line_or_eof(f,l) __show_one_line(f,l,false,false)
1002 * Show line-range always requires debuginfo to find source file and
1003 * line number.
1005 static int __show_line_range(struct line_range *lr, const char *module,
1006 bool user)
1008 struct build_id bid;
1009 int l = 1;
1010 struct int_node *ln;
1011 struct debuginfo *dinfo;
1012 FILE *fp;
1013 int ret;
1014 char *tmp;
1015 char sbuf[STRERR_BUFSIZE];
1016 char sbuild_id[SBUILD_ID_SIZE] = "";
1018 /* Search a line range */
1019 dinfo = open_debuginfo(module, NULL, false);
1020 if (!dinfo)
1021 return -ENOENT;
1023 ret = debuginfo__find_line_range(dinfo, lr);
1024 if (!ret) { /* Not found, retry with an alternative */
1025 ret = get_alternative_line_range(dinfo, lr, module, user);
1026 if (!ret)
1027 ret = debuginfo__find_line_range(dinfo, lr);
1029 if (dinfo->build_id) {
1030 build_id__init(&bid, dinfo->build_id, BUILD_ID_SIZE);
1031 build_id__sprintf(&bid, sbuild_id);
1033 debuginfo__delete(dinfo);
1034 if (ret == 0 || ret == -ENOENT) {
1035 pr_warning("Specified source line is not found.\n");
1036 return -ENOENT;
1037 } else if (ret < 0) {
1038 pr_warning("Debuginfo analysis failed.\n");
1039 return ret;
1042 /* Convert source file path */
1043 tmp = lr->path;
1044 ret = find_source_path(tmp, sbuild_id, lr->comp_dir, &lr->path);
1046 /* Free old path when new path is assigned */
1047 if (tmp != lr->path)
1048 free(tmp);
1050 if (ret < 0) {
1051 pr_warning("Failed to find source file path.\n");
1052 return ret;
1055 setup_pager();
1057 if (lr->function)
1058 fprintf(stdout, "<%s@%s:%d>\n", lr->function, lr->path,
1059 lr->start - lr->offset);
1060 else
1061 fprintf(stdout, "<%s:%d>\n", lr->path, lr->start);
1063 fp = fopen(lr->path, "r");
1064 if (fp == NULL) {
1065 pr_warning("Failed to open %s: %s\n", lr->path,
1066 str_error_r(errno, sbuf, sizeof(sbuf)));
1067 return -errno;
1069 /* Skip to starting line number */
1070 while (l < lr->start) {
1071 ret = skip_one_line(fp, l++);
1072 if (ret < 0)
1073 goto end;
1076 intlist__for_each_entry(ln, lr->line_list) {
1077 for (; ln->i > l; l++) {
1078 ret = show_one_line(fp, l - lr->offset);
1079 if (ret < 0)
1080 goto end;
1082 ret = show_one_line_with_num(fp, l++ - lr->offset);
1083 if (ret < 0)
1084 goto end;
1087 if (lr->end == INT_MAX)
1088 lr->end = l + NR_ADDITIONAL_LINES;
1089 while (l <= lr->end) {
1090 ret = show_one_line_or_eof(fp, l++ - lr->offset);
1091 if (ret <= 0)
1092 break;
1094 end:
1095 fclose(fp);
1096 return ret;
1099 int show_line_range(struct line_range *lr, const char *module,
1100 struct nsinfo *nsi, bool user)
1102 int ret;
1103 struct nscookie nsc;
1105 ret = init_probe_symbol_maps(user);
1106 if (ret < 0)
1107 return ret;
1108 nsinfo__mountns_enter(nsi, &nsc);
1109 ret = __show_line_range(lr, module, user);
1110 nsinfo__mountns_exit(&nsc);
1111 exit_probe_symbol_maps();
1113 return ret;
1116 static int show_available_vars_at(struct debuginfo *dinfo,
1117 struct perf_probe_event *pev,
1118 struct strfilter *_filter)
1120 char *buf;
1121 int ret, i, nvars;
1122 struct str_node *node;
1123 struct variable_list *vls = NULL, *vl;
1124 struct perf_probe_point tmp;
1125 const char *var;
1127 buf = synthesize_perf_probe_point(&pev->point);
1128 if (!buf)
1129 return -EINVAL;
1130 pr_debug("Searching variables at %s\n", buf);
1132 ret = debuginfo__find_available_vars_at(dinfo, pev, &vls);
1133 if (!ret) { /* Not found, retry with an alternative */
1134 ret = get_alternative_probe_event(dinfo, pev, &tmp);
1135 if (!ret) {
1136 ret = debuginfo__find_available_vars_at(dinfo, pev,
1137 &vls);
1138 /* Release the old probe_point */
1139 clear_perf_probe_point(&tmp);
1142 if (ret <= 0) {
1143 if (ret == 0 || ret == -ENOENT) {
1144 pr_err("Failed to find the address of %s\n", buf);
1145 ret = -ENOENT;
1146 } else
1147 pr_warning("Debuginfo analysis failed.\n");
1148 goto end;
1151 /* Some variables are found */
1152 fprintf(stdout, "Available variables at %s\n", buf);
1153 for (i = 0; i < ret; i++) {
1154 vl = &vls[i];
1156 * A probe point might be converted to
1157 * several trace points.
1159 fprintf(stdout, "\t@<%s+%lu>\n", vl->point.symbol,
1160 vl->point.offset);
1161 zfree(&vl->point.symbol);
1162 nvars = 0;
1163 if (vl->vars) {
1164 strlist__for_each_entry(node, vl->vars) {
1165 var = strchr(node->s, '\t') + 1;
1166 if (strfilter__compare(_filter, var)) {
1167 fprintf(stdout, "\t\t%s\n", node->s);
1168 nvars++;
1171 strlist__delete(vl->vars);
1173 if (nvars == 0)
1174 fprintf(stdout, "\t\t(No matched variables)\n");
1176 free(vls);
1177 end:
1178 free(buf);
1179 return ret;
1182 /* Show available variables on given probe point */
1183 int show_available_vars(struct perf_probe_event *pevs, int npevs,
1184 struct strfilter *_filter)
1186 int i, ret = 0;
1187 struct debuginfo *dinfo;
1189 ret = init_probe_symbol_maps(pevs->uprobes);
1190 if (ret < 0)
1191 return ret;
1193 dinfo = open_debuginfo(pevs->target, pevs->nsi, false);
1194 if (!dinfo) {
1195 ret = -ENOENT;
1196 goto out;
1199 setup_pager();
1201 for (i = 0; i < npevs && ret >= 0; i++)
1202 ret = show_available_vars_at(dinfo, &pevs[i], _filter);
1204 debuginfo__delete(dinfo);
1205 out:
1206 exit_probe_symbol_maps();
1207 return ret;
1210 #else /* !HAVE_DWARF_SUPPORT */
1212 static void debuginfo_cache__exit(void)
1216 static int
1217 find_perf_probe_point_from_dwarf(struct probe_trace_point *tp __maybe_unused,
1218 struct perf_probe_point *pp __maybe_unused,
1219 bool is_kprobe __maybe_unused)
1221 return -ENOSYS;
1224 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
1225 struct probe_trace_event **tevs __maybe_unused)
1227 if (perf_probe_event_need_dwarf(pev)) {
1228 pr_warning("Debuginfo-analysis is not supported.\n");
1229 return -ENOSYS;
1232 return 0;
1235 int show_line_range(struct line_range *lr __maybe_unused,
1236 const char *module __maybe_unused,
1237 struct nsinfo *nsi __maybe_unused,
1238 bool user __maybe_unused)
1240 pr_warning("Debuginfo-analysis is not supported.\n");
1241 return -ENOSYS;
1244 int show_available_vars(struct perf_probe_event *pevs __maybe_unused,
1245 int npevs __maybe_unused,
1246 struct strfilter *filter __maybe_unused)
1248 pr_warning("Debuginfo-analysis is not supported.\n");
1249 return -ENOSYS;
1251 #endif
1253 void line_range__clear(struct line_range *lr)
1255 zfree(&lr->function);
1256 zfree(&lr->file);
1257 zfree(&lr->path);
1258 zfree(&lr->comp_dir);
1259 intlist__delete(lr->line_list);
1262 int line_range__init(struct line_range *lr)
1264 memset(lr, 0, sizeof(*lr));
1265 lr->line_list = intlist__new(NULL);
1266 if (!lr->line_list)
1267 return -ENOMEM;
1268 else
1269 return 0;
1272 static int parse_line_num(char **ptr, int *val, const char *what)
1274 const char *start = *ptr;
1276 errno = 0;
1277 *val = strtol(*ptr, ptr, 0);
1278 if (errno || *ptr == start) {
1279 semantic_error("'%s' is not a valid number.\n", what);
1280 return -EINVAL;
1282 return 0;
1285 /* Check the name is good for event, group or function */
1286 static bool is_c_func_name(const char *name)
1288 if (!isalpha(*name) && *name != '_')
1289 return false;
1290 while (*++name != '\0') {
1291 if (!isalpha(*name) && !isdigit(*name) && *name != '_')
1292 return false;
1294 return true;
1298 * Stuff 'lr' according to the line range described by 'arg'.
1299 * The line range syntax is described by:
1301 * SRC[:SLN[+NUM|-ELN]]
1302 * FNC[@SRC][:SLN[+NUM|-ELN]]
1304 int parse_line_range_desc(const char *arg, struct line_range *lr)
1306 char *range, *file, *name = strdup(arg);
1307 int err;
1309 if (!name)
1310 return -ENOMEM;
1312 lr->start = 0;
1313 lr->end = INT_MAX;
1315 range = strchr(name, ':');
1316 if (range) {
1317 *range++ = '\0';
1319 err = parse_line_num(&range, &lr->start, "start line");
1320 if (err)
1321 goto err;
1323 if (*range == '+' || *range == '-') {
1324 const char c = *range++;
1326 err = parse_line_num(&range, &lr->end, "end line");
1327 if (err)
1328 goto err;
1330 if (c == '+') {
1331 lr->end += lr->start;
1333 * Adjust the number of lines here.
1334 * If the number of lines == 1, the
1335 * the end of line should be equal to
1336 * the start of line.
1338 lr->end--;
1342 pr_debug("Line range is %d to %d\n", lr->start, lr->end);
1344 err = -EINVAL;
1345 if (lr->start > lr->end) {
1346 semantic_error("Start line must be smaller"
1347 " than end line.\n");
1348 goto err;
1350 if (*range != '\0') {
1351 semantic_error("Tailing with invalid str '%s'.\n", range);
1352 goto err;
1356 file = strchr(name, '@');
1357 if (file) {
1358 *file = '\0';
1359 lr->file = strdup(++file);
1360 if (lr->file == NULL) {
1361 err = -ENOMEM;
1362 goto err;
1364 lr->function = name;
1365 } else if (strchr(name, '/') || strchr(name, '.'))
1366 lr->file = name;
1367 else if (is_c_func_name(name))/* We reuse it for checking funcname */
1368 lr->function = name;
1369 else { /* Invalid name */
1370 semantic_error("'%s' is not a valid function name.\n", name);
1371 err = -EINVAL;
1372 goto err;
1375 return 0;
1376 err:
1377 free(name);
1378 return err;
1381 static int parse_perf_probe_event_name(char **arg, struct perf_probe_event *pev)
1383 char *ptr;
1385 ptr = strpbrk_esc(*arg, ":");
1386 if (ptr) {
1387 *ptr = '\0';
1388 if (!pev->sdt && !is_c_func_name(*arg))
1389 goto ng_name;
1390 pev->group = strdup_esc(*arg);
1391 if (!pev->group)
1392 return -ENOMEM;
1393 *arg = ptr + 1;
1394 } else
1395 pev->group = NULL;
1397 pev->event = strdup_esc(*arg);
1398 if (pev->event == NULL)
1399 return -ENOMEM;
1401 if (!pev->sdt && !is_c_func_name(pev->event)) {
1402 zfree(&pev->event);
1403 ng_name:
1404 zfree(&pev->group);
1405 semantic_error("%s is bad for event name -it must "
1406 "follow C symbol-naming rule.\n", *arg);
1407 return -EINVAL;
1409 return 0;
1412 /* Parse probepoint definition. */
1413 static int parse_perf_probe_point(char *arg, struct perf_probe_event *pev)
1415 struct perf_probe_point *pp = &pev->point;
1416 char *ptr, *tmp;
1417 char c, nc = 0;
1418 bool file_spec = false;
1419 int ret;
1422 * <Syntax>
1423 * perf probe [GRP:][EVENT=]SRC[:LN|;PTN]
1424 * perf probe [GRP:][EVENT=]FUNC[@SRC][+OFFS|%return|:LN|;PAT]
1425 * perf probe %[GRP:]SDT_EVENT
1427 if (!arg)
1428 return -EINVAL;
1430 if (is_sdt_event(arg)) {
1431 pev->sdt = true;
1432 if (arg[0] == '%')
1433 arg++;
1436 ptr = strpbrk_esc(arg, ";=@+%");
1437 if (pev->sdt) {
1438 if (ptr) {
1439 if (*ptr != '@') {
1440 semantic_error("%s must be an SDT name.\n",
1441 arg);
1442 return -EINVAL;
1444 /* This must be a target file name or build id */
1445 tmp = build_id_cache__complement(ptr + 1);
1446 if (tmp) {
1447 pev->target = build_id_cache__origname(tmp);
1448 free(tmp);
1449 } else
1450 pev->target = strdup_esc(ptr + 1);
1451 if (!pev->target)
1452 return -ENOMEM;
1453 *ptr = '\0';
1455 ret = parse_perf_probe_event_name(&arg, pev);
1456 if (ret == 0) {
1457 if (asprintf(&pev->point.function, "%%%s", pev->event) < 0)
1458 ret = -errno;
1460 return ret;
1463 if (ptr && *ptr == '=') { /* Event name */
1464 *ptr = '\0';
1465 tmp = ptr + 1;
1466 ret = parse_perf_probe_event_name(&arg, pev);
1467 if (ret < 0)
1468 return ret;
1470 arg = tmp;
1474 * Check arg is function or file name and copy it.
1476 * We consider arg to be a file spec if and only if it satisfies
1477 * all of the below criteria::
1478 * - it does not include any of "+@%",
1479 * - it includes one of ":;", and
1480 * - it has a period '.' in the name.
1482 * Otherwise, we consider arg to be a function specification.
1484 if (!strpbrk_esc(arg, "+@%")) {
1485 ptr = strpbrk_esc(arg, ";:");
1486 /* This is a file spec if it includes a '.' before ; or : */
1487 if (ptr && memchr(arg, '.', ptr - arg))
1488 file_spec = true;
1491 ptr = strpbrk_esc(arg, ";:+@%");
1492 if (ptr) {
1493 nc = *ptr;
1494 *ptr++ = '\0';
1497 if (arg[0] == '\0')
1498 tmp = NULL;
1499 else {
1500 tmp = strdup_esc(arg);
1501 if (tmp == NULL)
1502 return -ENOMEM;
1505 if (file_spec)
1506 pp->file = tmp;
1507 else {
1508 pp->function = tmp;
1511 * Keep pp->function even if this is absolute address,
1512 * so it can mark whether abs_address is valid.
1513 * Which make 'perf probe lib.bin 0x0' possible.
1515 * Note that checking length of tmp is not needed
1516 * because when we access tmp[1] we know tmp[0] is '0',
1517 * so tmp[1] should always valid (but could be '\0').
1519 if (tmp && !strncmp(tmp, "0x", 2)) {
1520 pp->abs_address = strtoul(pp->function, &tmp, 0);
1521 if (*tmp != '\0') {
1522 semantic_error("Invalid absolute address.\n");
1523 return -EINVAL;
1528 /* Parse other options */
1529 while (ptr) {
1530 arg = ptr;
1531 c = nc;
1532 if (c == ';') { /* Lazy pattern must be the last part */
1533 pp->lazy_line = strdup(arg); /* let leave escapes */
1534 if (pp->lazy_line == NULL)
1535 return -ENOMEM;
1536 break;
1538 ptr = strpbrk_esc(arg, ";:+@%");
1539 if (ptr) {
1540 nc = *ptr;
1541 *ptr++ = '\0';
1543 switch (c) {
1544 case ':': /* Line number */
1545 pp->line = strtoul(arg, &tmp, 0);
1546 if (*tmp != '\0') {
1547 semantic_error("There is non-digit char"
1548 " in line number.\n");
1549 return -EINVAL;
1551 break;
1552 case '+': /* Byte offset from a symbol */
1553 pp->offset = strtoul(arg, &tmp, 0);
1554 if (*tmp != '\0') {
1555 semantic_error("There is non-digit character"
1556 " in offset.\n");
1557 return -EINVAL;
1559 break;
1560 case '@': /* File name */
1561 if (pp->file) {
1562 semantic_error("SRC@SRC is not allowed.\n");
1563 return -EINVAL;
1565 pp->file = strdup_esc(arg);
1566 if (pp->file == NULL)
1567 return -ENOMEM;
1568 break;
1569 case '%': /* Probe places */
1570 if (strcmp(arg, "return") == 0) {
1571 pp->retprobe = 1;
1572 } else { /* Others not supported yet */
1573 semantic_error("%%%s is not supported.\n", arg);
1574 return -ENOTSUP;
1576 break;
1577 default: /* Buggy case */
1578 pr_err("This program has a bug at %s:%d.\n",
1579 __FILE__, __LINE__);
1580 return -ENOTSUP;
1581 break;
1585 /* Exclusion check */
1586 if (pp->lazy_line && pp->line) {
1587 semantic_error("Lazy pattern can't be used with"
1588 " line number.\n");
1589 return -EINVAL;
1592 if (pp->lazy_line && pp->offset) {
1593 semantic_error("Lazy pattern can't be used with offset.\n");
1594 return -EINVAL;
1597 if (pp->line && pp->offset) {
1598 semantic_error("Offset can't be used with line number.\n");
1599 return -EINVAL;
1602 if (!pp->line && !pp->lazy_line && pp->file && !pp->function) {
1603 semantic_error("File always requires line number or "
1604 "lazy pattern.\n");
1605 return -EINVAL;
1608 if (pp->offset && !pp->function) {
1609 semantic_error("Offset requires an entry function.\n");
1610 return -EINVAL;
1613 if ((pp->offset || pp->line || pp->lazy_line) && pp->retprobe) {
1614 semantic_error("Offset/Line/Lazy pattern can't be used with "
1615 "return probe.\n");
1616 return -EINVAL;
1619 pr_debug("symbol:%s file:%s line:%d offset:%lu return:%d lazy:%s\n",
1620 pp->function, pp->file, pp->line, pp->offset, pp->retprobe,
1621 pp->lazy_line);
1622 return 0;
1625 /* Parse perf-probe event argument */
1626 static int parse_perf_probe_arg(char *str, struct perf_probe_arg *arg)
1628 char *tmp, *goodname;
1629 struct perf_probe_arg_field **fieldp;
1631 pr_debug("parsing arg: %s into ", str);
1633 tmp = strchr(str, '=');
1634 if (tmp) {
1635 arg->name = strndup(str, tmp - str);
1636 if (arg->name == NULL)
1637 return -ENOMEM;
1638 pr_debug("name:%s ", arg->name);
1639 str = tmp + 1;
1642 tmp = strchr(str, '@');
1643 if (tmp && tmp != str && !strcmp(tmp + 1, "user")) { /* user attr */
1644 if (!user_access_is_supported()) {
1645 semantic_error("ftrace does not support user access\n");
1646 return -EINVAL;
1648 *tmp = '\0';
1649 arg->user_access = true;
1650 pr_debug("user_access ");
1653 tmp = strchr(str, ':');
1654 if (tmp) { /* Type setting */
1655 *tmp = '\0';
1656 arg->type = strdup(tmp + 1);
1657 if (arg->type == NULL)
1658 return -ENOMEM;
1659 pr_debug("type:%s ", arg->type);
1662 tmp = strpbrk(str, "-.[");
1663 if (!is_c_varname(str) || !tmp) {
1664 /* A variable, register, symbol or special value */
1665 arg->var = strdup(str);
1666 if (arg->var == NULL)
1667 return -ENOMEM;
1668 pr_debug("%s\n", arg->var);
1669 return 0;
1672 /* Structure fields or array element */
1673 arg->var = strndup(str, tmp - str);
1674 if (arg->var == NULL)
1675 return -ENOMEM;
1676 goodname = arg->var;
1677 pr_debug("%s, ", arg->var);
1678 fieldp = &arg->field;
1680 do {
1681 *fieldp = zalloc(sizeof(struct perf_probe_arg_field));
1682 if (*fieldp == NULL)
1683 return -ENOMEM;
1684 if (*tmp == '[') { /* Array */
1685 str = tmp;
1686 (*fieldp)->index = strtol(str + 1, &tmp, 0);
1687 (*fieldp)->ref = true;
1688 if (*tmp != ']' || tmp == str + 1) {
1689 semantic_error("Array index must be a"
1690 " number.\n");
1691 return -EINVAL;
1693 tmp++;
1694 if (*tmp == '\0')
1695 tmp = NULL;
1696 } else { /* Structure */
1697 if (*tmp == '.') {
1698 str = tmp + 1;
1699 (*fieldp)->ref = false;
1700 } else if (tmp[1] == '>') {
1701 str = tmp + 2;
1702 (*fieldp)->ref = true;
1703 } else {
1704 semantic_error("Argument parse error: %s\n",
1705 str);
1706 return -EINVAL;
1708 tmp = strpbrk(str, "-.[");
1710 if (tmp) {
1711 (*fieldp)->name = strndup(str, tmp - str);
1712 if ((*fieldp)->name == NULL)
1713 return -ENOMEM;
1714 if (*str != '[')
1715 goodname = (*fieldp)->name;
1716 pr_debug("%s(%d), ", (*fieldp)->name, (*fieldp)->ref);
1717 fieldp = &(*fieldp)->next;
1719 } while (tmp);
1720 (*fieldp)->name = strdup(str);
1721 if ((*fieldp)->name == NULL)
1722 return -ENOMEM;
1723 if (*str != '[')
1724 goodname = (*fieldp)->name;
1725 pr_debug("%s(%d)\n", (*fieldp)->name, (*fieldp)->ref);
1727 /* If no name is specified, set the last field name (not array index)*/
1728 if (!arg->name) {
1729 arg->name = strdup(goodname);
1730 if (arg->name == NULL)
1731 return -ENOMEM;
1733 return 0;
1736 /* Parse perf-probe event command */
1737 int parse_perf_probe_command(const char *cmd, struct perf_probe_event *pev)
1739 char **argv;
1740 int argc, i, ret = 0;
1742 argv = argv_split(cmd, &argc);
1743 if (!argv) {
1744 pr_debug("Failed to split arguments.\n");
1745 return -ENOMEM;
1747 if (argc - 1 > MAX_PROBE_ARGS) {
1748 semantic_error("Too many probe arguments (%d).\n", argc - 1);
1749 ret = -ERANGE;
1750 goto out;
1752 /* Parse probe point */
1753 ret = parse_perf_probe_point(argv[0], pev);
1754 if (ret < 0)
1755 goto out;
1757 /* Generate event name if needed */
1758 if (!pev->event && pev->point.function && pev->point.line
1759 && !pev->point.lazy_line && !pev->point.offset) {
1760 if (asprintf(&pev->event, "%s_L%d", pev->point.function,
1761 pev->point.line) < 0)
1762 return -ENOMEM;
1765 /* Copy arguments and ensure return probe has no C argument */
1766 pev->nargs = argc - 1;
1767 pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1768 if (pev->args == NULL) {
1769 ret = -ENOMEM;
1770 goto out;
1772 for (i = 0; i < pev->nargs && ret >= 0; i++) {
1773 ret = parse_perf_probe_arg(argv[i + 1], &pev->args[i]);
1774 if (ret >= 0 &&
1775 is_c_varname(pev->args[i].var) && pev->point.retprobe) {
1776 semantic_error("You can't specify local variable for"
1777 " kretprobe.\n");
1778 ret = -EINVAL;
1781 out:
1782 argv_free(argv);
1784 return ret;
1787 /* Returns true if *any* ARG is either C variable, $params or $vars. */
1788 bool perf_probe_with_var(struct perf_probe_event *pev)
1790 int i = 0;
1792 for (i = 0; i < pev->nargs; i++)
1793 if (is_c_varname(pev->args[i].var) ||
1794 !strcmp(pev->args[i].var, PROBE_ARG_PARAMS) ||
1795 !strcmp(pev->args[i].var, PROBE_ARG_VARS))
1796 return true;
1797 return false;
1800 /* Return true if this perf_probe_event requires debuginfo */
1801 bool perf_probe_event_need_dwarf(struct perf_probe_event *pev)
1803 if (pev->point.file || pev->point.line || pev->point.lazy_line)
1804 return true;
1806 if (perf_probe_with_var(pev))
1807 return true;
1809 return false;
1812 /* Parse probe_events event into struct probe_point */
1813 int parse_probe_trace_command(const char *cmd, struct probe_trace_event *tev)
1815 struct probe_trace_point *tp = &tev->point;
1816 char pr;
1817 char *p;
1818 char *argv0_str = NULL, *fmt, *fmt1_str, *fmt2_str, *fmt3_str;
1819 int ret, i, argc;
1820 char **argv;
1822 pr_debug("Parsing probe_events: %s\n", cmd);
1823 argv = argv_split(cmd, &argc);
1824 if (!argv) {
1825 pr_debug("Failed to split arguments.\n");
1826 return -ENOMEM;
1828 if (argc < 2) {
1829 semantic_error("Too few probe arguments.\n");
1830 ret = -ERANGE;
1831 goto out;
1834 /* Scan event and group name. */
1835 argv0_str = strdup(argv[0]);
1836 if (argv0_str == NULL) {
1837 ret = -ENOMEM;
1838 goto out;
1840 fmt1_str = strtok_r(argv0_str, ":", &fmt);
1841 fmt2_str = strtok_r(NULL, "/", &fmt);
1842 fmt3_str = strtok_r(NULL, " \t", &fmt);
1843 if (fmt1_str == NULL || fmt2_str == NULL || fmt3_str == NULL) {
1844 semantic_error("Failed to parse event name: %s\n", argv[0]);
1845 ret = -EINVAL;
1846 goto out;
1848 pr = fmt1_str[0];
1849 tev->group = strdup(fmt2_str);
1850 tev->event = strdup(fmt3_str);
1851 if (tev->group == NULL || tev->event == NULL) {
1852 ret = -ENOMEM;
1853 goto out;
1855 pr_debug("Group:%s Event:%s probe:%c\n", tev->group, tev->event, pr);
1857 tp->retprobe = (pr == 'r');
1859 /* Scan module name(if there), function name and offset */
1860 p = strchr(argv[1], ':');
1861 if (p) {
1862 tp->module = strndup(argv[1], p - argv[1]);
1863 if (!tp->module) {
1864 ret = -ENOMEM;
1865 goto out;
1867 tev->uprobes = (tp->module[0] == '/');
1868 p++;
1869 } else
1870 p = argv[1];
1871 fmt1_str = strtok_r(p, "+", &fmt);
1872 /* only the address started with 0x */
1873 if (fmt1_str[0] == '0') {
1875 * Fix a special case:
1876 * if address == 0, kernel reports something like:
1877 * p:probe_libc/abs_0 /lib/libc-2.18.so:0x (null) arg1=%ax
1878 * Newer kernel may fix that, but we want to
1879 * support old kernel also.
1881 if (strcmp(fmt1_str, "0x") == 0) {
1882 if (!argv[2] || strcmp(argv[2], "(null)")) {
1883 ret = -EINVAL;
1884 goto out;
1886 tp->address = 0;
1888 free(argv[2]);
1889 for (i = 2; argv[i + 1] != NULL; i++)
1890 argv[i] = argv[i + 1];
1892 argv[i] = NULL;
1893 argc -= 1;
1894 } else
1895 tp->address = strtoul(fmt1_str, NULL, 0);
1896 } else {
1897 /* Only the symbol-based probe has offset */
1898 tp->symbol = strdup(fmt1_str);
1899 if (tp->symbol == NULL) {
1900 ret = -ENOMEM;
1901 goto out;
1903 fmt2_str = strtok_r(NULL, "", &fmt);
1904 if (fmt2_str == NULL)
1905 tp->offset = 0;
1906 else
1907 tp->offset = strtoul(fmt2_str, NULL, 10);
1910 if (tev->uprobes) {
1911 fmt2_str = strchr(p, '(');
1912 if (fmt2_str)
1913 tp->ref_ctr_offset = strtoul(fmt2_str + 1, NULL, 0);
1916 tev->nargs = argc - 2;
1917 tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
1918 if (tev->args == NULL) {
1919 ret = -ENOMEM;
1920 goto out;
1922 for (i = 0; i < tev->nargs; i++) {
1923 p = strchr(argv[i + 2], '=');
1924 if (p) /* We don't need which register is assigned. */
1925 *p++ = '\0';
1926 else
1927 p = argv[i + 2];
1928 tev->args[i].name = strdup(argv[i + 2]);
1929 /* TODO: parse regs and offset */
1930 tev->args[i].value = strdup(p);
1931 if (tev->args[i].name == NULL || tev->args[i].value == NULL) {
1932 ret = -ENOMEM;
1933 goto out;
1936 ret = 0;
1937 out:
1938 free(argv0_str);
1939 argv_free(argv);
1940 return ret;
1943 /* Compose only probe arg */
1944 char *synthesize_perf_probe_arg(struct perf_probe_arg *pa)
1946 struct perf_probe_arg_field *field = pa->field;
1947 struct strbuf buf;
1948 char *ret = NULL;
1949 int err;
1951 if (strbuf_init(&buf, 64) < 0)
1952 return NULL;
1954 if (pa->name && pa->var)
1955 err = strbuf_addf(&buf, "%s=%s", pa->name, pa->var);
1956 else
1957 err = strbuf_addstr(&buf, pa->name ?: pa->var);
1958 if (err)
1959 goto out;
1961 while (field) {
1962 if (field->name[0] == '[')
1963 err = strbuf_addstr(&buf, field->name);
1964 else
1965 err = strbuf_addf(&buf, "%s%s", field->ref ? "->" : ".",
1966 field->name);
1967 field = field->next;
1968 if (err)
1969 goto out;
1972 if (pa->type)
1973 if (strbuf_addf(&buf, ":%s", pa->type) < 0)
1974 goto out;
1976 ret = strbuf_detach(&buf, NULL);
1977 out:
1978 strbuf_release(&buf);
1979 return ret;
1982 /* Compose only probe point (not argument) */
1983 char *synthesize_perf_probe_point(struct perf_probe_point *pp)
1985 struct strbuf buf;
1986 char *tmp, *ret = NULL;
1987 int len, err = 0;
1989 if (strbuf_init(&buf, 64) < 0)
1990 return NULL;
1992 if (pp->function) {
1993 if (strbuf_addstr(&buf, pp->function) < 0)
1994 goto out;
1995 if (pp->offset)
1996 err = strbuf_addf(&buf, "+%lu", pp->offset);
1997 else if (pp->line)
1998 err = strbuf_addf(&buf, ":%d", pp->line);
1999 else if (pp->retprobe)
2000 err = strbuf_addstr(&buf, "%return");
2001 if (err)
2002 goto out;
2004 if (pp->file) {
2005 tmp = pp->file;
2006 len = strlen(tmp);
2007 if (len > 30) {
2008 tmp = strchr(pp->file + len - 30, '/');
2009 tmp = tmp ? tmp + 1 : pp->file + len - 30;
2011 err = strbuf_addf(&buf, "@%s", tmp);
2012 if (!err && !pp->function && pp->line)
2013 err = strbuf_addf(&buf, ":%d", pp->line);
2015 if (!err)
2016 ret = strbuf_detach(&buf, NULL);
2017 out:
2018 strbuf_release(&buf);
2019 return ret;
2022 char *synthesize_perf_probe_command(struct perf_probe_event *pev)
2024 struct strbuf buf;
2025 char *tmp, *ret = NULL;
2026 int i;
2028 if (strbuf_init(&buf, 64))
2029 return NULL;
2030 if (pev->event)
2031 if (strbuf_addf(&buf, "%s:%s=", pev->group ?: PERFPROBE_GROUP,
2032 pev->event) < 0)
2033 goto out;
2035 tmp = synthesize_perf_probe_point(&pev->point);
2036 if (!tmp || strbuf_addstr(&buf, tmp) < 0)
2037 goto out;
2038 free(tmp);
2040 for (i = 0; i < pev->nargs; i++) {
2041 tmp = synthesize_perf_probe_arg(pev->args + i);
2042 if (!tmp || strbuf_addf(&buf, " %s", tmp) < 0)
2043 goto out;
2044 free(tmp);
2047 ret = strbuf_detach(&buf, NULL);
2048 out:
2049 strbuf_release(&buf);
2050 return ret;
2053 static int __synthesize_probe_trace_arg_ref(struct probe_trace_arg_ref *ref,
2054 struct strbuf *buf, int depth)
2056 int err;
2057 if (ref->next) {
2058 depth = __synthesize_probe_trace_arg_ref(ref->next, buf,
2059 depth + 1);
2060 if (depth < 0)
2061 return depth;
2063 if (ref->user_access)
2064 err = strbuf_addf(buf, "%s%ld(", "+u", ref->offset);
2065 else
2066 err = strbuf_addf(buf, "%+ld(", ref->offset);
2067 return (err < 0) ? err : depth;
2070 static int synthesize_probe_trace_arg(struct probe_trace_arg *arg,
2071 struct strbuf *buf)
2073 struct probe_trace_arg_ref *ref = arg->ref;
2074 int depth = 0, err;
2076 /* Argument name or separator */
2077 if (arg->name)
2078 err = strbuf_addf(buf, " %s=", arg->name);
2079 else
2080 err = strbuf_addch(buf, ' ');
2081 if (err)
2082 return err;
2084 /* Special case: @XXX */
2085 if (arg->value[0] == '@' && arg->ref)
2086 ref = ref->next;
2088 /* Dereferencing arguments */
2089 if (ref) {
2090 depth = __synthesize_probe_trace_arg_ref(ref, buf, 1);
2091 if (depth < 0)
2092 return depth;
2095 /* Print argument value */
2096 if (arg->value[0] == '@' && arg->ref)
2097 err = strbuf_addf(buf, "%s%+ld", arg->value, arg->ref->offset);
2098 else
2099 err = strbuf_addstr(buf, arg->value);
2101 /* Closing */
2102 while (!err && depth--)
2103 err = strbuf_addch(buf, ')');
2105 /* Print argument type */
2106 if (!err && arg->type)
2107 err = strbuf_addf(buf, ":%s", arg->type);
2109 return err;
2112 static int
2113 synthesize_uprobe_trace_def(struct probe_trace_event *tev, struct strbuf *buf)
2115 struct probe_trace_point *tp = &tev->point;
2116 int err;
2118 err = strbuf_addf(buf, "%s:0x%lx", tp->module, tp->address);
2120 if (err >= 0 && tp->ref_ctr_offset) {
2121 if (!uprobe_ref_ctr_is_supported())
2122 return -1;
2123 err = strbuf_addf(buf, "(0x%lx)", tp->ref_ctr_offset);
2125 return err >= 0 ? 0 : -1;
2128 char *synthesize_probe_trace_command(struct probe_trace_event *tev)
2130 struct probe_trace_point *tp = &tev->point;
2131 struct strbuf buf;
2132 char *ret = NULL;
2133 int i, err;
2135 /* Uprobes must have tp->module */
2136 if (tev->uprobes && !tp->module)
2137 return NULL;
2139 if (strbuf_init(&buf, 32) < 0)
2140 return NULL;
2142 if (strbuf_addf(&buf, "%c:%s/%s ", tp->retprobe ? 'r' : 'p',
2143 tev->group, tev->event) < 0)
2144 goto error;
2146 * If tp->address == 0, then this point must be a
2147 * absolute address uprobe.
2148 * try_to_find_absolute_address() should have made
2149 * tp->symbol to "0x0".
2151 if (tev->uprobes && !tp->address) {
2152 if (!tp->symbol || strcmp(tp->symbol, "0x0"))
2153 goto error;
2156 /* Use the tp->address for uprobes */
2157 if (tev->uprobes) {
2158 err = synthesize_uprobe_trace_def(tev, &buf);
2159 } else if (!strncmp(tp->symbol, "0x", 2)) {
2160 /* Absolute address. See try_to_find_absolute_address() */
2161 err = strbuf_addf(&buf, "%s%s0x%lx", tp->module ?: "",
2162 tp->module ? ":" : "", tp->address);
2163 } else {
2164 err = strbuf_addf(&buf, "%s%s%s+%lu", tp->module ?: "",
2165 tp->module ? ":" : "", tp->symbol, tp->offset);
2168 if (err)
2169 goto error;
2171 for (i = 0; i < tev->nargs; i++)
2172 if (synthesize_probe_trace_arg(&tev->args[i], &buf) < 0)
2173 goto error;
2175 ret = strbuf_detach(&buf, NULL);
2176 error:
2177 strbuf_release(&buf);
2178 return ret;
2181 static int find_perf_probe_point_from_map(struct probe_trace_point *tp,
2182 struct perf_probe_point *pp,
2183 bool is_kprobe)
2185 struct symbol *sym = NULL;
2186 struct map *map = NULL;
2187 u64 addr = tp->address;
2188 int ret = -ENOENT;
2190 if (!is_kprobe) {
2191 map = dso__new_map(tp->module);
2192 if (!map)
2193 goto out;
2194 sym = map__find_symbol(map, addr);
2195 } else {
2196 if (tp->symbol && !addr) {
2197 if (kernel_get_symbol_address_by_name(tp->symbol,
2198 &addr, true, false) < 0)
2199 goto out;
2201 if (addr) {
2202 addr += tp->offset;
2203 sym = machine__find_kernel_symbol(host_machine, addr, &map);
2207 if (!sym)
2208 goto out;
2210 pp->retprobe = tp->retprobe;
2211 pp->offset = addr - map->unmap_ip(map, sym->start);
2212 pp->function = strdup(sym->name);
2213 ret = pp->function ? 0 : -ENOMEM;
2215 out:
2216 if (map && !is_kprobe) {
2217 map__put(map);
2220 return ret;
2223 static int convert_to_perf_probe_point(struct probe_trace_point *tp,
2224 struct perf_probe_point *pp,
2225 bool is_kprobe)
2227 char buf[128];
2228 int ret;
2230 ret = find_perf_probe_point_from_dwarf(tp, pp, is_kprobe);
2231 if (!ret)
2232 return 0;
2233 ret = find_perf_probe_point_from_map(tp, pp, is_kprobe);
2234 if (!ret)
2235 return 0;
2237 pr_debug("Failed to find probe point from both of dwarf and map.\n");
2239 if (tp->symbol) {
2240 pp->function = strdup(tp->symbol);
2241 pp->offset = tp->offset;
2242 } else {
2243 ret = e_snprintf(buf, 128, "0x%" PRIx64, (u64)tp->address);
2244 if (ret < 0)
2245 return ret;
2246 pp->function = strdup(buf);
2247 pp->offset = 0;
2249 if (pp->function == NULL)
2250 return -ENOMEM;
2252 pp->retprobe = tp->retprobe;
2254 return 0;
2257 static int convert_to_perf_probe_event(struct probe_trace_event *tev,
2258 struct perf_probe_event *pev, bool is_kprobe)
2260 struct strbuf buf = STRBUF_INIT;
2261 int i, ret;
2263 /* Convert event/group name */
2264 pev->event = strdup(tev->event);
2265 pev->group = strdup(tev->group);
2266 if (pev->event == NULL || pev->group == NULL)
2267 return -ENOMEM;
2269 /* Convert trace_point to probe_point */
2270 ret = convert_to_perf_probe_point(&tev->point, &pev->point, is_kprobe);
2271 if (ret < 0)
2272 return ret;
2274 /* Convert trace_arg to probe_arg */
2275 pev->nargs = tev->nargs;
2276 pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
2277 if (pev->args == NULL)
2278 return -ENOMEM;
2279 for (i = 0; i < tev->nargs && ret >= 0; i++) {
2280 if (tev->args[i].name)
2281 pev->args[i].name = strdup(tev->args[i].name);
2282 else {
2283 if ((ret = strbuf_init(&buf, 32)) < 0)
2284 goto error;
2285 ret = synthesize_probe_trace_arg(&tev->args[i], &buf);
2286 pev->args[i].name = strbuf_detach(&buf, NULL);
2288 if (pev->args[i].name == NULL && ret >= 0)
2289 ret = -ENOMEM;
2291 error:
2292 if (ret < 0)
2293 clear_perf_probe_event(pev);
2295 return ret;
2298 void clear_perf_probe_event(struct perf_probe_event *pev)
2300 struct perf_probe_arg_field *field, *next;
2301 int i;
2303 zfree(&pev->event);
2304 zfree(&pev->group);
2305 zfree(&pev->target);
2306 clear_perf_probe_point(&pev->point);
2308 for (i = 0; i < pev->nargs; i++) {
2309 zfree(&pev->args[i].name);
2310 zfree(&pev->args[i].var);
2311 zfree(&pev->args[i].type);
2312 field = pev->args[i].field;
2313 while (field) {
2314 next = field->next;
2315 zfree(&field->name);
2316 free(field);
2317 field = next;
2320 pev->nargs = 0;
2321 zfree(&pev->args);
2324 #define strdup_or_goto(str, label) \
2325 ({ char *__p = NULL; if (str && !(__p = strdup(str))) goto label; __p; })
2327 static int perf_probe_point__copy(struct perf_probe_point *dst,
2328 struct perf_probe_point *src)
2330 dst->file = strdup_or_goto(src->file, out_err);
2331 dst->function = strdup_or_goto(src->function, out_err);
2332 dst->lazy_line = strdup_or_goto(src->lazy_line, out_err);
2333 dst->line = src->line;
2334 dst->retprobe = src->retprobe;
2335 dst->offset = src->offset;
2336 return 0;
2338 out_err:
2339 clear_perf_probe_point(dst);
2340 return -ENOMEM;
2343 static int perf_probe_arg__copy(struct perf_probe_arg *dst,
2344 struct perf_probe_arg *src)
2346 struct perf_probe_arg_field *field, **ppfield;
2348 dst->name = strdup_or_goto(src->name, out_err);
2349 dst->var = strdup_or_goto(src->var, out_err);
2350 dst->type = strdup_or_goto(src->type, out_err);
2352 field = src->field;
2353 ppfield = &(dst->field);
2354 while (field) {
2355 *ppfield = zalloc(sizeof(*field));
2356 if (!*ppfield)
2357 goto out_err;
2358 (*ppfield)->name = strdup_or_goto(field->name, out_err);
2359 (*ppfield)->index = field->index;
2360 (*ppfield)->ref = field->ref;
2361 field = field->next;
2362 ppfield = &((*ppfield)->next);
2364 return 0;
2365 out_err:
2366 return -ENOMEM;
2369 int perf_probe_event__copy(struct perf_probe_event *dst,
2370 struct perf_probe_event *src)
2372 int i;
2374 dst->event = strdup_or_goto(src->event, out_err);
2375 dst->group = strdup_or_goto(src->group, out_err);
2376 dst->target = strdup_or_goto(src->target, out_err);
2377 dst->uprobes = src->uprobes;
2379 if (perf_probe_point__copy(&dst->point, &src->point) < 0)
2380 goto out_err;
2382 dst->args = zalloc(sizeof(struct perf_probe_arg) * src->nargs);
2383 if (!dst->args)
2384 goto out_err;
2385 dst->nargs = src->nargs;
2387 for (i = 0; i < src->nargs; i++)
2388 if (perf_probe_arg__copy(&dst->args[i], &src->args[i]) < 0)
2389 goto out_err;
2390 return 0;
2392 out_err:
2393 clear_perf_probe_event(dst);
2394 return -ENOMEM;
2397 void clear_probe_trace_event(struct probe_trace_event *tev)
2399 struct probe_trace_arg_ref *ref, *next;
2400 int i;
2402 zfree(&tev->event);
2403 zfree(&tev->group);
2404 zfree(&tev->point.symbol);
2405 zfree(&tev->point.realname);
2406 zfree(&tev->point.module);
2407 for (i = 0; i < tev->nargs; i++) {
2408 zfree(&tev->args[i].name);
2409 zfree(&tev->args[i].value);
2410 zfree(&tev->args[i].type);
2411 ref = tev->args[i].ref;
2412 while (ref) {
2413 next = ref->next;
2414 free(ref);
2415 ref = next;
2418 zfree(&tev->args);
2419 tev->nargs = 0;
2422 struct kprobe_blacklist_node {
2423 struct list_head list;
2424 unsigned long start;
2425 unsigned long end;
2426 char *symbol;
2429 static void kprobe_blacklist__delete(struct list_head *blacklist)
2431 struct kprobe_blacklist_node *node;
2433 while (!list_empty(blacklist)) {
2434 node = list_first_entry(blacklist,
2435 struct kprobe_blacklist_node, list);
2436 list_del_init(&node->list);
2437 zfree(&node->symbol);
2438 free(node);
2442 static int kprobe_blacklist__load(struct list_head *blacklist)
2444 struct kprobe_blacklist_node *node;
2445 const char *__debugfs = debugfs__mountpoint();
2446 char buf[PATH_MAX], *p;
2447 FILE *fp;
2448 int ret;
2450 if (__debugfs == NULL)
2451 return -ENOTSUP;
2453 ret = e_snprintf(buf, PATH_MAX, "%s/kprobes/blacklist", __debugfs);
2454 if (ret < 0)
2455 return ret;
2457 fp = fopen(buf, "r");
2458 if (!fp)
2459 return -errno;
2461 ret = 0;
2462 while (fgets(buf, PATH_MAX, fp)) {
2463 node = zalloc(sizeof(*node));
2464 if (!node) {
2465 ret = -ENOMEM;
2466 break;
2468 INIT_LIST_HEAD(&node->list);
2469 list_add_tail(&node->list, blacklist);
2470 if (sscanf(buf, "0x%lx-0x%lx", &node->start, &node->end) != 2) {
2471 ret = -EINVAL;
2472 break;
2474 p = strchr(buf, '\t');
2475 if (p) {
2476 p++;
2477 if (p[strlen(p) - 1] == '\n')
2478 p[strlen(p) - 1] = '\0';
2479 } else
2480 p = (char *)"unknown";
2481 node->symbol = strdup(p);
2482 if (!node->symbol) {
2483 ret = -ENOMEM;
2484 break;
2486 pr_debug2("Blacklist: 0x%lx-0x%lx, %s\n",
2487 node->start, node->end, node->symbol);
2488 ret++;
2490 if (ret < 0)
2491 kprobe_blacklist__delete(blacklist);
2492 fclose(fp);
2494 return ret;
2497 static struct kprobe_blacklist_node *
2498 kprobe_blacklist__find_by_address(struct list_head *blacklist,
2499 unsigned long address)
2501 struct kprobe_blacklist_node *node;
2503 list_for_each_entry(node, blacklist, list) {
2504 if (node->start <= address && address < node->end)
2505 return node;
2508 return NULL;
2511 static LIST_HEAD(kprobe_blacklist);
2513 static void kprobe_blacklist__init(void)
2515 if (!list_empty(&kprobe_blacklist))
2516 return;
2518 if (kprobe_blacklist__load(&kprobe_blacklist) < 0)
2519 pr_debug("No kprobe blacklist support, ignored\n");
2522 static void kprobe_blacklist__release(void)
2524 kprobe_blacklist__delete(&kprobe_blacklist);
2527 static bool kprobe_blacklist__listed(unsigned long address)
2529 return !!kprobe_blacklist__find_by_address(&kprobe_blacklist, address);
2532 static int perf_probe_event__sprintf(const char *group, const char *event,
2533 struct perf_probe_event *pev,
2534 const char *module,
2535 struct strbuf *result)
2537 int i, ret;
2538 char *buf;
2540 if (asprintf(&buf, "%s:%s", group, event) < 0)
2541 return -errno;
2542 ret = strbuf_addf(result, " %-20s (on ", buf);
2543 free(buf);
2544 if (ret)
2545 return ret;
2547 /* Synthesize only event probe point */
2548 buf = synthesize_perf_probe_point(&pev->point);
2549 if (!buf)
2550 return -ENOMEM;
2551 ret = strbuf_addstr(result, buf);
2552 free(buf);
2554 if (!ret && module)
2555 ret = strbuf_addf(result, " in %s", module);
2557 if (!ret && pev->nargs > 0) {
2558 ret = strbuf_add(result, " with", 5);
2559 for (i = 0; !ret && i < pev->nargs; i++) {
2560 buf = synthesize_perf_probe_arg(&pev->args[i]);
2561 if (!buf)
2562 return -ENOMEM;
2563 ret = strbuf_addf(result, " %s", buf);
2564 free(buf);
2567 if (!ret)
2568 ret = strbuf_addch(result, ')');
2570 return ret;
2573 /* Show an event */
2574 int show_perf_probe_event(const char *group, const char *event,
2575 struct perf_probe_event *pev,
2576 const char *module, bool use_stdout)
2578 struct strbuf buf = STRBUF_INIT;
2579 int ret;
2581 ret = perf_probe_event__sprintf(group, event, pev, module, &buf);
2582 if (ret >= 0) {
2583 if (use_stdout)
2584 printf("%s\n", buf.buf);
2585 else
2586 pr_info("%s\n", buf.buf);
2588 strbuf_release(&buf);
2590 return ret;
2593 static bool filter_probe_trace_event(struct probe_trace_event *tev,
2594 struct strfilter *filter)
2596 char tmp[128];
2598 /* At first, check the event name itself */
2599 if (strfilter__compare(filter, tev->event))
2600 return true;
2602 /* Next, check the combination of name and group */
2603 if (e_snprintf(tmp, 128, "%s:%s", tev->group, tev->event) < 0)
2604 return false;
2605 return strfilter__compare(filter, tmp);
2608 static int __show_perf_probe_events(int fd, bool is_kprobe,
2609 struct strfilter *filter)
2611 int ret = 0;
2612 struct probe_trace_event tev;
2613 struct perf_probe_event pev;
2614 struct strlist *rawlist;
2615 struct str_node *ent;
2617 memset(&tev, 0, sizeof(tev));
2618 memset(&pev, 0, sizeof(pev));
2620 rawlist = probe_file__get_rawlist(fd);
2621 if (!rawlist)
2622 return -ENOMEM;
2624 strlist__for_each_entry(ent, rawlist) {
2625 ret = parse_probe_trace_command(ent->s, &tev);
2626 if (ret >= 0) {
2627 if (!filter_probe_trace_event(&tev, filter))
2628 goto next;
2629 ret = convert_to_perf_probe_event(&tev, &pev,
2630 is_kprobe);
2631 if (ret < 0)
2632 goto next;
2633 ret = show_perf_probe_event(pev.group, pev.event,
2634 &pev, tev.point.module,
2635 true);
2637 next:
2638 clear_perf_probe_event(&pev);
2639 clear_probe_trace_event(&tev);
2640 if (ret < 0)
2641 break;
2643 strlist__delete(rawlist);
2644 /* Cleanup cached debuginfo if needed */
2645 debuginfo_cache__exit();
2647 return ret;
2650 /* List up current perf-probe events */
2651 int show_perf_probe_events(struct strfilter *filter)
2653 int kp_fd, up_fd, ret;
2655 setup_pager();
2657 if (probe_conf.cache)
2658 return probe_cache__show_all_caches(filter);
2660 ret = init_probe_symbol_maps(false);
2661 if (ret < 0)
2662 return ret;
2664 ret = probe_file__open_both(&kp_fd, &up_fd, 0);
2665 if (ret < 0)
2666 return ret;
2668 if (kp_fd >= 0)
2669 ret = __show_perf_probe_events(kp_fd, true, filter);
2670 if (up_fd >= 0 && ret >= 0)
2671 ret = __show_perf_probe_events(up_fd, false, filter);
2672 if (kp_fd > 0)
2673 close(kp_fd);
2674 if (up_fd > 0)
2675 close(up_fd);
2676 exit_probe_symbol_maps();
2678 return ret;
2681 static int get_new_event_name(char *buf, size_t len, const char *base,
2682 struct strlist *namelist, bool ret_event,
2683 bool allow_suffix)
2685 int i, ret;
2686 char *p, *nbase;
2688 if (*base == '.')
2689 base++;
2690 nbase = strdup(base);
2691 if (!nbase)
2692 return -ENOMEM;
2694 /* Cut off the dot suffixes (e.g. .const, .isra) and version suffixes */
2695 p = strpbrk(nbase, ".@");
2696 if (p && p != nbase)
2697 *p = '\0';
2699 /* Try no suffix number */
2700 ret = e_snprintf(buf, len, "%s%s", nbase, ret_event ? "__return" : "");
2701 if (ret < 0) {
2702 pr_debug("snprintf() failed: %d\n", ret);
2703 goto out;
2705 if (!strlist__has_entry(namelist, buf))
2706 goto out;
2708 if (!allow_suffix) {
2709 pr_warning("Error: event \"%s\" already exists.\n"
2710 " Hint: Remove existing event by 'perf probe -d'\n"
2711 " or force duplicates by 'perf probe -f'\n"
2712 " or set 'force=yes' in BPF source.\n",
2713 buf);
2714 ret = -EEXIST;
2715 goto out;
2718 /* Try to add suffix */
2719 for (i = 1; i < MAX_EVENT_INDEX; i++) {
2720 ret = e_snprintf(buf, len, "%s_%d", nbase, i);
2721 if (ret < 0) {
2722 pr_debug("snprintf() failed: %d\n", ret);
2723 goto out;
2725 if (!strlist__has_entry(namelist, buf))
2726 break;
2728 if (i == MAX_EVENT_INDEX) {
2729 pr_warning("Too many events are on the same function.\n");
2730 ret = -ERANGE;
2733 out:
2734 free(nbase);
2736 /* Final validation */
2737 if (ret >= 0 && !is_c_func_name(buf)) {
2738 pr_warning("Internal error: \"%s\" is an invalid event name.\n",
2739 buf);
2740 ret = -EINVAL;
2743 return ret;
2746 /* Warn if the current kernel's uprobe implementation is old */
2747 static void warn_uprobe_event_compat(struct probe_trace_event *tev)
2749 int i;
2750 char *buf = synthesize_probe_trace_command(tev);
2751 struct probe_trace_point *tp = &tev->point;
2753 if (tp->ref_ctr_offset && !uprobe_ref_ctr_is_supported()) {
2754 pr_warning("A semaphore is associated with %s:%s and "
2755 "seems your kernel doesn't support it.\n",
2756 tev->group, tev->event);
2759 /* Old uprobe event doesn't support memory dereference */
2760 if (!tev->uprobes || tev->nargs == 0 || !buf)
2761 goto out;
2763 for (i = 0; i < tev->nargs; i++)
2764 if (strglobmatch(tev->args[i].value, "[$@+-]*")) {
2765 pr_warning("Please upgrade your kernel to at least "
2766 "3.14 to have access to feature %s\n",
2767 tev->args[i].value);
2768 break;
2770 out:
2771 free(buf);
2774 /* Set new name from original perf_probe_event and namelist */
2775 static int probe_trace_event__set_name(struct probe_trace_event *tev,
2776 struct perf_probe_event *pev,
2777 struct strlist *namelist,
2778 bool allow_suffix)
2780 const char *event, *group;
2781 char buf[64];
2782 int ret;
2784 /* If probe_event or trace_event already have the name, reuse it */
2785 if (pev->event && !pev->sdt)
2786 event = pev->event;
2787 else if (tev->event)
2788 event = tev->event;
2789 else {
2790 /* Or generate new one from probe point */
2791 if (pev->point.function &&
2792 (strncmp(pev->point.function, "0x", 2) != 0) &&
2793 !strisglob(pev->point.function))
2794 event = pev->point.function;
2795 else
2796 event = tev->point.realname;
2798 if (pev->group && !pev->sdt)
2799 group = pev->group;
2800 else if (tev->group)
2801 group = tev->group;
2802 else
2803 group = PERFPROBE_GROUP;
2805 /* Get an unused new event name */
2806 ret = get_new_event_name(buf, 64, event, namelist,
2807 tev->point.retprobe, allow_suffix);
2808 if (ret < 0)
2809 return ret;
2811 event = buf;
2813 tev->event = strdup(event);
2814 tev->group = strdup(group);
2815 if (tev->event == NULL || tev->group == NULL)
2816 return -ENOMEM;
2819 * Add new event name to namelist if multiprobe event is NOT
2820 * supported, since we have to use new event name for following
2821 * probes in that case.
2823 if (!multiprobe_event_is_supported())
2824 strlist__add(namelist, event);
2825 return 0;
2828 static int __open_probe_file_and_namelist(bool uprobe,
2829 struct strlist **namelist)
2831 int fd;
2833 fd = probe_file__open(PF_FL_RW | (uprobe ? PF_FL_UPROBE : 0));
2834 if (fd < 0)
2835 return fd;
2837 /* Get current event names */
2838 *namelist = probe_file__get_namelist(fd);
2839 if (!(*namelist)) {
2840 pr_debug("Failed to get current event list.\n");
2841 close(fd);
2842 return -ENOMEM;
2844 return fd;
2847 static int __add_probe_trace_events(struct perf_probe_event *pev,
2848 struct probe_trace_event *tevs,
2849 int ntevs, bool allow_suffix)
2851 int i, fd[2] = {-1, -1}, up, ret;
2852 struct probe_trace_event *tev = NULL;
2853 struct probe_cache *cache = NULL;
2854 struct strlist *namelist[2] = {NULL, NULL};
2855 struct nscookie nsc;
2857 up = pev->uprobes ? 1 : 0;
2858 fd[up] = __open_probe_file_and_namelist(up, &namelist[up]);
2859 if (fd[up] < 0)
2860 return fd[up];
2862 ret = 0;
2863 for (i = 0; i < ntevs; i++) {
2864 tev = &tevs[i];
2865 up = tev->uprobes ? 1 : 0;
2866 if (fd[up] == -1) { /* Open the kprobe/uprobe_events */
2867 fd[up] = __open_probe_file_and_namelist(up,
2868 &namelist[up]);
2869 if (fd[up] < 0)
2870 goto close_out;
2872 /* Skip if the symbol is out of .text or blacklisted */
2873 if (!tev->point.symbol && !pev->uprobes)
2874 continue;
2876 /* Set new name for tev (and update namelist) */
2877 ret = probe_trace_event__set_name(tev, pev, namelist[up],
2878 allow_suffix);
2879 if (ret < 0)
2880 break;
2882 nsinfo__mountns_enter(pev->nsi, &nsc);
2883 ret = probe_file__add_event(fd[up], tev);
2884 nsinfo__mountns_exit(&nsc);
2885 if (ret < 0)
2886 break;
2889 * Probes after the first probe which comes from same
2890 * user input are always allowed to add suffix, because
2891 * there might be several addresses corresponding to
2892 * one code line.
2894 allow_suffix = true;
2896 if (ret == -EINVAL && pev->uprobes)
2897 warn_uprobe_event_compat(tev);
2898 if (ret == 0 && probe_conf.cache) {
2899 cache = probe_cache__new(pev->target, pev->nsi);
2900 if (!cache ||
2901 probe_cache__add_entry(cache, pev, tevs, ntevs) < 0 ||
2902 probe_cache__commit(cache) < 0)
2903 pr_warning("Failed to add event to probe cache\n");
2904 probe_cache__delete(cache);
2907 close_out:
2908 for (up = 0; up < 2; up++) {
2909 strlist__delete(namelist[up]);
2910 if (fd[up] >= 0)
2911 close(fd[up]);
2913 return ret;
2916 static int find_probe_functions(struct map *map, char *name,
2917 struct symbol **syms)
2919 int found = 0;
2920 struct symbol *sym;
2921 struct rb_node *tmp;
2922 const char *norm, *ver;
2923 char *buf = NULL;
2924 bool cut_version = true;
2926 if (map__load(map) < 0)
2927 return 0;
2929 /* If user gives a version, don't cut off the version from symbols */
2930 if (strchr(name, '@'))
2931 cut_version = false;
2933 map__for_each_symbol(map, sym, tmp) {
2934 norm = arch__normalize_symbol_name(sym->name);
2935 if (!norm)
2936 continue;
2938 if (cut_version) {
2939 /* We don't care about default symbol or not */
2940 ver = strchr(norm, '@');
2941 if (ver) {
2942 buf = strndup(norm, ver - norm);
2943 if (!buf)
2944 return -ENOMEM;
2945 norm = buf;
2949 if (strglobmatch(norm, name)) {
2950 found++;
2951 if (syms && found < probe_conf.max_probes)
2952 syms[found - 1] = sym;
2954 if (buf)
2955 zfree(&buf);
2958 return found;
2961 void __weak arch__fix_tev_from_maps(struct perf_probe_event *pev __maybe_unused,
2962 struct probe_trace_event *tev __maybe_unused,
2963 struct map *map __maybe_unused,
2964 struct symbol *sym __maybe_unused) { }
2967 * Find probe function addresses from map.
2968 * Return an error or the number of found probe_trace_event
2970 static int find_probe_trace_events_from_map(struct perf_probe_event *pev,
2971 struct probe_trace_event **tevs)
2973 struct map *map = NULL;
2974 struct ref_reloc_sym *reloc_sym = NULL;
2975 struct symbol *sym;
2976 struct symbol **syms = NULL;
2977 struct probe_trace_event *tev;
2978 struct perf_probe_point *pp = &pev->point;
2979 struct probe_trace_point *tp;
2980 int num_matched_functions;
2981 int ret, i, j, skipped = 0;
2982 char *mod_name;
2984 map = get_target_map(pev->target, pev->nsi, pev->uprobes);
2985 if (!map) {
2986 ret = -EINVAL;
2987 goto out;
2990 syms = malloc(sizeof(struct symbol *) * probe_conf.max_probes);
2991 if (!syms) {
2992 ret = -ENOMEM;
2993 goto out;
2997 * Load matched symbols: Since the different local symbols may have
2998 * same name but different addresses, this lists all the symbols.
3000 num_matched_functions = find_probe_functions(map, pp->function, syms);
3001 if (num_matched_functions <= 0) {
3002 pr_err("Failed to find symbol %s in %s\n", pp->function,
3003 pev->target ? : "kernel");
3004 ret = -ENOENT;
3005 goto out;
3006 } else if (num_matched_functions > probe_conf.max_probes) {
3007 pr_err("Too many functions matched in %s\n",
3008 pev->target ? : "kernel");
3009 ret = -E2BIG;
3010 goto out;
3013 /* Note that the symbols in the kmodule are not relocated */
3014 if (!pev->uprobes && !pev->target &&
3015 (!pp->retprobe || kretprobe_offset_is_supported())) {
3016 reloc_sym = kernel_get_ref_reloc_sym(NULL);
3017 if (!reloc_sym) {
3018 pr_warning("Relocated base symbol is not found!\n");
3019 ret = -EINVAL;
3020 goto out;
3024 /* Setup result trace-probe-events */
3025 *tevs = zalloc(sizeof(*tev) * num_matched_functions);
3026 if (!*tevs) {
3027 ret = -ENOMEM;
3028 goto out;
3031 ret = 0;
3033 for (j = 0; j < num_matched_functions; j++) {
3034 sym = syms[j];
3036 /* There can be duplicated symbols in the map */
3037 for (i = 0; i < j; i++)
3038 if (sym->start == syms[i]->start) {
3039 pr_debug("Found duplicated symbol %s @ %" PRIx64 "\n",
3040 sym->name, sym->start);
3041 break;
3043 if (i != j)
3044 continue;
3046 tev = (*tevs) + ret;
3047 tp = &tev->point;
3048 if (ret == num_matched_functions) {
3049 pr_warning("Too many symbols are listed. Skip it.\n");
3050 break;
3052 ret++;
3054 if (pp->offset > sym->end - sym->start) {
3055 pr_warning("Offset %ld is bigger than the size of %s\n",
3056 pp->offset, sym->name);
3057 ret = -ENOENT;
3058 goto err_out;
3060 /* Add one probe point */
3061 tp->address = map->unmap_ip(map, sym->start) + pp->offset;
3063 /* Check the kprobe (not in module) is within .text */
3064 if (!pev->uprobes && !pev->target &&
3065 kprobe_warn_out_range(sym->name, tp->address)) {
3066 tp->symbol = NULL; /* Skip it */
3067 skipped++;
3068 } else if (reloc_sym) {
3069 tp->symbol = strdup_or_goto(reloc_sym->name, nomem_out);
3070 tp->offset = tp->address - reloc_sym->addr;
3071 } else {
3072 tp->symbol = strdup_or_goto(sym->name, nomem_out);
3073 tp->offset = pp->offset;
3075 tp->realname = strdup_or_goto(sym->name, nomem_out);
3077 tp->retprobe = pp->retprobe;
3078 if (pev->target) {
3079 if (pev->uprobes) {
3080 tev->point.module = strdup_or_goto(pev->target,
3081 nomem_out);
3082 } else {
3083 mod_name = find_module_name(pev->target);
3084 tev->point.module =
3085 strdup(mod_name ? mod_name : pev->target);
3086 free(mod_name);
3087 if (!tev->point.module)
3088 goto nomem_out;
3091 tev->uprobes = pev->uprobes;
3092 tev->nargs = pev->nargs;
3093 if (tev->nargs) {
3094 tev->args = zalloc(sizeof(struct probe_trace_arg) *
3095 tev->nargs);
3096 if (tev->args == NULL)
3097 goto nomem_out;
3099 for (i = 0; i < tev->nargs; i++) {
3100 if (pev->args[i].name)
3101 tev->args[i].name =
3102 strdup_or_goto(pev->args[i].name,
3103 nomem_out);
3105 tev->args[i].value = strdup_or_goto(pev->args[i].var,
3106 nomem_out);
3107 if (pev->args[i].type)
3108 tev->args[i].type =
3109 strdup_or_goto(pev->args[i].type,
3110 nomem_out);
3112 arch__fix_tev_from_maps(pev, tev, map, sym);
3114 if (ret == skipped) {
3115 ret = -ENOENT;
3116 goto err_out;
3119 out:
3120 map__put(map);
3121 free(syms);
3122 return ret;
3124 nomem_out:
3125 ret = -ENOMEM;
3126 err_out:
3127 clear_probe_trace_events(*tevs, num_matched_functions);
3128 zfree(tevs);
3129 goto out;
3132 static int try_to_find_absolute_address(struct perf_probe_event *pev,
3133 struct probe_trace_event **tevs)
3135 struct perf_probe_point *pp = &pev->point;
3136 struct probe_trace_event *tev;
3137 struct probe_trace_point *tp;
3138 int i, err;
3140 if (!(pev->point.function && !strncmp(pev->point.function, "0x", 2)))
3141 return -EINVAL;
3142 if (perf_probe_event_need_dwarf(pev))
3143 return -EINVAL;
3146 * This is 'perf probe /lib/libc.so 0xabcd'. Try to probe at
3147 * absolute address.
3149 * Only one tev can be generated by this.
3151 *tevs = zalloc(sizeof(*tev));
3152 if (!*tevs)
3153 return -ENOMEM;
3155 tev = *tevs;
3156 tp = &tev->point;
3159 * Don't use tp->offset, use address directly, because
3160 * in synthesize_probe_trace_command() address cannot be
3161 * zero.
3163 tp->address = pev->point.abs_address;
3164 tp->retprobe = pp->retprobe;
3165 tev->uprobes = pev->uprobes;
3167 err = -ENOMEM;
3169 * Give it a '0x' leading symbol name.
3170 * In __add_probe_trace_events, a NULL symbol is interpreted as
3171 * invalid.
3173 if (asprintf(&tp->symbol, "0x%lx", tp->address) < 0)
3174 goto errout;
3176 /* For kprobe, check range */
3177 if ((!tev->uprobes) &&
3178 (kprobe_warn_out_range(tev->point.symbol,
3179 tev->point.address))) {
3180 err = -EACCES;
3181 goto errout;
3184 if (asprintf(&tp->realname, "abs_%lx", tp->address) < 0)
3185 goto errout;
3187 if (pev->target) {
3188 tp->module = strdup(pev->target);
3189 if (!tp->module)
3190 goto errout;
3193 if (tev->group) {
3194 tev->group = strdup(pev->group);
3195 if (!tev->group)
3196 goto errout;
3199 if (pev->event) {
3200 tev->event = strdup(pev->event);
3201 if (!tev->event)
3202 goto errout;
3205 tev->nargs = pev->nargs;
3206 tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
3207 if (!tev->args)
3208 goto errout;
3210 for (i = 0; i < tev->nargs; i++)
3211 copy_to_probe_trace_arg(&tev->args[i], &pev->args[i]);
3213 return 1;
3215 errout:
3216 clear_probe_trace_events(*tevs, 1);
3217 *tevs = NULL;
3218 return err;
3221 /* Concatinate two arrays */
3222 static void *memcat(void *a, size_t sz_a, void *b, size_t sz_b)
3224 void *ret;
3226 ret = malloc(sz_a + sz_b);
3227 if (ret) {
3228 memcpy(ret, a, sz_a);
3229 memcpy(ret + sz_a, b, sz_b);
3231 return ret;
3234 static int
3235 concat_probe_trace_events(struct probe_trace_event **tevs, int *ntevs,
3236 struct probe_trace_event **tevs2, int ntevs2)
3238 struct probe_trace_event *new_tevs;
3239 int ret = 0;
3241 if (*ntevs == 0) {
3242 *tevs = *tevs2;
3243 *ntevs = ntevs2;
3244 *tevs2 = NULL;
3245 return 0;
3248 if (*ntevs + ntevs2 > probe_conf.max_probes)
3249 ret = -E2BIG;
3250 else {
3251 /* Concatinate the array of probe_trace_event */
3252 new_tevs = memcat(*tevs, (*ntevs) * sizeof(**tevs),
3253 *tevs2, ntevs2 * sizeof(**tevs2));
3254 if (!new_tevs)
3255 ret = -ENOMEM;
3256 else {
3257 free(*tevs);
3258 *tevs = new_tevs;
3259 *ntevs += ntevs2;
3262 if (ret < 0)
3263 clear_probe_trace_events(*tevs2, ntevs2);
3264 zfree(tevs2);
3266 return ret;
3270 * Try to find probe_trace_event from given probe caches. Return the number
3271 * of cached events found, if an error occurs return the error.
3273 static int find_cached_events(struct perf_probe_event *pev,
3274 struct probe_trace_event **tevs,
3275 const char *target)
3277 struct probe_cache *cache;
3278 struct probe_cache_entry *entry;
3279 struct probe_trace_event *tmp_tevs = NULL;
3280 int ntevs = 0;
3281 int ret = 0;
3283 cache = probe_cache__new(target, pev->nsi);
3284 /* Return 0 ("not found") if the target has no probe cache. */
3285 if (!cache)
3286 return 0;
3288 for_each_probe_cache_entry(entry, cache) {
3289 /* Skip the cache entry which has no name */
3290 if (!entry->pev.event || !entry->pev.group)
3291 continue;
3292 if ((!pev->group || strglobmatch(entry->pev.group, pev->group)) &&
3293 strglobmatch(entry->pev.event, pev->event)) {
3294 ret = probe_cache_entry__get_event(entry, &tmp_tevs);
3295 if (ret > 0)
3296 ret = concat_probe_trace_events(tevs, &ntevs,
3297 &tmp_tevs, ret);
3298 if (ret < 0)
3299 break;
3302 probe_cache__delete(cache);
3303 if (ret < 0) {
3304 clear_probe_trace_events(*tevs, ntevs);
3305 zfree(tevs);
3306 } else {
3307 ret = ntevs;
3308 if (ntevs > 0 && target && target[0] == '/')
3309 pev->uprobes = true;
3312 return ret;
3315 /* Try to find probe_trace_event from all probe caches */
3316 static int find_cached_events_all(struct perf_probe_event *pev,
3317 struct probe_trace_event **tevs)
3319 struct probe_trace_event *tmp_tevs = NULL;
3320 struct strlist *bidlist;
3321 struct str_node *nd;
3322 char *pathname;
3323 int ntevs = 0;
3324 int ret;
3326 /* Get the buildid list of all valid caches */
3327 bidlist = build_id_cache__list_all(true);
3328 if (!bidlist) {
3329 ret = -errno;
3330 pr_debug("Failed to get buildids: %d\n", ret);
3331 return ret;
3334 ret = 0;
3335 strlist__for_each_entry(nd, bidlist) {
3336 pathname = build_id_cache__origname(nd->s);
3337 ret = find_cached_events(pev, &tmp_tevs, pathname);
3338 /* In the case of cnt == 0, we just skip it */
3339 if (ret > 0)
3340 ret = concat_probe_trace_events(tevs, &ntevs,
3341 &tmp_tevs, ret);
3342 free(pathname);
3343 if (ret < 0)
3344 break;
3346 strlist__delete(bidlist);
3348 if (ret < 0) {
3349 clear_probe_trace_events(*tevs, ntevs);
3350 zfree(tevs);
3351 } else
3352 ret = ntevs;
3354 return ret;
3357 static int find_probe_trace_events_from_cache(struct perf_probe_event *pev,
3358 struct probe_trace_event **tevs)
3360 struct probe_cache *cache;
3361 struct probe_cache_entry *entry;
3362 struct probe_trace_event *tev;
3363 struct str_node *node;
3364 int ret, i;
3366 if (pev->sdt) {
3367 /* For SDT/cached events, we use special search functions */
3368 if (!pev->target)
3369 return find_cached_events_all(pev, tevs);
3370 else
3371 return find_cached_events(pev, tevs, pev->target);
3373 cache = probe_cache__new(pev->target, pev->nsi);
3374 if (!cache)
3375 return 0;
3377 entry = probe_cache__find(cache, pev);
3378 if (!entry) {
3379 /* SDT must be in the cache */
3380 ret = pev->sdt ? -ENOENT : 0;
3381 goto out;
3384 ret = strlist__nr_entries(entry->tevlist);
3385 if (ret > probe_conf.max_probes) {
3386 pr_debug("Too many entries matched in the cache of %s\n",
3387 pev->target ? : "kernel");
3388 ret = -E2BIG;
3389 goto out;
3392 *tevs = zalloc(ret * sizeof(*tev));
3393 if (!*tevs) {
3394 ret = -ENOMEM;
3395 goto out;
3398 i = 0;
3399 strlist__for_each_entry(node, entry->tevlist) {
3400 tev = &(*tevs)[i++];
3401 ret = parse_probe_trace_command(node->s, tev);
3402 if (ret < 0)
3403 goto out;
3404 /* Set the uprobes attribute as same as original */
3405 tev->uprobes = pev->uprobes;
3407 ret = i;
3409 out:
3410 probe_cache__delete(cache);
3411 return ret;
3414 static int convert_to_probe_trace_events(struct perf_probe_event *pev,
3415 struct probe_trace_event **tevs)
3417 int ret;
3419 if (!pev->group && !pev->sdt) {
3420 /* Set group name if not given */
3421 if (!pev->uprobes) {
3422 pev->group = strdup(PERFPROBE_GROUP);
3423 ret = pev->group ? 0 : -ENOMEM;
3424 } else
3425 ret = convert_exec_to_group(pev->target, &pev->group);
3426 if (ret != 0) {
3427 pr_warning("Failed to make a group name.\n");
3428 return ret;
3432 ret = try_to_find_absolute_address(pev, tevs);
3433 if (ret > 0)
3434 return ret;
3436 /* At first, we need to lookup cache entry */
3437 ret = find_probe_trace_events_from_cache(pev, tevs);
3438 if (ret > 0 || pev->sdt) /* SDT can be found only in the cache */
3439 return ret == 0 ? -ENOENT : ret; /* Found in probe cache */
3441 /* Convert perf_probe_event with debuginfo */
3442 ret = try_to_find_probe_trace_events(pev, tevs);
3443 if (ret != 0)
3444 return ret; /* Found in debuginfo or got an error */
3446 return find_probe_trace_events_from_map(pev, tevs);
3449 int convert_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3451 int i, ret;
3453 /* Loop 1: convert all events */
3454 for (i = 0; i < npevs; i++) {
3455 /* Init kprobe blacklist if needed */
3456 if (!pevs[i].uprobes)
3457 kprobe_blacklist__init();
3458 /* Convert with or without debuginfo */
3459 ret = convert_to_probe_trace_events(&pevs[i], &pevs[i].tevs);
3460 if (ret < 0)
3461 return ret;
3462 pevs[i].ntevs = ret;
3464 /* This just release blacklist only if allocated */
3465 kprobe_blacklist__release();
3467 return 0;
3470 static int show_probe_trace_event(struct probe_trace_event *tev)
3472 char *buf = synthesize_probe_trace_command(tev);
3474 if (!buf) {
3475 pr_debug("Failed to synthesize probe trace event.\n");
3476 return -EINVAL;
3479 /* Showing definition always go stdout */
3480 printf("%s\n", buf);
3481 free(buf);
3483 return 0;
3486 int show_probe_trace_events(struct perf_probe_event *pevs, int npevs)
3488 struct strlist *namelist = strlist__new(NULL, NULL);
3489 struct probe_trace_event *tev;
3490 struct perf_probe_event *pev;
3491 int i, j, ret = 0;
3493 if (!namelist)
3494 return -ENOMEM;
3496 for (j = 0; j < npevs && !ret; j++) {
3497 pev = &pevs[j];
3498 for (i = 0; i < pev->ntevs && !ret; i++) {
3499 tev = &pev->tevs[i];
3500 /* Skip if the symbol is out of .text or blacklisted */
3501 if (!tev->point.symbol && !pev->uprobes)
3502 continue;
3504 /* Set new name for tev (and update namelist) */
3505 ret = probe_trace_event__set_name(tev, pev,
3506 namelist, true);
3507 if (!ret)
3508 ret = show_probe_trace_event(tev);
3511 strlist__delete(namelist);
3513 return ret;
3516 int apply_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3518 int i, ret = 0;
3520 /* Loop 2: add all events */
3521 for (i = 0; i < npevs; i++) {
3522 ret = __add_probe_trace_events(&pevs[i], pevs[i].tevs,
3523 pevs[i].ntevs,
3524 probe_conf.force_add);
3525 if (ret < 0)
3526 break;
3528 return ret;
3531 void cleanup_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3533 int i, j;
3534 struct perf_probe_event *pev;
3536 /* Loop 3: cleanup and free trace events */
3537 for (i = 0; i < npevs; i++) {
3538 pev = &pevs[i];
3539 for (j = 0; j < pevs[i].ntevs; j++)
3540 clear_probe_trace_event(&pevs[i].tevs[j]);
3541 zfree(&pevs[i].tevs);
3542 pevs[i].ntevs = 0;
3543 nsinfo__zput(pev->nsi);
3544 clear_perf_probe_event(&pevs[i]);
3548 int add_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3550 int ret;
3552 ret = init_probe_symbol_maps(pevs->uprobes);
3553 if (ret < 0)
3554 return ret;
3556 ret = convert_perf_probe_events(pevs, npevs);
3557 if (ret == 0)
3558 ret = apply_perf_probe_events(pevs, npevs);
3560 cleanup_perf_probe_events(pevs, npevs);
3562 exit_probe_symbol_maps();
3563 return ret;
3566 int del_perf_probe_events(struct strfilter *filter)
3568 int ret, ret2, ufd = -1, kfd = -1;
3569 char *str = strfilter__string(filter);
3571 if (!str)
3572 return -EINVAL;
3574 /* Get current event names */
3575 ret = probe_file__open_both(&kfd, &ufd, PF_FL_RW);
3576 if (ret < 0)
3577 goto out;
3579 ret = probe_file__del_events(kfd, filter);
3580 if (ret < 0 && ret != -ENOENT)
3581 goto error;
3583 ret2 = probe_file__del_events(ufd, filter);
3584 if (ret2 < 0 && ret2 != -ENOENT) {
3585 ret = ret2;
3586 goto error;
3588 ret = 0;
3590 error:
3591 if (kfd >= 0)
3592 close(kfd);
3593 if (ufd >= 0)
3594 close(ufd);
3595 out:
3596 free(str);
3598 return ret;
3601 int show_available_funcs(const char *target, struct nsinfo *nsi,
3602 struct strfilter *_filter, bool user)
3604 struct rb_node *nd;
3605 struct map *map;
3606 int ret;
3608 ret = init_probe_symbol_maps(user);
3609 if (ret < 0)
3610 return ret;
3612 /* Get a symbol map */
3613 map = get_target_map(target, nsi, user);
3614 if (!map) {
3615 pr_err("Failed to get a map for %s\n", (target) ? : "kernel");
3616 return -EINVAL;
3619 ret = map__load(map);
3620 if (ret) {
3621 if (ret == -2) {
3622 char *str = strfilter__string(_filter);
3623 pr_err("Failed to find symbols matched to \"%s\"\n",
3624 str);
3625 free(str);
3626 } else
3627 pr_err("Failed to load symbols in %s\n",
3628 (target) ? : "kernel");
3629 goto end;
3631 if (!dso__sorted_by_name(map->dso))
3632 dso__sort_by_name(map->dso);
3634 /* Show all (filtered) symbols */
3635 setup_pager();
3637 for (nd = rb_first_cached(&map->dso->symbol_names); nd;
3638 nd = rb_next(nd)) {
3639 struct symbol_name_rb_node *pos = rb_entry(nd, struct symbol_name_rb_node, rb_node);
3641 if (strfilter__compare(_filter, pos->sym.name))
3642 printf("%s\n", pos->sym.name);
3644 end:
3645 map__put(map);
3646 exit_probe_symbol_maps();
3648 return ret;
3651 int copy_to_probe_trace_arg(struct probe_trace_arg *tvar,
3652 struct perf_probe_arg *pvar)
3654 tvar->value = strdup(pvar->var);
3655 if (tvar->value == NULL)
3656 return -ENOMEM;
3657 if (pvar->type) {
3658 tvar->type = strdup(pvar->type);
3659 if (tvar->type == NULL)
3660 return -ENOMEM;
3662 if (pvar->name) {
3663 tvar->name = strdup(pvar->name);
3664 if (tvar->name == NULL)
3665 return -ENOMEM;
3666 } else
3667 tvar->name = NULL;
3668 return 0;