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