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