db6021834e8fd23ae56a45cd29d608f65264e4c9
[firefly-linux-kernel-4.4.55.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/debugfs.h>
44 #include <api/fs/tracefs.h>
45 #include "trace-event.h"        /* For __maybe_unused */
46 #include "probe-event.h"
47 #include "probe-finder.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 /* If there is no space to write, returns -E2BIG. */
59 static int e_snprintf(char *str, size_t size, const char *format, ...)
60         __attribute__((format(printf, 3, 4)));
61
62 static int e_snprintf(char *str, size_t size, const char *format, ...)
63 {
64         int ret;
65         va_list ap;
66         va_start(ap, format);
67         ret = vsnprintf(str, size, format, ap);
68         va_end(ap);
69         if (ret >= (int)size)
70                 ret = -E2BIG;
71         return ret;
72 }
73
74 static char *synthesize_perf_probe_point(struct perf_probe_point *pp);
75 static void clear_probe_trace_event(struct probe_trace_event *tev);
76 static struct machine *host_machine;
77
78 /* Initialize symbol maps and path of vmlinux/modules */
79 static int init_symbol_maps(bool user_only)
80 {
81         int ret;
82
83         symbol_conf.sort_by_name = true;
84         symbol_conf.allow_aliases = true;
85         ret = symbol__init(NULL);
86         if (ret < 0) {
87                 pr_debug("Failed to init symbol map.\n");
88                 goto out;
89         }
90
91         if (host_machine || user_only)  /* already initialized */
92                 return 0;
93
94         if (symbol_conf.vmlinux_name)
95                 pr_debug("Use vmlinux: %s\n", symbol_conf.vmlinux_name);
96
97         host_machine = machine__new_host();
98         if (!host_machine) {
99                 pr_debug("machine__new_host() failed.\n");
100                 symbol__exit();
101                 ret = -1;
102         }
103 out:
104         if (ret < 0)
105                 pr_warning("Failed to init vmlinux path.\n");
106         return ret;
107 }
108
109 static void exit_symbol_maps(void)
110 {
111         if (host_machine) {
112                 machine__delete(host_machine);
113                 host_machine = NULL;
114         }
115         symbol__exit();
116 }
117
118 static struct symbol *__find_kernel_function_by_name(const char *name,
119                                                      struct map **mapp)
120 {
121         return machine__find_kernel_function_by_name(host_machine, name, mapp,
122                                                      NULL);
123 }
124
125 static struct symbol *__find_kernel_function(u64 addr, struct map **mapp)
126 {
127         return machine__find_kernel_function(host_machine, addr, mapp, NULL);
128 }
129
130 static struct ref_reloc_sym *kernel_get_ref_reloc_sym(void)
131 {
132         /* kmap->ref_reloc_sym should be set if host_machine is initialized */
133         struct kmap *kmap;
134
135         if (map__load(host_machine->vmlinux_maps[MAP__FUNCTION], NULL) < 0)
136                 return NULL;
137
138         kmap = map__kmap(host_machine->vmlinux_maps[MAP__FUNCTION]);
139         if (!kmap)
140                 return NULL;
141         return kmap->ref_reloc_sym;
142 }
143
144 static u64 kernel_get_symbol_address_by_name(const char *name, bool reloc)
145 {
146         struct ref_reloc_sym *reloc_sym;
147         struct symbol *sym;
148         struct map *map;
149
150         /* ref_reloc_sym is just a label. Need a special fix*/
151         reloc_sym = kernel_get_ref_reloc_sym();
152         if (reloc_sym && strcmp(name, reloc_sym->name) == 0)
153                 return (reloc) ? reloc_sym->addr : reloc_sym->unrelocated_addr;
154         else {
155                 sym = __find_kernel_function_by_name(name, &map);
156                 if (sym)
157                         return map->unmap_ip(map, sym->start) -
158                                 ((reloc) ? 0 : map->reloc);
159         }
160         return 0;
161 }
162
163 static struct map *kernel_get_module_map(const char *module)
164 {
165         struct rb_node *nd;
166         struct map_groups *grp = &host_machine->kmaps;
167
168         /* A file path -- this is an offline module */
169         if (module && strchr(module, '/'))
170                 return machine__new_module(host_machine, 0, module);
171
172         if (!module)
173                 module = "kernel";
174
175         for (nd = rb_first(&grp->maps[MAP__FUNCTION]); nd; nd = rb_next(nd)) {
176                 struct map *pos = rb_entry(nd, struct map, rb_node);
177                 if (strncmp(pos->dso->short_name + 1, module,
178                             pos->dso->short_name_len - 2) == 0) {
179                         return pos;
180                 }
181         }
182         return NULL;
183 }
184
185 static struct map *get_target_map(const char *target, bool user)
186 {
187         /* Init maps of given executable or kernel */
188         if (user)
189                 return dso__new_map(target);
190         else
191                 return kernel_get_module_map(target);
192 }
193
194 static void put_target_map(struct map *map, bool user)
195 {
196         if (map && user) {
197                 /* Only the user map needs to be released */
198                 map__delete(map);
199         }
200 }
201
202
203 static struct dso *kernel_get_module_dso(const char *module)
204 {
205         struct dso *dso;
206         struct map *map;
207         const char *vmlinux_name;
208
209         if (module) {
210                 list_for_each_entry(dso, &host_machine->kernel_dsos.head,
211                                     node) {
212                         if (strncmp(dso->short_name + 1, module,
213                                     dso->short_name_len - 2) == 0)
214                                 goto found;
215                 }
216                 pr_debug("Failed to find module %s.\n", module);
217                 return NULL;
218         }
219
220         map = host_machine->vmlinux_maps[MAP__FUNCTION];
221         dso = map->dso;
222
223         vmlinux_name = symbol_conf.vmlinux_name;
224         if (vmlinux_name) {
225                 if (dso__load_vmlinux(dso, map, vmlinux_name, false, NULL) <= 0)
226                         return NULL;
227         } else {
228                 if (dso__load_vmlinux_path(dso, map, NULL) <= 0) {
229                         pr_debug("Failed to load kernel map.\n");
230                         return NULL;
231                 }
232         }
233 found:
234         return dso;
235 }
236
237 const char *kernel_get_module_path(const char *module)
238 {
239         struct dso *dso = kernel_get_module_dso(module);
240         return (dso) ? dso->long_name : NULL;
241 }
242
243 static int convert_exec_to_group(const char *exec, char **result)
244 {
245         char *ptr1, *ptr2, *exec_copy;
246         char buf[64];
247         int ret;
248
249         exec_copy = strdup(exec);
250         if (!exec_copy)
251                 return -ENOMEM;
252
253         ptr1 = basename(exec_copy);
254         if (!ptr1) {
255                 ret = -EINVAL;
256                 goto out;
257         }
258
259         ptr2 = strpbrk(ptr1, "-._");
260         if (ptr2)
261                 *ptr2 = '\0';
262         ret = e_snprintf(buf, 64, "%s_%s", PERFPROBE_GROUP, ptr1);
263         if (ret < 0)
264                 goto out;
265
266         *result = strdup(buf);
267         ret = *result ? 0 : -ENOMEM;
268
269 out:
270         free(exec_copy);
271         return ret;
272 }
273
274 static void clear_perf_probe_point(struct perf_probe_point *pp)
275 {
276         free(pp->file);
277         free(pp->function);
278         free(pp->lazy_line);
279 }
280
281 static void clear_probe_trace_events(struct probe_trace_event *tevs, int ntevs)
282 {
283         int i;
284
285         for (i = 0; i < ntevs; i++)
286                 clear_probe_trace_event(tevs + i);
287 }
288
289 #ifdef HAVE_DWARF_SUPPORT
290 /*
291  * Some binaries like glibc have special symbols which are on the symbol
292  * table, but not in the debuginfo. If we can find the address of the
293  * symbol from map, we can translate the address back to the probe point.
294  */
295 static int find_alternative_probe_point(struct debuginfo *dinfo,
296                                         struct perf_probe_point *pp,
297                                         struct perf_probe_point *result,
298                                         const char *target, bool uprobes)
299 {
300         struct map *map = NULL;
301         struct symbol *sym;
302         u64 address = 0;
303         int ret = -ENOENT;
304
305         /* This can work only for function-name based one */
306         if (!pp->function || pp->file)
307                 return -ENOTSUP;
308
309         map = get_target_map(target, uprobes);
310         if (!map)
311                 return -EINVAL;
312
313         /* Find the address of given function */
314         map__for_each_symbol_by_name(map, pp->function, sym) {
315                 if (uprobes)
316                         address = sym->start;
317                 else
318                         address = map->unmap_ip(map, sym->start);
319                 break;
320         }
321         if (!address) {
322                 ret = -ENOENT;
323                 goto out;
324         }
325         pr_debug("Symbol %s address found : %" PRIx64 "\n",
326                         pp->function, address);
327
328         ret = debuginfo__find_probe_point(dinfo, (unsigned long)address,
329                                           result);
330         if (ret <= 0)
331                 ret = (!ret) ? -ENOENT : ret;
332         else {
333                 result->offset += pp->offset;
334                 result->line += pp->line;
335                 result->retprobe = pp->retprobe;
336                 ret = 0;
337         }
338
339 out:
340         put_target_map(map, uprobes);
341         return ret;
342
343 }
344
345 static int get_alternative_probe_event(struct debuginfo *dinfo,
346                                        struct perf_probe_event *pev,
347                                        struct perf_probe_point *tmp)
348 {
349         int ret;
350
351         memcpy(tmp, &pev->point, sizeof(*tmp));
352         memset(&pev->point, 0, sizeof(pev->point));
353         ret = find_alternative_probe_point(dinfo, tmp, &pev->point,
354                                            pev->target, pev->uprobes);
355         if (ret < 0)
356                 memcpy(&pev->point, tmp, sizeof(*tmp));
357
358         return ret;
359 }
360
361 static int get_alternative_line_range(struct debuginfo *dinfo,
362                                       struct line_range *lr,
363                                       const char *target, bool user)
364 {
365         struct perf_probe_point pp = { .function = lr->function,
366                                        .file = lr->file,
367                                        .line = lr->start };
368         struct perf_probe_point result;
369         int ret, len = 0;
370
371         memset(&result, 0, sizeof(result));
372
373         if (lr->end != INT_MAX)
374                 len = lr->end - lr->start;
375         ret = find_alternative_probe_point(dinfo, &pp, &result,
376                                            target, user);
377         if (!ret) {
378                 lr->function = result.function;
379                 lr->file = result.file;
380                 lr->start = result.line;
381                 if (lr->end != INT_MAX)
382                         lr->end = lr->start + len;
383                 clear_perf_probe_point(&pp);
384         }
385         return ret;
386 }
387
388 /* Open new debuginfo of given module */
389 static struct debuginfo *open_debuginfo(const char *module, bool silent)
390 {
391         const char *path = module;
392         struct debuginfo *ret;
393
394         if (!module || !strchr(module, '/')) {
395                 path = kernel_get_module_path(module);
396                 if (!path) {
397                         if (!silent)
398                                 pr_err("Failed to find path of %s module.\n",
399                                        module ?: "kernel");
400                         return NULL;
401                 }
402         }
403         ret = debuginfo__new(path);
404         if (!ret && !silent) {
405                 pr_warning("The %s file has no debug information.\n", path);
406                 if (!module || !strtailcmp(path, ".ko"))
407                         pr_warning("Rebuild with CONFIG_DEBUG_INFO=y, ");
408                 else
409                         pr_warning("Rebuild with -g, ");
410                 pr_warning("or install an appropriate debuginfo package.\n");
411         }
412         return ret;
413 }
414
415
416 static int get_text_start_address(const char *exec, unsigned long *address)
417 {
418         Elf *elf;
419         GElf_Ehdr ehdr;
420         GElf_Shdr shdr;
421         int fd, ret = -ENOENT;
422
423         fd = open(exec, O_RDONLY);
424         if (fd < 0)
425                 return -errno;
426
427         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
428         if (elf == NULL)
429                 return -EINVAL;
430
431         if (gelf_getehdr(elf, &ehdr) == NULL)
432                 goto out;
433
434         if (!elf_section_by_name(elf, &ehdr, &shdr, ".text", NULL))
435                 goto out;
436
437         *address = shdr.sh_addr - shdr.sh_offset;
438         ret = 0;
439 out:
440         elf_end(elf);
441         return ret;
442 }
443
444 /*
445  * Convert trace point to probe point with debuginfo
446  */
447 static int find_perf_probe_point_from_dwarf(struct probe_trace_point *tp,
448                                             struct perf_probe_point *pp,
449                                             bool is_kprobe)
450 {
451         struct debuginfo *dinfo = NULL;
452         unsigned long stext = 0;
453         u64 addr = tp->address;
454         int ret = -ENOENT;
455
456         /* convert the address to dwarf address */
457         if (!is_kprobe) {
458                 if (!addr) {
459                         ret = -EINVAL;
460                         goto error;
461                 }
462                 ret = get_text_start_address(tp->module, &stext);
463                 if (ret < 0)
464                         goto error;
465                 addr += stext;
466         } else {
467                 addr = kernel_get_symbol_address_by_name(tp->symbol, false);
468                 if (addr == 0)
469                         goto error;
470                 addr += tp->offset;
471         }
472
473         pr_debug("try to find information at %" PRIx64 " in %s\n", addr,
474                  tp->module ? : "kernel");
475
476         dinfo = open_debuginfo(tp->module, verbose == 0);
477         if (dinfo) {
478                 ret = debuginfo__find_probe_point(dinfo,
479                                                  (unsigned long)addr, pp);
480                 debuginfo__delete(dinfo);
481         } else
482                 ret = -ENOENT;
483
484         if (ret > 0) {
485                 pp->retprobe = tp->retprobe;
486                 return 0;
487         }
488 error:
489         pr_debug("Failed to find corresponding probes from debuginfo.\n");
490         return ret ? : -ENOENT;
491 }
492
493 static int add_exec_to_probe_trace_events(struct probe_trace_event *tevs,
494                                           int ntevs, const char *exec)
495 {
496         int i, ret = 0;
497         unsigned long stext = 0;
498
499         if (!exec)
500                 return 0;
501
502         ret = get_text_start_address(exec, &stext);
503         if (ret < 0)
504                 return ret;
505
506         for (i = 0; i < ntevs && ret >= 0; i++) {
507                 /* point.address is the addres of point.symbol + point.offset */
508                 tevs[i].point.address -= stext;
509                 tevs[i].point.module = strdup(exec);
510                 if (!tevs[i].point.module) {
511                         ret = -ENOMEM;
512                         break;
513                 }
514                 tevs[i].uprobes = true;
515         }
516
517         return ret;
518 }
519
520 static int add_module_to_probe_trace_events(struct probe_trace_event *tevs,
521                                             int ntevs, const char *module)
522 {
523         int i, ret = 0;
524         char *tmp;
525
526         if (!module)
527                 return 0;
528
529         tmp = strrchr(module, '/');
530         if (tmp) {
531                 /* This is a module path -- get the module name */
532                 module = strdup(tmp + 1);
533                 if (!module)
534                         return -ENOMEM;
535                 tmp = strchr(module, '.');
536                 if (tmp)
537                         *tmp = '\0';
538                 tmp = (char *)module;   /* For free() */
539         }
540
541         for (i = 0; i < ntevs; i++) {
542                 tevs[i].point.module = strdup(module);
543                 if (!tevs[i].point.module) {
544                         ret = -ENOMEM;
545                         break;
546                 }
547         }
548
549         free(tmp);
550         return ret;
551 }
552
553 /* Post processing the probe events */
554 static int post_process_probe_trace_events(struct probe_trace_event *tevs,
555                                            int ntevs, const char *module,
556                                            bool uprobe)
557 {
558         struct ref_reloc_sym *reloc_sym;
559         u64 etext_addr;
560         char *tmp;
561         int i, skipped = 0;
562
563         if (uprobe)
564                 return add_exec_to_probe_trace_events(tevs, ntevs, module);
565
566         /* Note that currently ref_reloc_sym based probe is not for drivers */
567         if (module)
568                 return add_module_to_probe_trace_events(tevs, ntevs, module);
569
570         reloc_sym = kernel_get_ref_reloc_sym();
571         if (!reloc_sym) {
572                 pr_warning("Relocated base symbol is not found!\n");
573                 return -EINVAL;
574         }
575         /* Get the address of _etext for checking non-probable text symbol */
576         etext_addr = kernel_get_symbol_address_by_name("_etext", false);
577
578         for (i = 0; i < ntevs; i++) {
579                 if (tevs[i].point.address && !tevs[i].point.retprobe) {
580                         /* If we found a wrong one, mark it by NULL symbol */
581                         if (etext_addr < tevs[i].point.address) {
582                                 pr_warning("%s+%lu is out of .text, skip it.\n",
583                                    tevs[i].point.symbol, tevs[i].point.offset);
584                                 tmp = NULL;
585                                 skipped++;
586                         } else {
587                                 tmp = strdup(reloc_sym->name);
588                                 if (!tmp)
589                                         return -ENOMEM;
590                         }
591                         /* If we have no realname, use symbol for it */
592                         if (!tevs[i].point.realname)
593                                 tevs[i].point.realname = tevs[i].point.symbol;
594                         else
595                                 free(tevs[i].point.symbol);
596                         tevs[i].point.symbol = tmp;
597                         tevs[i].point.offset = tevs[i].point.address -
598                                                reloc_sym->unrelocated_addr;
599                 }
600         }
601         return skipped;
602 }
603
604 /* Try to find perf_probe_event with debuginfo */
605 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
606                                           struct probe_trace_event **tevs)
607 {
608         bool need_dwarf = perf_probe_event_need_dwarf(pev);
609         struct perf_probe_point tmp;
610         struct debuginfo *dinfo;
611         int ntevs, ret = 0;
612
613         dinfo = open_debuginfo(pev->target, !need_dwarf);
614         if (!dinfo) {
615                 if (need_dwarf)
616                         return -ENOENT;
617                 pr_debug("Could not open debuginfo. Try to use symbols.\n");
618                 return 0;
619         }
620
621         pr_debug("Try to find probe point from debuginfo.\n");
622         /* Searching trace events corresponding to a probe event */
623         ntevs = debuginfo__find_trace_events(dinfo, pev, tevs);
624
625         if (ntevs == 0) {  /* Not found, retry with an alternative */
626                 ret = get_alternative_probe_event(dinfo, pev, &tmp);
627                 if (!ret) {
628                         ntevs = debuginfo__find_trace_events(dinfo, pev, tevs);
629                         /*
630                          * Write back to the original probe_event for
631                          * setting appropriate (user given) event name
632                          */
633                         clear_perf_probe_point(&pev->point);
634                         memcpy(&pev->point, &tmp, sizeof(tmp));
635                 }
636         }
637
638         debuginfo__delete(dinfo);
639
640         if (ntevs > 0) {        /* Succeeded to find trace events */
641                 pr_debug("Found %d probe_trace_events.\n", ntevs);
642                 ret = post_process_probe_trace_events(*tevs, ntevs,
643                                                 pev->target, pev->uprobes);
644                 if (ret < 0 || ret == ntevs) {
645                         clear_probe_trace_events(*tevs, ntevs);
646                         zfree(tevs);
647                 }
648                 if (ret != ntevs)
649                         return ret < 0 ? ret : ntevs;
650                 ntevs = 0;
651                 /* Fall through */
652         }
653
654         if (ntevs == 0) {       /* No error but failed to find probe point. */
655                 pr_warning("Probe point '%s' not found.\n",
656                            synthesize_perf_probe_point(&pev->point));
657                 return -ENOENT;
658         }
659         /* Error path : ntevs < 0 */
660         pr_debug("An error occurred in debuginfo analysis (%d).\n", ntevs);
661         if (ntevs == -EBADF) {
662                 pr_warning("Warning: No dwarf info found in the vmlinux - "
663                         "please rebuild kernel with CONFIG_DEBUG_INFO=y.\n");
664                 if (!need_dwarf) {
665                         pr_debug("Trying to use symbols.\n");
666                         return 0;
667                 }
668         }
669         return ntevs;
670 }
671
672 #define LINEBUF_SIZE 256
673 #define NR_ADDITIONAL_LINES 2
674
675 static int __show_one_line(FILE *fp, int l, bool skip, bool show_num)
676 {
677         char buf[LINEBUF_SIZE], sbuf[STRERR_BUFSIZE];
678         const char *color = show_num ? "" : PERF_COLOR_BLUE;
679         const char *prefix = NULL;
680
681         do {
682                 if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
683                         goto error;
684                 if (skip)
685                         continue;
686                 if (!prefix) {
687                         prefix = show_num ? "%7d  " : "         ";
688                         color_fprintf(stdout, color, prefix, l);
689                 }
690                 color_fprintf(stdout, color, "%s", buf);
691
692         } while (strchr(buf, '\n') == NULL);
693
694         return 1;
695 error:
696         if (ferror(fp)) {
697                 pr_warning("File read error: %s\n",
698                            strerror_r(errno, sbuf, sizeof(sbuf)));
699                 return -1;
700         }
701         return 0;
702 }
703
704 static int _show_one_line(FILE *fp, int l, bool skip, bool show_num)
705 {
706         int rv = __show_one_line(fp, l, skip, show_num);
707         if (rv == 0) {
708                 pr_warning("Source file is shorter than expected.\n");
709                 rv = -1;
710         }
711         return rv;
712 }
713
714 #define show_one_line_with_num(f,l)     _show_one_line(f,l,false,true)
715 #define show_one_line(f,l)              _show_one_line(f,l,false,false)
716 #define skip_one_line(f,l)              _show_one_line(f,l,true,false)
717 #define show_one_line_or_eof(f,l)       __show_one_line(f,l,false,false)
718
719 /*
720  * Show line-range always requires debuginfo to find source file and
721  * line number.
722  */
723 static int __show_line_range(struct line_range *lr, const char *module,
724                              bool user)
725 {
726         int l = 1;
727         struct int_node *ln;
728         struct debuginfo *dinfo;
729         FILE *fp;
730         int ret;
731         char *tmp;
732         char sbuf[STRERR_BUFSIZE];
733
734         /* Search a line range */
735         dinfo = open_debuginfo(module, false);
736         if (!dinfo)
737                 return -ENOENT;
738
739         ret = debuginfo__find_line_range(dinfo, lr);
740         if (!ret) {     /* Not found, retry with an alternative */
741                 ret = get_alternative_line_range(dinfo, lr, module, user);
742                 if (!ret)
743                         ret = debuginfo__find_line_range(dinfo, lr);
744         }
745         debuginfo__delete(dinfo);
746         if (ret == 0 || ret == -ENOENT) {
747                 pr_warning("Specified source line is not found.\n");
748                 return -ENOENT;
749         } else if (ret < 0) {
750                 pr_warning("Debuginfo analysis failed.\n");
751                 return ret;
752         }
753
754         /* Convert source file path */
755         tmp = lr->path;
756         ret = get_real_path(tmp, lr->comp_dir, &lr->path);
757
758         /* Free old path when new path is assigned */
759         if (tmp != lr->path)
760                 free(tmp);
761
762         if (ret < 0) {
763                 pr_warning("Failed to find source file path.\n");
764                 return ret;
765         }
766
767         setup_pager();
768
769         if (lr->function)
770                 fprintf(stdout, "<%s@%s:%d>\n", lr->function, lr->path,
771                         lr->start - lr->offset);
772         else
773                 fprintf(stdout, "<%s:%d>\n", lr->path, lr->start);
774
775         fp = fopen(lr->path, "r");
776         if (fp == NULL) {
777                 pr_warning("Failed to open %s: %s\n", lr->path,
778                            strerror_r(errno, sbuf, sizeof(sbuf)));
779                 return -errno;
780         }
781         /* Skip to starting line number */
782         while (l < lr->start) {
783                 ret = skip_one_line(fp, l++);
784                 if (ret < 0)
785                         goto end;
786         }
787
788         intlist__for_each(ln, lr->line_list) {
789                 for (; ln->i > l; l++) {
790                         ret = show_one_line(fp, l - lr->offset);
791                         if (ret < 0)
792                                 goto end;
793                 }
794                 ret = show_one_line_with_num(fp, l++ - lr->offset);
795                 if (ret < 0)
796                         goto end;
797         }
798
799         if (lr->end == INT_MAX)
800                 lr->end = l + NR_ADDITIONAL_LINES;
801         while (l <= lr->end) {
802                 ret = show_one_line_or_eof(fp, l++ - lr->offset);
803                 if (ret <= 0)
804                         break;
805         }
806 end:
807         fclose(fp);
808         return ret;
809 }
810
811 int show_line_range(struct line_range *lr, const char *module, bool user)
812 {
813         int ret;
814
815         ret = init_symbol_maps(user);
816         if (ret < 0)
817                 return ret;
818         ret = __show_line_range(lr, module, user);
819         exit_symbol_maps();
820
821         return ret;
822 }
823
824 static int show_available_vars_at(struct debuginfo *dinfo,
825                                   struct perf_probe_event *pev,
826                                   struct strfilter *_filter)
827 {
828         char *buf;
829         int ret, i, nvars;
830         struct str_node *node;
831         struct variable_list *vls = NULL, *vl;
832         struct perf_probe_point tmp;
833         const char *var;
834
835         buf = synthesize_perf_probe_point(&pev->point);
836         if (!buf)
837                 return -EINVAL;
838         pr_debug("Searching variables at %s\n", buf);
839
840         ret = debuginfo__find_available_vars_at(dinfo, pev, &vls);
841         if (!ret) {  /* Not found, retry with an alternative */
842                 ret = get_alternative_probe_event(dinfo, pev, &tmp);
843                 if (!ret) {
844                         ret = debuginfo__find_available_vars_at(dinfo, pev,
845                                                                 &vls);
846                         /* Release the old probe_point */
847                         clear_perf_probe_point(&tmp);
848                 }
849         }
850         if (ret <= 0) {
851                 if (ret == 0 || ret == -ENOENT) {
852                         pr_err("Failed to find the address of %s\n", buf);
853                         ret = -ENOENT;
854                 } else
855                         pr_warning("Debuginfo analysis failed.\n");
856                 goto end;
857         }
858
859         /* Some variables are found */
860         fprintf(stdout, "Available variables at %s\n", buf);
861         for (i = 0; i < ret; i++) {
862                 vl = &vls[i];
863                 /*
864                  * A probe point might be converted to
865                  * several trace points.
866                  */
867                 fprintf(stdout, "\t@<%s+%lu>\n", vl->point.symbol,
868                         vl->point.offset);
869                 zfree(&vl->point.symbol);
870                 nvars = 0;
871                 if (vl->vars) {
872                         strlist__for_each(node, vl->vars) {
873                                 var = strchr(node->s, '\t') + 1;
874                                 if (strfilter__compare(_filter, var)) {
875                                         fprintf(stdout, "\t\t%s\n", node->s);
876                                         nvars++;
877                                 }
878                         }
879                         strlist__delete(vl->vars);
880                 }
881                 if (nvars == 0)
882                         fprintf(stdout, "\t\t(No matched variables)\n");
883         }
884         free(vls);
885 end:
886         free(buf);
887         return ret;
888 }
889
890 /* Show available variables on given probe point */
891 int show_available_vars(struct perf_probe_event *pevs, int npevs,
892                         struct strfilter *_filter)
893 {
894         int i, ret = 0;
895         struct debuginfo *dinfo;
896
897         ret = init_symbol_maps(pevs->uprobes);
898         if (ret < 0)
899                 return ret;
900
901         dinfo = open_debuginfo(pevs->target, false);
902         if (!dinfo) {
903                 ret = -ENOENT;
904                 goto out;
905         }
906
907         setup_pager();
908
909         for (i = 0; i < npevs && ret >= 0; i++)
910                 ret = show_available_vars_at(dinfo, &pevs[i], _filter);
911
912         debuginfo__delete(dinfo);
913 out:
914         exit_symbol_maps();
915         return ret;
916 }
917
918 #else   /* !HAVE_DWARF_SUPPORT */
919
920 static int
921 find_perf_probe_point_from_dwarf(struct probe_trace_point *tp __maybe_unused,
922                                  struct perf_probe_point *pp __maybe_unused,
923                                  bool is_kprobe __maybe_unused)
924 {
925         return -ENOSYS;
926 }
927
928 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
929                                 struct probe_trace_event **tevs __maybe_unused)
930 {
931         if (perf_probe_event_need_dwarf(pev)) {
932                 pr_warning("Debuginfo-analysis is not supported.\n");
933                 return -ENOSYS;
934         }
935
936         return 0;
937 }
938
939 int show_line_range(struct line_range *lr __maybe_unused,
940                     const char *module __maybe_unused,
941                     bool user __maybe_unused)
942 {
943         pr_warning("Debuginfo-analysis is not supported.\n");
944         return -ENOSYS;
945 }
946
947 int show_available_vars(struct perf_probe_event *pevs __maybe_unused,
948                         int npevs __maybe_unused,
949                         struct strfilter *filter __maybe_unused)
950 {
951         pr_warning("Debuginfo-analysis is not supported.\n");
952         return -ENOSYS;
953 }
954 #endif
955
956 void line_range__clear(struct line_range *lr)
957 {
958         free(lr->function);
959         free(lr->file);
960         free(lr->path);
961         free(lr->comp_dir);
962         intlist__delete(lr->line_list);
963         memset(lr, 0, sizeof(*lr));
964 }
965
966 int line_range__init(struct line_range *lr)
967 {
968         memset(lr, 0, sizeof(*lr));
969         lr->line_list = intlist__new(NULL);
970         if (!lr->line_list)
971                 return -ENOMEM;
972         else
973                 return 0;
974 }
975
976 static int parse_line_num(char **ptr, int *val, const char *what)
977 {
978         const char *start = *ptr;
979
980         errno = 0;
981         *val = strtol(*ptr, ptr, 0);
982         if (errno || *ptr == start) {
983                 semantic_error("'%s' is not a valid number.\n", what);
984                 return -EINVAL;
985         }
986         return 0;
987 }
988
989 /* Check the name is good for event, group or function */
990 static bool is_c_func_name(const char *name)
991 {
992         if (!isalpha(*name) && *name != '_')
993                 return false;
994         while (*++name != '\0') {
995                 if (!isalpha(*name) && !isdigit(*name) && *name != '_')
996                         return false;
997         }
998         return true;
999 }
1000
1001 /*
1002  * Stuff 'lr' according to the line range described by 'arg'.
1003  * The line range syntax is described by:
1004  *
1005  *         SRC[:SLN[+NUM|-ELN]]
1006  *         FNC[@SRC][:SLN[+NUM|-ELN]]
1007  */
1008 int parse_line_range_desc(const char *arg, struct line_range *lr)
1009 {
1010         char *range, *file, *name = strdup(arg);
1011         int err;
1012
1013         if (!name)
1014                 return -ENOMEM;
1015
1016         lr->start = 0;
1017         lr->end = INT_MAX;
1018
1019         range = strchr(name, ':');
1020         if (range) {
1021                 *range++ = '\0';
1022
1023                 err = parse_line_num(&range, &lr->start, "start line");
1024                 if (err)
1025                         goto err;
1026
1027                 if (*range == '+' || *range == '-') {
1028                         const char c = *range++;
1029
1030                         err = parse_line_num(&range, &lr->end, "end line");
1031                         if (err)
1032                                 goto err;
1033
1034                         if (c == '+') {
1035                                 lr->end += lr->start;
1036                                 /*
1037                                  * Adjust the number of lines here.
1038                                  * If the number of lines == 1, the
1039                                  * the end of line should be equal to
1040                                  * the start of line.
1041                                  */
1042                                 lr->end--;
1043                         }
1044                 }
1045
1046                 pr_debug("Line range is %d to %d\n", lr->start, lr->end);
1047
1048                 err = -EINVAL;
1049                 if (lr->start > lr->end) {
1050                         semantic_error("Start line must be smaller"
1051                                        " than end line.\n");
1052                         goto err;
1053                 }
1054                 if (*range != '\0') {
1055                         semantic_error("Tailing with invalid str '%s'.\n", range);
1056                         goto err;
1057                 }
1058         }
1059
1060         file = strchr(name, '@');
1061         if (file) {
1062                 *file = '\0';
1063                 lr->file = strdup(++file);
1064                 if (lr->file == NULL) {
1065                         err = -ENOMEM;
1066                         goto err;
1067                 }
1068                 lr->function = name;
1069         } else if (strchr(name, '/') || strchr(name, '.'))
1070                 lr->file = name;
1071         else if (is_c_func_name(name))/* We reuse it for checking funcname */
1072                 lr->function = name;
1073         else {  /* Invalid name */
1074                 semantic_error("'%s' is not a valid function name.\n", name);
1075                 err = -EINVAL;
1076                 goto err;
1077         }
1078
1079         return 0;
1080 err:
1081         free(name);
1082         return err;
1083 }
1084
1085 /* Parse probepoint definition. */
1086 static int parse_perf_probe_point(char *arg, struct perf_probe_event *pev)
1087 {
1088         struct perf_probe_point *pp = &pev->point;
1089         char *ptr, *tmp;
1090         char c, nc = 0;
1091         bool file_spec = false;
1092         /*
1093          * <Syntax>
1094          * perf probe [EVENT=]SRC[:LN|;PTN]
1095          * perf probe [EVENT=]FUNC[@SRC][+OFFS|%return|:LN|;PAT]
1096          *
1097          * TODO:Group name support
1098          */
1099         if (!arg)
1100                 return -EINVAL;
1101
1102         ptr = strpbrk(arg, ";=@+%");
1103         if (ptr && *ptr == '=') {       /* Event name */
1104                 *ptr = '\0';
1105                 tmp = ptr + 1;
1106                 if (strchr(arg, ':')) {
1107                         semantic_error("Group name is not supported yet.\n");
1108                         return -ENOTSUP;
1109                 }
1110                 if (!is_c_func_name(arg)) {
1111                         semantic_error("%s is bad for event name -it must "
1112                                        "follow C symbol-naming rule.\n", arg);
1113                         return -EINVAL;
1114                 }
1115                 pev->event = strdup(arg);
1116                 if (pev->event == NULL)
1117                         return -ENOMEM;
1118                 pev->group = NULL;
1119                 arg = tmp;
1120         }
1121
1122         /*
1123          * Check arg is function or file name and copy it.
1124          *
1125          * We consider arg to be a file spec if and only if it satisfies
1126          * all of the below criteria::
1127          * - it does not include any of "+@%",
1128          * - it includes one of ":;", and
1129          * - it has a period '.' in the name.
1130          *
1131          * Otherwise, we consider arg to be a function specification.
1132          */
1133         if (!strpbrk(arg, "+@%") && (ptr = strpbrk(arg, ";:")) != NULL) {
1134                 /* This is a file spec if it includes a '.' before ; or : */
1135                 if (memchr(arg, '.', ptr - arg))
1136                         file_spec = true;
1137         }
1138
1139         ptr = strpbrk(arg, ";:+@%");
1140         if (ptr) {
1141                 nc = *ptr;
1142                 *ptr++ = '\0';
1143         }
1144
1145         tmp = strdup(arg);
1146         if (tmp == NULL)
1147                 return -ENOMEM;
1148
1149         if (file_spec)
1150                 pp->file = tmp;
1151         else
1152                 pp->function = tmp;
1153
1154         /* Parse other options */
1155         while (ptr) {
1156                 arg = ptr;
1157                 c = nc;
1158                 if (c == ';') { /* Lazy pattern must be the last part */
1159                         pp->lazy_line = strdup(arg);
1160                         if (pp->lazy_line == NULL)
1161                                 return -ENOMEM;
1162                         break;
1163                 }
1164                 ptr = strpbrk(arg, ";:+@%");
1165                 if (ptr) {
1166                         nc = *ptr;
1167                         *ptr++ = '\0';
1168                 }
1169                 switch (c) {
1170                 case ':':       /* Line number */
1171                         pp->line = strtoul(arg, &tmp, 0);
1172                         if (*tmp != '\0') {
1173                                 semantic_error("There is non-digit char"
1174                                                " in line number.\n");
1175                                 return -EINVAL;
1176                         }
1177                         break;
1178                 case '+':       /* Byte offset from a symbol */
1179                         pp->offset = strtoul(arg, &tmp, 0);
1180                         if (*tmp != '\0') {
1181                                 semantic_error("There is non-digit character"
1182                                                 " in offset.\n");
1183                                 return -EINVAL;
1184                         }
1185                         break;
1186                 case '@':       /* File name */
1187                         if (pp->file) {
1188                                 semantic_error("SRC@SRC is not allowed.\n");
1189                                 return -EINVAL;
1190                         }
1191                         pp->file = strdup(arg);
1192                         if (pp->file == NULL)
1193                                 return -ENOMEM;
1194                         break;
1195                 case '%':       /* Probe places */
1196                         if (strcmp(arg, "return") == 0) {
1197                                 pp->retprobe = 1;
1198                         } else {        /* Others not supported yet */
1199                                 semantic_error("%%%s is not supported.\n", arg);
1200                                 return -ENOTSUP;
1201                         }
1202                         break;
1203                 default:        /* Buggy case */
1204                         pr_err("This program has a bug at %s:%d.\n",
1205                                 __FILE__, __LINE__);
1206                         return -ENOTSUP;
1207                         break;
1208                 }
1209         }
1210
1211         /* Exclusion check */
1212         if (pp->lazy_line && pp->line) {
1213                 semantic_error("Lazy pattern can't be used with"
1214                                " line number.\n");
1215                 return -EINVAL;
1216         }
1217
1218         if (pp->lazy_line && pp->offset) {
1219                 semantic_error("Lazy pattern can't be used with offset.\n");
1220                 return -EINVAL;
1221         }
1222
1223         if (pp->line && pp->offset) {
1224                 semantic_error("Offset can't be used with line number.\n");
1225                 return -EINVAL;
1226         }
1227
1228         if (!pp->line && !pp->lazy_line && pp->file && !pp->function) {
1229                 semantic_error("File always requires line number or "
1230                                "lazy pattern.\n");
1231                 return -EINVAL;
1232         }
1233
1234         if (pp->offset && !pp->function) {
1235                 semantic_error("Offset requires an entry function.\n");
1236                 return -EINVAL;
1237         }
1238
1239         if (pp->retprobe && !pp->function) {
1240                 semantic_error("Return probe requires an entry function.\n");
1241                 return -EINVAL;
1242         }
1243
1244         if ((pp->offset || pp->line || pp->lazy_line) && pp->retprobe) {
1245                 semantic_error("Offset/Line/Lazy pattern can't be used with "
1246                                "return probe.\n");
1247                 return -EINVAL;
1248         }
1249
1250         pr_debug("symbol:%s file:%s line:%d offset:%lu return:%d lazy:%s\n",
1251                  pp->function, pp->file, pp->line, pp->offset, pp->retprobe,
1252                  pp->lazy_line);
1253         return 0;
1254 }
1255
1256 /* Parse perf-probe event argument */
1257 static int parse_perf_probe_arg(char *str, struct perf_probe_arg *arg)
1258 {
1259         char *tmp, *goodname;
1260         struct perf_probe_arg_field **fieldp;
1261
1262         pr_debug("parsing arg: %s into ", str);
1263
1264         tmp = strchr(str, '=');
1265         if (tmp) {
1266                 arg->name = strndup(str, tmp - str);
1267                 if (arg->name == NULL)
1268                         return -ENOMEM;
1269                 pr_debug("name:%s ", arg->name);
1270                 str = tmp + 1;
1271         }
1272
1273         tmp = strchr(str, ':');
1274         if (tmp) {      /* Type setting */
1275                 *tmp = '\0';
1276                 arg->type = strdup(tmp + 1);
1277                 if (arg->type == NULL)
1278                         return -ENOMEM;
1279                 pr_debug("type:%s ", arg->type);
1280         }
1281
1282         tmp = strpbrk(str, "-.[");
1283         if (!is_c_varname(str) || !tmp) {
1284                 /* A variable, register, symbol or special value */
1285                 arg->var = strdup(str);
1286                 if (arg->var == NULL)
1287                         return -ENOMEM;
1288                 pr_debug("%s\n", arg->var);
1289                 return 0;
1290         }
1291
1292         /* Structure fields or array element */
1293         arg->var = strndup(str, tmp - str);
1294         if (arg->var == NULL)
1295                 return -ENOMEM;
1296         goodname = arg->var;
1297         pr_debug("%s, ", arg->var);
1298         fieldp = &arg->field;
1299
1300         do {
1301                 *fieldp = zalloc(sizeof(struct perf_probe_arg_field));
1302                 if (*fieldp == NULL)
1303                         return -ENOMEM;
1304                 if (*tmp == '[') {      /* Array */
1305                         str = tmp;
1306                         (*fieldp)->index = strtol(str + 1, &tmp, 0);
1307                         (*fieldp)->ref = true;
1308                         if (*tmp != ']' || tmp == str + 1) {
1309                                 semantic_error("Array index must be a"
1310                                                 " number.\n");
1311                                 return -EINVAL;
1312                         }
1313                         tmp++;
1314                         if (*tmp == '\0')
1315                                 tmp = NULL;
1316                 } else {                /* Structure */
1317                         if (*tmp == '.') {
1318                                 str = tmp + 1;
1319                                 (*fieldp)->ref = false;
1320                         } else if (tmp[1] == '>') {
1321                                 str = tmp + 2;
1322                                 (*fieldp)->ref = true;
1323                         } else {
1324                                 semantic_error("Argument parse error: %s\n",
1325                                                str);
1326                                 return -EINVAL;
1327                         }
1328                         tmp = strpbrk(str, "-.[");
1329                 }
1330                 if (tmp) {
1331                         (*fieldp)->name = strndup(str, tmp - str);
1332                         if ((*fieldp)->name == NULL)
1333                                 return -ENOMEM;
1334                         if (*str != '[')
1335                                 goodname = (*fieldp)->name;
1336                         pr_debug("%s(%d), ", (*fieldp)->name, (*fieldp)->ref);
1337                         fieldp = &(*fieldp)->next;
1338                 }
1339         } while (tmp);
1340         (*fieldp)->name = strdup(str);
1341         if ((*fieldp)->name == NULL)
1342                 return -ENOMEM;
1343         if (*str != '[')
1344                 goodname = (*fieldp)->name;
1345         pr_debug("%s(%d)\n", (*fieldp)->name, (*fieldp)->ref);
1346
1347         /* If no name is specified, set the last field name (not array index)*/
1348         if (!arg->name) {
1349                 arg->name = strdup(goodname);
1350                 if (arg->name == NULL)
1351                         return -ENOMEM;
1352         }
1353         return 0;
1354 }
1355
1356 /* Parse perf-probe event command */
1357 int parse_perf_probe_command(const char *cmd, struct perf_probe_event *pev)
1358 {
1359         char **argv;
1360         int argc, i, ret = 0;
1361
1362         argv = argv_split(cmd, &argc);
1363         if (!argv) {
1364                 pr_debug("Failed to split arguments.\n");
1365                 return -ENOMEM;
1366         }
1367         if (argc - 1 > MAX_PROBE_ARGS) {
1368                 semantic_error("Too many probe arguments (%d).\n", argc - 1);
1369                 ret = -ERANGE;
1370                 goto out;
1371         }
1372         /* Parse probe point */
1373         ret = parse_perf_probe_point(argv[0], pev);
1374         if (ret < 0)
1375                 goto out;
1376
1377         /* Copy arguments and ensure return probe has no C argument */
1378         pev->nargs = argc - 1;
1379         pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1380         if (pev->args == NULL) {
1381                 ret = -ENOMEM;
1382                 goto out;
1383         }
1384         for (i = 0; i < pev->nargs && ret >= 0; i++) {
1385                 ret = parse_perf_probe_arg(argv[i + 1], &pev->args[i]);
1386                 if (ret >= 0 &&
1387                     is_c_varname(pev->args[i].var) && pev->point.retprobe) {
1388                         semantic_error("You can't specify local variable for"
1389                                        " kretprobe.\n");
1390                         ret = -EINVAL;
1391                 }
1392         }
1393 out:
1394         argv_free(argv);
1395
1396         return ret;
1397 }
1398
1399 /* Return true if this perf_probe_event requires debuginfo */
1400 bool perf_probe_event_need_dwarf(struct perf_probe_event *pev)
1401 {
1402         int i;
1403
1404         if (pev->point.file || pev->point.line || pev->point.lazy_line)
1405                 return true;
1406
1407         for (i = 0; i < pev->nargs; i++)
1408                 if (is_c_varname(pev->args[i].var))
1409                         return true;
1410
1411         return false;
1412 }
1413
1414 /* Parse probe_events event into struct probe_point */
1415 static int parse_probe_trace_command(const char *cmd,
1416                                      struct probe_trace_event *tev)
1417 {
1418         struct probe_trace_point *tp = &tev->point;
1419         char pr;
1420         char *p;
1421         char *argv0_str = NULL, *fmt, *fmt1_str, *fmt2_str, *fmt3_str;
1422         int ret, i, argc;
1423         char **argv;
1424
1425         pr_debug("Parsing probe_events: %s\n", cmd);
1426         argv = argv_split(cmd, &argc);
1427         if (!argv) {
1428                 pr_debug("Failed to split arguments.\n");
1429                 return -ENOMEM;
1430         }
1431         if (argc < 2) {
1432                 semantic_error("Too few probe arguments.\n");
1433                 ret = -ERANGE;
1434                 goto out;
1435         }
1436
1437         /* Scan event and group name. */
1438         argv0_str = strdup(argv[0]);
1439         if (argv0_str == NULL) {
1440                 ret = -ENOMEM;
1441                 goto out;
1442         }
1443         fmt1_str = strtok_r(argv0_str, ":", &fmt);
1444         fmt2_str = strtok_r(NULL, "/", &fmt);
1445         fmt3_str = strtok_r(NULL, " \t", &fmt);
1446         if (fmt1_str == NULL || strlen(fmt1_str) != 1 || fmt2_str == NULL
1447             || fmt3_str == NULL) {
1448                 semantic_error("Failed to parse event name: %s\n", argv[0]);
1449                 ret = -EINVAL;
1450                 goto out;
1451         }
1452         pr = fmt1_str[0];
1453         tev->group = strdup(fmt2_str);
1454         tev->event = strdup(fmt3_str);
1455         if (tev->group == NULL || tev->event == NULL) {
1456                 ret = -ENOMEM;
1457                 goto out;
1458         }
1459         pr_debug("Group:%s Event:%s probe:%c\n", tev->group, tev->event, pr);
1460
1461         tp->retprobe = (pr == 'r');
1462
1463         /* Scan module name(if there), function name and offset */
1464         p = strchr(argv[1], ':');
1465         if (p) {
1466                 tp->module = strndup(argv[1], p - argv[1]);
1467                 p++;
1468         } else
1469                 p = argv[1];
1470         fmt1_str = strtok_r(p, "+", &fmt);
1471         if (fmt1_str[0] == '0') /* only the address started with 0x */
1472                 tp->address = strtoul(fmt1_str, NULL, 0);
1473         else {
1474                 /* Only the symbol-based probe has offset */
1475                 tp->symbol = strdup(fmt1_str);
1476                 if (tp->symbol == NULL) {
1477                         ret = -ENOMEM;
1478                         goto out;
1479                 }
1480                 fmt2_str = strtok_r(NULL, "", &fmt);
1481                 if (fmt2_str == NULL)
1482                         tp->offset = 0;
1483                 else
1484                         tp->offset = strtoul(fmt2_str, NULL, 10);
1485         }
1486
1487         tev->nargs = argc - 2;
1488         tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
1489         if (tev->args == NULL) {
1490                 ret = -ENOMEM;
1491                 goto out;
1492         }
1493         for (i = 0; i < tev->nargs; i++) {
1494                 p = strchr(argv[i + 2], '=');
1495                 if (p)  /* We don't need which register is assigned. */
1496                         *p++ = '\0';
1497                 else
1498                         p = argv[i + 2];
1499                 tev->args[i].name = strdup(argv[i + 2]);
1500                 /* TODO: parse regs and offset */
1501                 tev->args[i].value = strdup(p);
1502                 if (tev->args[i].name == NULL || tev->args[i].value == NULL) {
1503                         ret = -ENOMEM;
1504                         goto out;
1505                 }
1506         }
1507         ret = 0;
1508 out:
1509         free(argv0_str);
1510         argv_free(argv);
1511         return ret;
1512 }
1513
1514 /* Compose only probe arg */
1515 int synthesize_perf_probe_arg(struct perf_probe_arg *pa, char *buf, size_t len)
1516 {
1517         struct perf_probe_arg_field *field = pa->field;
1518         int ret;
1519         char *tmp = buf;
1520
1521         if (pa->name && pa->var)
1522                 ret = e_snprintf(tmp, len, "%s=%s", pa->name, pa->var);
1523         else
1524                 ret = e_snprintf(tmp, len, "%s", pa->name ? pa->name : pa->var);
1525         if (ret <= 0)
1526                 goto error;
1527         tmp += ret;
1528         len -= ret;
1529
1530         while (field) {
1531                 if (field->name[0] == '[')
1532                         ret = e_snprintf(tmp, len, "%s", field->name);
1533                 else
1534                         ret = e_snprintf(tmp, len, "%s%s",
1535                                          field->ref ? "->" : ".", field->name);
1536                 if (ret <= 0)
1537                         goto error;
1538                 tmp += ret;
1539                 len -= ret;
1540                 field = field->next;
1541         }
1542
1543         if (pa->type) {
1544                 ret = e_snprintf(tmp, len, ":%s", pa->type);
1545                 if (ret <= 0)
1546                         goto error;
1547                 tmp += ret;
1548                 len -= ret;
1549         }
1550
1551         return tmp - buf;
1552 error:
1553         pr_debug("Failed to synthesize perf probe argument: %d\n", ret);
1554         return ret;
1555 }
1556
1557 /* Compose only probe point (not argument) */
1558 static char *synthesize_perf_probe_point(struct perf_probe_point *pp)
1559 {
1560         char *buf, *tmp;
1561         char offs[32] = "", line[32] = "", file[32] = "";
1562         int ret, len;
1563
1564         buf = zalloc(MAX_CMDLEN);
1565         if (buf == NULL) {
1566                 ret = -ENOMEM;
1567                 goto error;
1568         }
1569         if (pp->offset) {
1570                 ret = e_snprintf(offs, 32, "+%lu", pp->offset);
1571                 if (ret <= 0)
1572                         goto error;
1573         }
1574         if (pp->line) {
1575                 ret = e_snprintf(line, 32, ":%d", pp->line);
1576                 if (ret <= 0)
1577                         goto error;
1578         }
1579         if (pp->file) {
1580                 tmp = pp->file;
1581                 len = strlen(tmp);
1582                 if (len > 30) {
1583                         tmp = strchr(pp->file + len - 30, '/');
1584                         tmp = tmp ? tmp + 1 : pp->file + len - 30;
1585                 }
1586                 ret = e_snprintf(file, 32, "@%s", tmp);
1587                 if (ret <= 0)
1588                         goto error;
1589         }
1590
1591         if (pp->function)
1592                 ret = e_snprintf(buf, MAX_CMDLEN, "%s%s%s%s%s", pp->function,
1593                                  offs, pp->retprobe ? "%return" : "", line,
1594                                  file);
1595         else
1596                 ret = e_snprintf(buf, MAX_CMDLEN, "%s%s", file, line);
1597         if (ret <= 0)
1598                 goto error;
1599
1600         return buf;
1601 error:
1602         pr_debug("Failed to synthesize perf probe point: %d\n", ret);
1603         free(buf);
1604         return NULL;
1605 }
1606
1607 #if 0
1608 char *synthesize_perf_probe_command(struct perf_probe_event *pev)
1609 {
1610         char *buf;
1611         int i, len, ret;
1612
1613         buf = synthesize_perf_probe_point(&pev->point);
1614         if (!buf)
1615                 return NULL;
1616
1617         len = strlen(buf);
1618         for (i = 0; i < pev->nargs; i++) {
1619                 ret = e_snprintf(&buf[len], MAX_CMDLEN - len, " %s",
1620                                  pev->args[i].name);
1621                 if (ret <= 0) {
1622                         free(buf);
1623                         return NULL;
1624                 }
1625                 len += ret;
1626         }
1627
1628         return buf;
1629 }
1630 #endif
1631
1632 static int __synthesize_probe_trace_arg_ref(struct probe_trace_arg_ref *ref,
1633                                              char **buf, size_t *buflen,
1634                                              int depth)
1635 {
1636         int ret;
1637         if (ref->next) {
1638                 depth = __synthesize_probe_trace_arg_ref(ref->next, buf,
1639                                                          buflen, depth + 1);
1640                 if (depth < 0)
1641                         goto out;
1642         }
1643
1644         ret = e_snprintf(*buf, *buflen, "%+ld(", ref->offset);
1645         if (ret < 0)
1646                 depth = ret;
1647         else {
1648                 *buf += ret;
1649                 *buflen -= ret;
1650         }
1651 out:
1652         return depth;
1653
1654 }
1655
1656 static int synthesize_probe_trace_arg(struct probe_trace_arg *arg,
1657                                        char *buf, size_t buflen)
1658 {
1659         struct probe_trace_arg_ref *ref = arg->ref;
1660         int ret, depth = 0;
1661         char *tmp = buf;
1662
1663         /* Argument name or separator */
1664         if (arg->name)
1665                 ret = e_snprintf(buf, buflen, " %s=", arg->name);
1666         else
1667                 ret = e_snprintf(buf, buflen, " ");
1668         if (ret < 0)
1669                 return ret;
1670         buf += ret;
1671         buflen -= ret;
1672
1673         /* Special case: @XXX */
1674         if (arg->value[0] == '@' && arg->ref)
1675                         ref = ref->next;
1676
1677         /* Dereferencing arguments */
1678         if (ref) {
1679                 depth = __synthesize_probe_trace_arg_ref(ref, &buf,
1680                                                           &buflen, 1);
1681                 if (depth < 0)
1682                         return depth;
1683         }
1684
1685         /* Print argument value */
1686         if (arg->value[0] == '@' && arg->ref)
1687                 ret = e_snprintf(buf, buflen, "%s%+ld", arg->value,
1688                                  arg->ref->offset);
1689         else
1690                 ret = e_snprintf(buf, buflen, "%s", arg->value);
1691         if (ret < 0)
1692                 return ret;
1693         buf += ret;
1694         buflen -= ret;
1695
1696         /* Closing */
1697         while (depth--) {
1698                 ret = e_snprintf(buf, buflen, ")");
1699                 if (ret < 0)
1700                         return ret;
1701                 buf += ret;
1702                 buflen -= ret;
1703         }
1704         /* Print argument type */
1705         if (arg->type) {
1706                 ret = e_snprintf(buf, buflen, ":%s", arg->type);
1707                 if (ret <= 0)
1708                         return ret;
1709                 buf += ret;
1710         }
1711
1712         return buf - tmp;
1713 }
1714
1715 char *synthesize_probe_trace_command(struct probe_trace_event *tev)
1716 {
1717         struct probe_trace_point *tp = &tev->point;
1718         char *buf;
1719         int i, len, ret;
1720
1721         buf = zalloc(MAX_CMDLEN);
1722         if (buf == NULL)
1723                 return NULL;
1724
1725         len = e_snprintf(buf, MAX_CMDLEN, "%c:%s/%s ", tp->retprobe ? 'r' : 'p',
1726                          tev->group, tev->event);
1727         if (len <= 0)
1728                 goto error;
1729
1730         /* Uprobes must have tp->address and tp->module */
1731         if (tev->uprobes && (!tp->address || !tp->module))
1732                 goto error;
1733
1734         /* Use the tp->address for uprobes */
1735         if (tev->uprobes)
1736                 ret = e_snprintf(buf + len, MAX_CMDLEN - len, "%s:0x%lx",
1737                                  tp->module, tp->address);
1738         else
1739                 ret = e_snprintf(buf + len, MAX_CMDLEN - len, "%s%s%s+%lu",
1740                                  tp->module ?: "", tp->module ? ":" : "",
1741                                  tp->symbol, tp->offset);
1742
1743         if (ret <= 0)
1744                 goto error;
1745         len += ret;
1746
1747         for (i = 0; i < tev->nargs; i++) {
1748                 ret = synthesize_probe_trace_arg(&tev->args[i], buf + len,
1749                                                   MAX_CMDLEN - len);
1750                 if (ret <= 0)
1751                         goto error;
1752                 len += ret;
1753         }
1754
1755         return buf;
1756 error:
1757         free(buf);
1758         return NULL;
1759 }
1760
1761 static int find_perf_probe_point_from_map(struct probe_trace_point *tp,
1762                                           struct perf_probe_point *pp,
1763                                           bool is_kprobe)
1764 {
1765         struct symbol *sym = NULL;
1766         struct map *map;
1767         u64 addr;
1768         int ret = -ENOENT;
1769
1770         if (!is_kprobe) {
1771                 map = dso__new_map(tp->module);
1772                 if (!map)
1773                         goto out;
1774                 addr = tp->address;
1775                 sym = map__find_symbol(map, addr, NULL);
1776         } else {
1777                 addr = kernel_get_symbol_address_by_name(tp->symbol, true);
1778                 if (addr) {
1779                         addr += tp->offset;
1780                         sym = __find_kernel_function(addr, &map);
1781                 }
1782         }
1783         if (!sym)
1784                 goto out;
1785
1786         pp->retprobe = tp->retprobe;
1787         pp->offset = addr - map->unmap_ip(map, sym->start);
1788         pp->function = strdup(sym->name);
1789         ret = pp->function ? 0 : -ENOMEM;
1790
1791 out:
1792         if (map && !is_kprobe) {
1793                 map__delete(map);
1794         }
1795
1796         return ret;
1797 }
1798
1799 static int convert_to_perf_probe_point(struct probe_trace_point *tp,
1800                                         struct perf_probe_point *pp,
1801                                         bool is_kprobe)
1802 {
1803         char buf[128];
1804         int ret;
1805
1806         ret = find_perf_probe_point_from_dwarf(tp, pp, is_kprobe);
1807         if (!ret)
1808                 return 0;
1809         ret = find_perf_probe_point_from_map(tp, pp, is_kprobe);
1810         if (!ret)
1811                 return 0;
1812
1813         pr_debug("Failed to find probe point from both of dwarf and map.\n");
1814
1815         if (tp->symbol) {
1816                 pp->function = strdup(tp->symbol);
1817                 pp->offset = tp->offset;
1818         } else if (!tp->module && !is_kprobe) {
1819                 ret = e_snprintf(buf, 128, "0x%" PRIx64, (u64)tp->address);
1820                 if (ret < 0)
1821                         return ret;
1822                 pp->function = strdup(buf);
1823                 pp->offset = 0;
1824         }
1825         if (pp->function == NULL)
1826                 return -ENOMEM;
1827
1828         pp->retprobe = tp->retprobe;
1829
1830         return 0;
1831 }
1832
1833 static int convert_to_perf_probe_event(struct probe_trace_event *tev,
1834                                struct perf_probe_event *pev, bool is_kprobe)
1835 {
1836         char buf[64] = "";
1837         int i, ret;
1838
1839         /* Convert event/group name */
1840         pev->event = strdup(tev->event);
1841         pev->group = strdup(tev->group);
1842         if (pev->event == NULL || pev->group == NULL)
1843                 return -ENOMEM;
1844
1845         /* Convert trace_point to probe_point */
1846         ret = convert_to_perf_probe_point(&tev->point, &pev->point, is_kprobe);
1847         if (ret < 0)
1848                 return ret;
1849
1850         /* Convert trace_arg to probe_arg */
1851         pev->nargs = tev->nargs;
1852         pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1853         if (pev->args == NULL)
1854                 return -ENOMEM;
1855         for (i = 0; i < tev->nargs && ret >= 0; i++) {
1856                 if (tev->args[i].name)
1857                         pev->args[i].name = strdup(tev->args[i].name);
1858                 else {
1859                         ret = synthesize_probe_trace_arg(&tev->args[i],
1860                                                           buf, 64);
1861                         pev->args[i].name = strdup(buf);
1862                 }
1863                 if (pev->args[i].name == NULL && ret >= 0)
1864                         ret = -ENOMEM;
1865         }
1866
1867         if (ret < 0)
1868                 clear_perf_probe_event(pev);
1869
1870         return ret;
1871 }
1872
1873 void clear_perf_probe_event(struct perf_probe_event *pev)
1874 {
1875         struct perf_probe_arg_field *field, *next;
1876         int i;
1877
1878         free(pev->event);
1879         free(pev->group);
1880         free(pev->target);
1881         clear_perf_probe_point(&pev->point);
1882
1883         for (i = 0; i < pev->nargs; i++) {
1884                 free(pev->args[i].name);
1885                 free(pev->args[i].var);
1886                 free(pev->args[i].type);
1887                 field = pev->args[i].field;
1888                 while (field) {
1889                         next = field->next;
1890                         zfree(&field->name);
1891                         free(field);
1892                         field = next;
1893                 }
1894         }
1895         free(pev->args);
1896         memset(pev, 0, sizeof(*pev));
1897 }
1898
1899 static void clear_probe_trace_event(struct probe_trace_event *tev)
1900 {
1901         struct probe_trace_arg_ref *ref, *next;
1902         int i;
1903
1904         free(tev->event);
1905         free(tev->group);
1906         free(tev->point.symbol);
1907         free(tev->point.realname);
1908         free(tev->point.module);
1909         for (i = 0; i < tev->nargs; i++) {
1910                 free(tev->args[i].name);
1911                 free(tev->args[i].value);
1912                 free(tev->args[i].type);
1913                 ref = tev->args[i].ref;
1914                 while (ref) {
1915                         next = ref->next;
1916                         free(ref);
1917                         ref = next;
1918                 }
1919         }
1920         free(tev->args);
1921         memset(tev, 0, sizeof(*tev));
1922 }
1923
1924 static void print_open_warning(int err, bool is_kprobe)
1925 {
1926         char sbuf[STRERR_BUFSIZE];
1927
1928         if (err == -ENOENT) {
1929                 const char *config;
1930
1931                 if (!is_kprobe)
1932                         config = "CONFIG_UPROBE_EVENTS";
1933                 else
1934                         config = "CONFIG_KPROBE_EVENTS";
1935
1936                 pr_warning("%cprobe_events file does not exist"
1937                            " - please rebuild kernel with %s.\n",
1938                            is_kprobe ? 'k' : 'u', config);
1939         } else if (err == -ENOTSUP)
1940                 pr_warning("Tracefs or debugfs is not mounted.\n");
1941         else
1942                 pr_warning("Failed to open %cprobe_events: %s\n",
1943                            is_kprobe ? 'k' : 'u',
1944                            strerror_r(-err, sbuf, sizeof(sbuf)));
1945 }
1946
1947 static void print_both_open_warning(int kerr, int uerr)
1948 {
1949         /* Both kprobes and uprobes are disabled, warn it. */
1950         if (kerr == -ENOTSUP && uerr == -ENOTSUP)
1951                 pr_warning("Tracefs or debugfs is not mounted.\n");
1952         else if (kerr == -ENOENT && uerr == -ENOENT)
1953                 pr_warning("Please rebuild kernel with CONFIG_KPROBE_EVENTS "
1954                            "or/and CONFIG_UPROBE_EVENTS.\n");
1955         else {
1956                 char sbuf[STRERR_BUFSIZE];
1957                 pr_warning("Failed to open kprobe events: %s.\n",
1958                            strerror_r(-kerr, sbuf, sizeof(sbuf)));
1959                 pr_warning("Failed to open uprobe events: %s.\n",
1960                            strerror_r(-uerr, sbuf, sizeof(sbuf)));
1961         }
1962 }
1963
1964 static int open_probe_events(const char *trace_file, bool readwrite)
1965 {
1966         char buf[PATH_MAX];
1967         const char *__debugfs;
1968         const char *tracing_dir = "";
1969         int ret;
1970
1971         __debugfs = tracefs_find_mountpoint();
1972         if (__debugfs == NULL) {
1973                 tracing_dir = "tracing/";
1974
1975                 __debugfs = debugfs_find_mountpoint();
1976                 if (__debugfs == NULL)
1977                         return -ENOTSUP;
1978         }
1979
1980         ret = e_snprintf(buf, PATH_MAX, "%s/%s%s",
1981                          __debugfs, tracing_dir, trace_file);
1982         if (ret >= 0) {
1983                 pr_debug("Opening %s write=%d\n", buf, readwrite);
1984                 if (readwrite && !probe_event_dry_run)
1985                         ret = open(buf, O_RDWR | O_APPEND, 0);
1986                 else
1987                         ret = open(buf, O_RDONLY, 0);
1988
1989                 if (ret < 0)
1990                         ret = -errno;
1991         }
1992         return ret;
1993 }
1994
1995 static int open_kprobe_events(bool readwrite)
1996 {
1997         return open_probe_events("kprobe_events", readwrite);
1998 }
1999
2000 static int open_uprobe_events(bool readwrite)
2001 {
2002         return open_probe_events("uprobe_events", readwrite);
2003 }
2004
2005 /* Get raw string list of current kprobe_events  or uprobe_events */
2006 static struct strlist *get_probe_trace_command_rawlist(int fd)
2007 {
2008         int ret, idx;
2009         FILE *fp;
2010         char buf[MAX_CMDLEN];
2011         char *p;
2012         struct strlist *sl;
2013
2014         sl = strlist__new(true, NULL);
2015
2016         fp = fdopen(dup(fd), "r");
2017         while (!feof(fp)) {
2018                 p = fgets(buf, MAX_CMDLEN, fp);
2019                 if (!p)
2020                         break;
2021
2022                 idx = strlen(p) - 1;
2023                 if (p[idx] == '\n')
2024                         p[idx] = '\0';
2025                 ret = strlist__add(sl, buf);
2026                 if (ret < 0) {
2027                         pr_debug("strlist__add failed (%d)\n", ret);
2028                         strlist__delete(sl);
2029                         return NULL;
2030                 }
2031         }
2032         fclose(fp);
2033
2034         return sl;
2035 }
2036
2037 struct kprobe_blacklist_node {
2038         struct list_head list;
2039         unsigned long start;
2040         unsigned long end;
2041         char *symbol;
2042 };
2043
2044 static void kprobe_blacklist__delete(struct list_head *blacklist)
2045 {
2046         struct kprobe_blacklist_node *node;
2047
2048         while (!list_empty(blacklist)) {
2049                 node = list_first_entry(blacklist,
2050                                         struct kprobe_blacklist_node, list);
2051                 list_del(&node->list);
2052                 free(node->symbol);
2053                 free(node);
2054         }
2055 }
2056
2057 static int kprobe_blacklist__load(struct list_head *blacklist)
2058 {
2059         struct kprobe_blacklist_node *node;
2060         const char *__debugfs = debugfs_find_mountpoint();
2061         char buf[PATH_MAX], *p;
2062         FILE *fp;
2063         int ret;
2064
2065         if (__debugfs == NULL)
2066                 return -ENOTSUP;
2067
2068         ret = e_snprintf(buf, PATH_MAX, "%s/kprobes/blacklist", __debugfs);
2069         if (ret < 0)
2070                 return ret;
2071
2072         fp = fopen(buf, "r");
2073         if (!fp)
2074                 return -errno;
2075
2076         ret = 0;
2077         while (fgets(buf, PATH_MAX, fp)) {
2078                 node = zalloc(sizeof(*node));
2079                 if (!node) {
2080                         ret = -ENOMEM;
2081                         break;
2082                 }
2083                 INIT_LIST_HEAD(&node->list);
2084                 list_add_tail(&node->list, blacklist);
2085                 if (sscanf(buf, "0x%lx-0x%lx", &node->start, &node->end) != 2) {
2086                         ret = -EINVAL;
2087                         break;
2088                 }
2089                 p = strchr(buf, '\t');
2090                 if (p) {
2091                         p++;
2092                         if (p[strlen(p) - 1] == '\n')
2093                                 p[strlen(p) - 1] = '\0';
2094                 } else
2095                         p = (char *)"unknown";
2096                 node->symbol = strdup(p);
2097                 if (!node->symbol) {
2098                         ret = -ENOMEM;
2099                         break;
2100                 }
2101                 pr_debug2("Blacklist: 0x%lx-0x%lx, %s\n",
2102                           node->start, node->end, node->symbol);
2103                 ret++;
2104         }
2105         if (ret < 0)
2106                 kprobe_blacklist__delete(blacklist);
2107         fclose(fp);
2108
2109         return ret;
2110 }
2111
2112 static struct kprobe_blacklist_node *
2113 kprobe_blacklist__find_by_address(struct list_head *blacklist,
2114                                   unsigned long address)
2115 {
2116         struct kprobe_blacklist_node *node;
2117
2118         list_for_each_entry(node, blacklist, list) {
2119                 if (node->start <= address && address <= node->end)
2120                         return node;
2121         }
2122
2123         return NULL;
2124 }
2125
2126 /* Show an event */
2127 static int show_perf_probe_event(struct perf_probe_event *pev,
2128                                  const char *module)
2129 {
2130         int i, ret;
2131         char buf[128];
2132         char *place;
2133
2134         /* Synthesize only event probe point */
2135         place = synthesize_perf_probe_point(&pev->point);
2136         if (!place)
2137                 return -EINVAL;
2138
2139         ret = e_snprintf(buf, 128, "%s:%s", pev->group, pev->event);
2140         if (ret < 0)
2141                 return ret;
2142
2143         pr_info("  %-20s (on %s", buf, place);
2144         if (module)
2145                 pr_info(" in %s", module);
2146
2147         if (pev->nargs > 0) {
2148                 pr_info(" with");
2149                 for (i = 0; i < pev->nargs; i++) {
2150                         ret = synthesize_perf_probe_arg(&pev->args[i],
2151                                                         buf, 128);
2152                         if (ret < 0)
2153                                 break;
2154                         pr_info(" %s", buf);
2155                 }
2156         }
2157         pr_info(")\n");
2158         free(place);
2159         return ret;
2160 }
2161
2162 static bool filter_probe_trace_event(struct probe_trace_event *tev,
2163                                      struct strfilter *filter)
2164 {
2165         char tmp[128];
2166
2167         /* At first, check the event name itself */
2168         if (strfilter__compare(filter, tev->event))
2169                 return true;
2170
2171         /* Next, check the combination of name and group */
2172         if (e_snprintf(tmp, 128, "%s:%s", tev->group, tev->event) < 0)
2173                 return false;
2174         return strfilter__compare(filter, tmp);
2175 }
2176
2177 static int __show_perf_probe_events(int fd, bool is_kprobe,
2178                                     struct strfilter *filter)
2179 {
2180         int ret = 0;
2181         struct probe_trace_event tev;
2182         struct perf_probe_event pev;
2183         struct strlist *rawlist;
2184         struct str_node *ent;
2185
2186         memset(&tev, 0, sizeof(tev));
2187         memset(&pev, 0, sizeof(pev));
2188
2189         rawlist = get_probe_trace_command_rawlist(fd);
2190         if (!rawlist)
2191                 return -ENOMEM;
2192
2193         strlist__for_each(ent, rawlist) {
2194                 ret = parse_probe_trace_command(ent->s, &tev);
2195                 if (ret >= 0) {
2196                         if (!filter_probe_trace_event(&tev, filter))
2197                                 goto next;
2198                         ret = convert_to_perf_probe_event(&tev, &pev,
2199                                                                 is_kprobe);
2200                         if (ret >= 0)
2201                                 ret = show_perf_probe_event(&pev,
2202                                                             tev.point.module);
2203                 }
2204 next:
2205                 clear_perf_probe_event(&pev);
2206                 clear_probe_trace_event(&tev);
2207                 if (ret < 0)
2208                         break;
2209         }
2210         strlist__delete(rawlist);
2211
2212         return ret;
2213 }
2214
2215 /* List up current perf-probe events */
2216 int show_perf_probe_events(struct strfilter *filter)
2217 {
2218         int kp_fd, up_fd, ret;
2219
2220         setup_pager();
2221
2222         ret = init_symbol_maps(false);
2223         if (ret < 0)
2224                 return ret;
2225
2226         kp_fd = open_kprobe_events(false);
2227         if (kp_fd >= 0) {
2228                 ret = __show_perf_probe_events(kp_fd, true, filter);
2229                 close(kp_fd);
2230                 if (ret < 0)
2231                         goto out;
2232         }
2233
2234         up_fd = open_uprobe_events(false);
2235         if (kp_fd < 0 && up_fd < 0) {
2236                 print_both_open_warning(kp_fd, up_fd);
2237                 ret = kp_fd;
2238                 goto out;
2239         }
2240
2241         if (up_fd >= 0) {
2242                 ret = __show_perf_probe_events(up_fd, false, filter);
2243                 close(up_fd);
2244         }
2245 out:
2246         exit_symbol_maps();
2247         return ret;
2248 }
2249
2250 /* Get current perf-probe event names */
2251 static struct strlist *get_probe_trace_event_names(int fd, bool include_group)
2252 {
2253         char buf[128];
2254         struct strlist *sl, *rawlist;
2255         struct str_node *ent;
2256         struct probe_trace_event tev;
2257         int ret = 0;
2258
2259         memset(&tev, 0, sizeof(tev));
2260         rawlist = get_probe_trace_command_rawlist(fd);
2261         if (!rawlist)
2262                 return NULL;
2263         sl = strlist__new(true, NULL);
2264         strlist__for_each(ent, rawlist) {
2265                 ret = parse_probe_trace_command(ent->s, &tev);
2266                 if (ret < 0)
2267                         break;
2268                 if (include_group) {
2269                         ret = e_snprintf(buf, 128, "%s:%s", tev.group,
2270                                         tev.event);
2271                         if (ret >= 0)
2272                                 ret = strlist__add(sl, buf);
2273                 } else
2274                         ret = strlist__add(sl, tev.event);
2275                 clear_probe_trace_event(&tev);
2276                 if (ret < 0)
2277                         break;
2278         }
2279         strlist__delete(rawlist);
2280
2281         if (ret < 0) {
2282                 strlist__delete(sl);
2283                 return NULL;
2284         }
2285         return sl;
2286 }
2287
2288 static int write_probe_trace_event(int fd, struct probe_trace_event *tev)
2289 {
2290         int ret = 0;
2291         char *buf = synthesize_probe_trace_command(tev);
2292         char sbuf[STRERR_BUFSIZE];
2293
2294         if (!buf) {
2295                 pr_debug("Failed to synthesize probe trace event.\n");
2296                 return -EINVAL;
2297         }
2298
2299         pr_debug("Writing event: %s\n", buf);
2300         if (!probe_event_dry_run) {
2301                 ret = write(fd, buf, strlen(buf));
2302                 if (ret <= 0) {
2303                         ret = -errno;
2304                         pr_warning("Failed to write event: %s\n",
2305                                    strerror_r(errno, sbuf, sizeof(sbuf)));
2306                 }
2307         }
2308         free(buf);
2309         return ret;
2310 }
2311
2312 static int get_new_event_name(char *buf, size_t len, const char *base,
2313                               struct strlist *namelist, bool allow_suffix)
2314 {
2315         int i, ret;
2316
2317         if (*base == '.')
2318                 base++;
2319
2320         /* Try no suffix */
2321         ret = e_snprintf(buf, len, "%s", base);
2322         if (ret < 0) {
2323                 pr_debug("snprintf() failed: %d\n", ret);
2324                 return ret;
2325         }
2326         if (!strlist__has_entry(namelist, buf))
2327                 return 0;
2328
2329         if (!allow_suffix) {
2330                 pr_warning("Error: event \"%s\" already exists. "
2331                            "(Use -f to force duplicates.)\n", base);
2332                 return -EEXIST;
2333         }
2334
2335         /* Try to add suffix */
2336         for (i = 1; i < MAX_EVENT_INDEX; i++) {
2337                 ret = e_snprintf(buf, len, "%s_%d", base, i);
2338                 if (ret < 0) {
2339                         pr_debug("snprintf() failed: %d\n", ret);
2340                         return ret;
2341                 }
2342                 if (!strlist__has_entry(namelist, buf))
2343                         break;
2344         }
2345         if (i == MAX_EVENT_INDEX) {
2346                 pr_warning("Too many events are on the same function.\n");
2347                 ret = -ERANGE;
2348         }
2349
2350         return ret;
2351 }
2352
2353 /* Warn if the current kernel's uprobe implementation is old */
2354 static void warn_uprobe_event_compat(struct probe_trace_event *tev)
2355 {
2356         int i;
2357         char *buf = synthesize_probe_trace_command(tev);
2358
2359         /* Old uprobe event doesn't support memory dereference */
2360         if (!tev->uprobes || tev->nargs == 0 || !buf)
2361                 goto out;
2362
2363         for (i = 0; i < tev->nargs; i++)
2364                 if (strglobmatch(tev->args[i].value, "[$@+-]*")) {
2365                         pr_warning("Please upgrade your kernel to at least "
2366                                    "3.14 to have access to feature %s\n",
2367                                    tev->args[i].value);
2368                         break;
2369                 }
2370 out:
2371         free(buf);
2372 }
2373
2374 static int __add_probe_trace_events(struct perf_probe_event *pev,
2375                                      struct probe_trace_event *tevs,
2376                                      int ntevs, bool allow_suffix)
2377 {
2378         int i, fd, ret;
2379         struct probe_trace_event *tev = NULL;
2380         char buf[64];
2381         const char *event, *group;
2382         struct strlist *namelist;
2383         LIST_HEAD(blacklist);
2384         struct kprobe_blacklist_node *node;
2385         bool safename;
2386
2387         if (pev->uprobes)
2388                 fd = open_uprobe_events(true);
2389         else
2390                 fd = open_kprobe_events(true);
2391
2392         if (fd < 0) {
2393                 print_open_warning(fd, !pev->uprobes);
2394                 return fd;
2395         }
2396
2397         /* Get current event names */
2398         namelist = get_probe_trace_event_names(fd, false);
2399         if (!namelist) {
2400                 pr_debug("Failed to get current event list.\n");
2401                 ret = -ENOMEM;
2402                 goto close_out;
2403         }
2404         /* Get kprobe blacklist if exists */
2405         if (!pev->uprobes) {
2406                 ret = kprobe_blacklist__load(&blacklist);
2407                 if (ret < 0)
2408                         pr_debug("No kprobe blacklist support, ignored\n");
2409         }
2410
2411         safename = (pev->point.function && !strisglob(pev->point.function));
2412         ret = 0;
2413         pr_info("Added new event%s\n", (ntevs > 1) ? "s:" : ":");
2414         for (i = 0; i < ntevs; i++) {
2415                 tev = &tevs[i];
2416                 /* Skip if the symbol is out of .text (marked previously) */
2417                 if (!tev->point.symbol)
2418                         continue;
2419                 /* Ensure that the address is NOT blacklisted */
2420                 node = kprobe_blacklist__find_by_address(&blacklist,
2421                                                          tev->point.address);
2422                 if (node) {
2423                         pr_warning("Warning: Skipped probing on blacklisted function: %s\n", node->symbol);
2424                         continue;
2425                 }
2426
2427                 if (pev->event)
2428                         event = pev->event;
2429                 else
2430                         if (safename)
2431                                 event = pev->point.function;
2432                         else
2433                                 event = tev->point.realname;
2434                 if (pev->group)
2435                         group = pev->group;
2436                 else
2437                         group = PERFPROBE_GROUP;
2438
2439                 /* Get an unused new event name */
2440                 ret = get_new_event_name(buf, 64, event,
2441                                          namelist, allow_suffix);
2442                 if (ret < 0)
2443                         break;
2444                 event = buf;
2445
2446                 tev->event = strdup(event);
2447                 tev->group = strdup(group);
2448                 if (tev->event == NULL || tev->group == NULL) {
2449                         ret = -ENOMEM;
2450                         break;
2451                 }
2452                 ret = write_probe_trace_event(fd, tev);
2453                 if (ret < 0)
2454                         break;
2455                 /* Add added event name to namelist */
2456                 strlist__add(namelist, event);
2457
2458                 /* Trick here - save current event/group */
2459                 event = pev->event;
2460                 group = pev->group;
2461                 pev->event = tev->event;
2462                 pev->group = tev->group;
2463                 show_perf_probe_event(pev, tev->point.module);
2464                 /* Trick here - restore current event/group */
2465                 pev->event = (char *)event;
2466                 pev->group = (char *)group;
2467
2468                 /*
2469                  * Probes after the first probe which comes from same
2470                  * user input are always allowed to add suffix, because
2471                  * there might be several addresses corresponding to
2472                  * one code line.
2473                  */
2474                 allow_suffix = true;
2475         }
2476         if (ret == -EINVAL && pev->uprobes)
2477                 warn_uprobe_event_compat(tev);
2478
2479         /* Note that it is possible to skip all events because of blacklist */
2480         if (ret >= 0 && tev->event) {
2481                 /* Show how to use the event. */
2482                 pr_info("\nYou can now use it in all perf tools, such as:\n\n");
2483                 pr_info("\tperf record -e %s:%s -aR sleep 1\n\n", tev->group,
2484                          tev->event);
2485         }
2486
2487         kprobe_blacklist__delete(&blacklist);
2488         strlist__delete(namelist);
2489 close_out:
2490         close(fd);
2491         return ret;
2492 }
2493
2494 static int find_probe_functions(struct map *map, char *name)
2495 {
2496         int found = 0;
2497         struct symbol *sym;
2498         struct rb_node *tmp;
2499
2500         if (map__load(map, NULL) < 0)
2501                 return 0;
2502
2503         map__for_each_symbol(map, sym, tmp) {
2504                 if (strglobmatch(sym->name, name))
2505                         found++;
2506         }
2507
2508         return found;
2509 }
2510
2511 #define strdup_or_goto(str, label)      \
2512         ({ char *__p = strdup(str); if (!__p) goto label; __p; })
2513
2514 void __weak arch__fix_tev_from_maps(struct perf_probe_event *pev __maybe_unused,
2515                                 struct probe_trace_event *tev __maybe_unused,
2516                                 struct map *map __maybe_unused) { }
2517
2518 /*
2519  * Find probe function addresses from map.
2520  * Return an error or the number of found probe_trace_event
2521  */
2522 static int find_probe_trace_events_from_map(struct perf_probe_event *pev,
2523                                             struct probe_trace_event **tevs)
2524 {
2525         struct map *map = NULL;
2526         struct ref_reloc_sym *reloc_sym = NULL;
2527         struct symbol *sym;
2528         struct probe_trace_event *tev;
2529         struct perf_probe_point *pp = &pev->point;
2530         struct probe_trace_point *tp;
2531         int num_matched_functions;
2532         int ret, i;
2533
2534         map = get_target_map(pev->target, pev->uprobes);
2535         if (!map) {
2536                 ret = -EINVAL;
2537                 goto out;
2538         }
2539
2540         /*
2541          * Load matched symbols: Since the different local symbols may have
2542          * same name but different addresses, this lists all the symbols.
2543          */
2544         num_matched_functions = find_probe_functions(map, pp->function);
2545         if (num_matched_functions == 0) {
2546                 pr_err("Failed to find symbol %s in %s\n", pp->function,
2547                         pev->target ? : "kernel");
2548                 ret = -ENOENT;
2549                 goto out;
2550         } else if (num_matched_functions > probe_conf.max_probes) {
2551                 pr_err("Too many functions matched in %s\n",
2552                         pev->target ? : "kernel");
2553                 ret = -E2BIG;
2554                 goto out;
2555         }
2556
2557         if (!pev->uprobes && !pp->retprobe) {
2558                 reloc_sym = kernel_get_ref_reloc_sym();
2559                 if (!reloc_sym) {
2560                         pr_warning("Relocated base symbol is not found!\n");
2561                         ret = -EINVAL;
2562                         goto out;
2563                 }
2564         }
2565
2566         /* Setup result trace-probe-events */
2567         *tevs = zalloc(sizeof(*tev) * num_matched_functions);
2568         if (!*tevs) {
2569                 ret = -ENOMEM;
2570                 goto out;
2571         }
2572
2573         ret = 0;
2574
2575         map__for_each_symbol_by_name(map, pp->function, sym) {
2576                 tev = (*tevs) + ret;
2577                 tp = &tev->point;
2578                 if (ret == num_matched_functions) {
2579                         pr_warning("Too many symbols are listed. Skip it.\n");
2580                         break;
2581                 }
2582                 ret++;
2583
2584                 if (pp->offset > sym->end - sym->start) {
2585                         pr_warning("Offset %ld is bigger than the size of %s\n",
2586                                    pp->offset, sym->name);
2587                         ret = -ENOENT;
2588                         goto err_out;
2589                 }
2590                 /* Add one probe point */
2591                 tp->address = map->unmap_ip(map, sym->start) + pp->offset;
2592                 if (reloc_sym) {
2593                         tp->symbol = strdup_or_goto(reloc_sym->name, nomem_out);
2594                         tp->offset = tp->address - reloc_sym->addr;
2595                 } else {
2596                         tp->symbol = strdup_or_goto(sym->name, nomem_out);
2597                         tp->offset = pp->offset;
2598                 }
2599                 tp->retprobe = pp->retprobe;
2600                 if (pev->target)
2601                         tev->point.module = strdup_or_goto(pev->target,
2602                                                            nomem_out);
2603                 tev->uprobes = pev->uprobes;
2604                 tev->nargs = pev->nargs;
2605                 if (tev->nargs) {
2606                         tev->args = zalloc(sizeof(struct probe_trace_arg) *
2607                                            tev->nargs);
2608                         if (tev->args == NULL)
2609                                 goto nomem_out;
2610                 }
2611                 for (i = 0; i < tev->nargs; i++) {
2612                         if (pev->args[i].name)
2613                                 tev->args[i].name =
2614                                         strdup_or_goto(pev->args[i].name,
2615                                                         nomem_out);
2616
2617                         tev->args[i].value = strdup_or_goto(pev->args[i].var,
2618                                                             nomem_out);
2619                         if (pev->args[i].type)
2620                                 tev->args[i].type =
2621                                         strdup_or_goto(pev->args[i].type,
2622                                                         nomem_out);
2623                 }
2624                 arch__fix_tev_from_maps(pev, tev, map);
2625         }
2626
2627 out:
2628         put_target_map(map, pev->uprobes);
2629         return ret;
2630
2631 nomem_out:
2632         ret = -ENOMEM;
2633 err_out:
2634         clear_probe_trace_events(*tevs, num_matched_functions);
2635         zfree(tevs);
2636         goto out;
2637 }
2638
2639 bool __weak arch__prefers_symtab(void) { return false; }
2640
2641 static int convert_to_probe_trace_events(struct perf_probe_event *pev,
2642                                          struct probe_trace_event **tevs)
2643 {
2644         int ret;
2645
2646         if (pev->uprobes && !pev->group) {
2647                 /* Replace group name if not given */
2648                 ret = convert_exec_to_group(pev->target, &pev->group);
2649                 if (ret != 0) {
2650                         pr_warning("Failed to make a group name.\n");
2651                         return ret;
2652                 }
2653         }
2654
2655         if (arch__prefers_symtab() && !perf_probe_event_need_dwarf(pev)) {
2656                 ret = find_probe_trace_events_from_map(pev, tevs);
2657                 if (ret > 0)
2658                         return ret; /* Found in symbol table */
2659         }
2660
2661         /* Convert perf_probe_event with debuginfo */
2662         ret = try_to_find_probe_trace_events(pev, tevs);
2663         if (ret != 0)
2664                 return ret;     /* Found in debuginfo or got an error */
2665
2666         return find_probe_trace_events_from_map(pev, tevs);
2667 }
2668
2669 struct __event_package {
2670         struct perf_probe_event         *pev;
2671         struct probe_trace_event        *tevs;
2672         int                             ntevs;
2673 };
2674
2675 int add_perf_probe_events(struct perf_probe_event *pevs, int npevs)
2676 {
2677         int i, j, ret;
2678         struct __event_package *pkgs;
2679
2680         ret = 0;
2681         pkgs = zalloc(sizeof(struct __event_package) * npevs);
2682
2683         if (pkgs == NULL)
2684                 return -ENOMEM;
2685
2686         ret = init_symbol_maps(pevs->uprobes);
2687         if (ret < 0) {
2688                 free(pkgs);
2689                 return ret;
2690         }
2691
2692         /* Loop 1: convert all events */
2693         for (i = 0; i < npevs; i++) {
2694                 pkgs[i].pev = &pevs[i];
2695                 /* Convert with or without debuginfo */
2696                 ret  = convert_to_probe_trace_events(pkgs[i].pev,
2697                                                      &pkgs[i].tevs);
2698                 if (ret < 0)
2699                         goto end;
2700                 pkgs[i].ntevs = ret;
2701         }
2702
2703         /* Loop 2: add all events */
2704         for (i = 0; i < npevs; i++) {
2705                 ret = __add_probe_trace_events(pkgs[i].pev, pkgs[i].tevs,
2706                                                pkgs[i].ntevs,
2707                                                probe_conf.force_add);
2708                 if (ret < 0)
2709                         break;
2710         }
2711 end:
2712         /* Loop 3: cleanup and free trace events  */
2713         for (i = 0; i < npevs; i++) {
2714                 for (j = 0; j < pkgs[i].ntevs; j++)
2715                         clear_probe_trace_event(&pkgs[i].tevs[j]);
2716                 zfree(&pkgs[i].tevs);
2717         }
2718         free(pkgs);
2719         exit_symbol_maps();
2720
2721         return ret;
2722 }
2723
2724 static int __del_trace_probe_event(int fd, struct str_node *ent)
2725 {
2726         char *p;
2727         char buf[128];
2728         int ret;
2729
2730         /* Convert from perf-probe event to trace-probe event */
2731         ret = e_snprintf(buf, 128, "-:%s", ent->s);
2732         if (ret < 0)
2733                 goto error;
2734
2735         p = strchr(buf + 2, ':');
2736         if (!p) {
2737                 pr_debug("Internal error: %s should have ':' but not.\n",
2738                          ent->s);
2739                 ret = -ENOTSUP;
2740                 goto error;
2741         }
2742         *p = '/';
2743
2744         pr_debug("Writing event: %s\n", buf);
2745         ret = write(fd, buf, strlen(buf));
2746         if (ret < 0) {
2747                 ret = -errno;
2748                 goto error;
2749         }
2750
2751         pr_info("Removed event: %s\n", ent->s);
2752         return 0;
2753 error:
2754         pr_warning("Failed to delete event: %s\n",
2755                    strerror_r(-ret, buf, sizeof(buf)));
2756         return ret;
2757 }
2758
2759 static int del_trace_probe_events(int fd, struct strfilter *filter,
2760                                   struct strlist *namelist)
2761 {
2762         struct str_node *ent;
2763         const char *p;
2764         int ret = -ENOENT;
2765
2766         if (!namelist)
2767                 return -ENOENT;
2768
2769         strlist__for_each(ent, namelist) {
2770                 p = strchr(ent->s, ':');
2771                 if ((p && strfilter__compare(filter, p + 1)) ||
2772                     strfilter__compare(filter, ent->s)) {
2773                         ret = __del_trace_probe_event(fd, ent);
2774                         if (ret < 0)
2775                                 break;
2776                 }
2777         }
2778
2779         return ret;
2780 }
2781
2782 int del_perf_probe_events(struct strfilter *filter)
2783 {
2784         int ret, ret2, ufd = -1, kfd = -1;
2785         struct strlist *namelist = NULL, *unamelist = NULL;
2786         char *str = strfilter__string(filter);
2787
2788         if (!str)
2789                 return -EINVAL;
2790
2791         pr_debug("Delete filter: \'%s\'\n", str);
2792
2793         /* Get current event names */
2794         kfd = open_kprobe_events(true);
2795         if (kfd >= 0)
2796                 namelist = get_probe_trace_event_names(kfd, true);
2797
2798         ufd = open_uprobe_events(true);
2799         if (ufd >= 0)
2800                 unamelist = get_probe_trace_event_names(ufd, true);
2801
2802         if (kfd < 0 && ufd < 0) {
2803                 print_both_open_warning(kfd, ufd);
2804                 ret = kfd;
2805                 goto error;
2806         }
2807
2808         ret = del_trace_probe_events(kfd, filter, namelist);
2809         if (ret < 0 && ret != -ENOENT)
2810                 goto error;
2811
2812         ret2 = del_trace_probe_events(ufd, filter, unamelist);
2813         if (ret2 < 0 && ret2 != -ENOENT)
2814                 ret = ret2;
2815         else if (ret == -ENOENT && ret2 == -ENOENT) {
2816                 pr_debug("\"%s\" does not hit any event.\n", str);
2817                 /* Note that this is silently ignored */
2818                 ret = 0;
2819         }
2820
2821 error:
2822         if (kfd >= 0) {
2823                 strlist__delete(namelist);
2824                 close(kfd);
2825         }
2826
2827         if (ufd >= 0) {
2828                 strlist__delete(unamelist);
2829                 close(ufd);
2830         }
2831         free(str);
2832
2833         return ret;
2834 }
2835
2836 /* TODO: don't use a global variable for filter ... */
2837 static struct strfilter *available_func_filter;
2838
2839 /*
2840  * If a symbol corresponds to a function with global binding and
2841  * matches filter return 0. For all others return 1.
2842  */
2843 static int filter_available_functions(struct map *map __maybe_unused,
2844                                       struct symbol *sym)
2845 {
2846         if (strfilter__compare(available_func_filter, sym->name))
2847                 return 0;
2848         return 1;
2849 }
2850
2851 int show_available_funcs(const char *target, struct strfilter *_filter,
2852                                         bool user)
2853 {
2854         struct map *map;
2855         int ret;
2856
2857         ret = init_symbol_maps(user);
2858         if (ret < 0)
2859                 return ret;
2860
2861         /* Get a symbol map */
2862         if (user)
2863                 map = dso__new_map(target);
2864         else
2865                 map = kernel_get_module_map(target);
2866         if (!map) {
2867                 pr_err("Failed to get a map for %s\n", (target) ? : "kernel");
2868                 return -EINVAL;
2869         }
2870
2871         /* Load symbols with given filter */
2872         available_func_filter = _filter;
2873         if (map__load(map, filter_available_functions)) {
2874                 pr_err("Failed to load symbols in %s\n", (target) ? : "kernel");
2875                 goto end;
2876         }
2877         if (!dso__sorted_by_name(map->dso, map->type))
2878                 dso__sort_by_name(map->dso, map->type);
2879
2880         /* Show all (filtered) symbols */
2881         setup_pager();
2882         dso__fprintf_symbols_by_name(map->dso, map->type, stdout);
2883 end:
2884         if (user) {
2885                 map__delete(map);
2886         }
2887         exit_symbol_maps();
2888
2889         return ret;
2890 }
2891