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