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