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