ace3ba37c880af9cc677f457f0facc6aed04a57b
[linux-2.6-block.git] / tools / perf / util / probe-event.c
1 /*
2  * probe-event.c : perf-probe definition to probe_events format converter
3  *
4  * Written by Masami Hiramatsu <mhiramat@redhat.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19  *
20  */
21
22 #include <sys/utsname.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <stdarg.h>
32 #include <limits.h>
33 #include <elf.h>
34
35 #include "util.h"
36 #include "event.h"
37 #include "strlist.h"
38 #include "debug.h"
39 #include "cache.h"
40 #include "color.h"
41 #include "symbol.h"
42 #include "thread.h"
43 #include <api/fs/debugfs.h>
44 #include "trace-event.h"        /* For __maybe_unused */
45 #include "probe-event.h"
46 #include "probe-finder.h"
47 #include "session.h"
48
49 #define MAX_CMDLEN 256
50 #define PERFPROBE_GROUP "probe"
51
52 bool probe_event_dry_run;       /* Dry run flag */
53
54 #define semantic_error(msg ...) pr_err("Semantic error :" msg)
55
56 /* If there is no space to write, returns -E2BIG. */
57 static int e_snprintf(char *str, size_t size, const char *format, ...)
58         __attribute__((format(printf, 3, 4)));
59
60 static int e_snprintf(char *str, size_t size, const char *format, ...)
61 {
62         int ret;
63         va_list ap;
64         va_start(ap, format);
65         ret = vsnprintf(str, size, format, ap);
66         va_end(ap);
67         if (ret >= (int)size)
68                 ret = -E2BIG;
69         return ret;
70 }
71
72 static char *synthesize_perf_probe_point(struct perf_probe_point *pp);
73 static int convert_name_to_addr(struct perf_probe_event *pev,
74                                 const char *exec);
75 static void clear_probe_trace_event(struct probe_trace_event *tev);
76 static struct machine *host_machine;
77
78 /* Initialize symbol maps and path of vmlinux/modules */
79 static int init_symbol_maps(bool user_only)
80 {
81         int ret;
82
83         symbol_conf.sort_by_name = true;
84         ret = symbol__init();
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 map *kernel_get_module_map(const char *module)
125 {
126         struct rb_node *nd;
127         struct map_groups *grp = &host_machine->kmaps;
128
129         /* A file path -- this is an offline module */
130         if (module && strchr(module, '/'))
131                 return machine__new_module(host_machine, 0, module);
132
133         if (!module)
134                 module = "kernel";
135
136         for (nd = rb_first(&grp->maps[MAP__FUNCTION]); nd; nd = rb_next(nd)) {
137                 struct map *pos = rb_entry(nd, struct map, rb_node);
138                 if (strncmp(pos->dso->short_name + 1, module,
139                             pos->dso->short_name_len - 2) == 0) {
140                         return pos;
141                 }
142         }
143         return NULL;
144 }
145
146 static struct dso *kernel_get_module_dso(const char *module)
147 {
148         struct dso *dso;
149         struct map *map;
150         const char *vmlinux_name;
151
152         if (module) {
153                 list_for_each_entry(dso, &host_machine->kernel_dsos, node) {
154                         if (strncmp(dso->short_name + 1, module,
155                                     dso->short_name_len - 2) == 0)
156                                 goto found;
157                 }
158                 pr_debug("Failed to find module %s.\n", module);
159                 return NULL;
160         }
161
162         map = host_machine->vmlinux_maps[MAP__FUNCTION];
163         dso = map->dso;
164
165         vmlinux_name = symbol_conf.vmlinux_name;
166         if (vmlinux_name) {
167                 if (dso__load_vmlinux(dso, map, vmlinux_name, false, NULL) <= 0)
168                         return NULL;
169         } else {
170                 if (dso__load_vmlinux_path(dso, map, NULL) <= 0) {
171                         pr_debug("Failed to load kernel map.\n");
172                         return NULL;
173                 }
174         }
175 found:
176         return dso;
177 }
178
179 const char *kernel_get_module_path(const char *module)
180 {
181         struct dso *dso = kernel_get_module_dso(module);
182         return (dso) ? dso->long_name : NULL;
183 }
184
185 static int convert_exec_to_group(const char *exec, char **result)
186 {
187         char *ptr1, *ptr2, *exec_copy;
188         char buf[64];
189         int ret;
190
191         exec_copy = strdup(exec);
192         if (!exec_copy)
193                 return -ENOMEM;
194
195         ptr1 = basename(exec_copy);
196         if (!ptr1) {
197                 ret = -EINVAL;
198                 goto out;
199         }
200
201         ptr2 = strpbrk(ptr1, "-._");
202         if (ptr2)
203                 *ptr2 = '\0';
204         ret = e_snprintf(buf, 64, "%s_%s", PERFPROBE_GROUP, ptr1);
205         if (ret < 0)
206                 goto out;
207
208         *result = strdup(buf);
209         ret = *result ? 0 : -ENOMEM;
210
211 out:
212         free(exec_copy);
213         return ret;
214 }
215
216 static int convert_to_perf_probe_point(struct probe_trace_point *tp,
217                                         struct perf_probe_point *pp)
218 {
219         pp->function = strdup(tp->symbol);
220
221         if (pp->function == NULL)
222                 return -ENOMEM;
223
224         pp->offset = tp->offset;
225         pp->retprobe = tp->retprobe;
226
227         return 0;
228 }
229
230 #ifdef HAVE_DWARF_SUPPORT
231 /* Open new debuginfo of given module */
232 static struct debuginfo *open_debuginfo(const char *module)
233 {
234         const char *path;
235
236         /* A file path -- this is an offline module */
237         if (module && strchr(module, '/'))
238                 path = module;
239         else {
240                 path = kernel_get_module_path(module);
241
242                 if (!path) {
243                         pr_err("Failed to find path of %s module.\n",
244                                module ?: "kernel");
245                         return NULL;
246                 }
247         }
248         return debuginfo__new(path);
249 }
250
251 /*
252  * Convert trace point to probe point with debuginfo
253  * Currently only handles kprobes.
254  */
255 static int kprobe_convert_to_perf_probe(struct probe_trace_point *tp,
256                                         struct perf_probe_point *pp)
257 {
258         struct symbol *sym;
259         struct map *map;
260         u64 addr;
261         int ret = -ENOENT;
262         struct debuginfo *dinfo;
263
264         sym = __find_kernel_function_by_name(tp->symbol, &map);
265         if (sym) {
266                 addr = map->unmap_ip(map, sym->start + tp->offset);
267                 pr_debug("try to find %s+%ld@%" PRIx64 "\n", tp->symbol,
268                          tp->offset, addr);
269
270                 dinfo = debuginfo__new_online_kernel(addr);
271                 if (dinfo) {
272                         ret = debuginfo__find_probe_point(dinfo,
273                                                  (unsigned long)addr, pp);
274                         debuginfo__delete(dinfo);
275                 } else {
276                         pr_debug("Failed to open debuginfo at 0x%" PRIx64 "\n",
277                                  addr);
278                         ret = -ENOENT;
279                 }
280         }
281         if (ret <= 0) {
282                 pr_debug("Failed to find corresponding probes from "
283                          "debuginfo. Use kprobe event information.\n");
284                 return convert_to_perf_probe_point(tp, pp);
285         }
286         pp->retprobe = tp->retprobe;
287
288         return 0;
289 }
290
291 static int get_text_start_address(const char *exec, unsigned long *address)
292 {
293         Elf *elf;
294         GElf_Ehdr ehdr;
295         GElf_Shdr shdr;
296         int fd, ret = -ENOENT;
297
298         fd = open(exec, O_RDONLY);
299         if (fd < 0)
300                 return -errno;
301
302         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
303         if (elf == NULL)
304                 return -EINVAL;
305
306         if (gelf_getehdr(elf, &ehdr) == NULL)
307                 goto out;
308
309         if (!elf_section_by_name(elf, &ehdr, &shdr, ".text", NULL))
310                 goto out;
311
312         *address = shdr.sh_addr - shdr.sh_offset;
313         ret = 0;
314 out:
315         elf_end(elf);
316         return ret;
317 }
318
319 static int add_exec_to_probe_trace_events(struct probe_trace_event *tevs,
320                                           int ntevs, const char *exec)
321 {
322         int i, ret = 0;
323         unsigned long offset, stext = 0;
324         char buf[32];
325
326         if (!exec)
327                 return 0;
328
329         ret = get_text_start_address(exec, &stext);
330         if (ret < 0)
331                 return ret;
332
333         for (i = 0; i < ntevs && ret >= 0; i++) {
334                 /* point.address is the addres of point.symbol + point.offset */
335                 offset = tevs[i].point.address - stext;
336                 tevs[i].point.offset = 0;
337                 zfree(&tevs[i].point.symbol);
338                 ret = e_snprintf(buf, 32, "0x%lx", offset);
339                 if (ret < 0)
340                         break;
341                 tevs[i].point.module = strdup(exec);
342                 tevs[i].point.symbol = strdup(buf);
343                 if (!tevs[i].point.symbol || !tevs[i].point.module) {
344                         ret = -ENOMEM;
345                         break;
346                 }
347                 tevs[i].uprobes = true;
348         }
349
350         return ret;
351 }
352
353 static int add_module_to_probe_trace_events(struct probe_trace_event *tevs,
354                                             int ntevs, const char *module)
355 {
356         int i, ret = 0;
357         char *tmp;
358
359         if (!module)
360                 return 0;
361
362         tmp = strrchr(module, '/');
363         if (tmp) {
364                 /* This is a module path -- get the module name */
365                 module = strdup(tmp + 1);
366                 if (!module)
367                         return -ENOMEM;
368                 tmp = strchr(module, '.');
369                 if (tmp)
370                         *tmp = '\0';
371                 tmp = (char *)module;   /* For free() */
372         }
373
374         for (i = 0; i < ntevs; i++) {
375                 tevs[i].point.module = strdup(module);
376                 if (!tevs[i].point.module) {
377                         ret = -ENOMEM;
378                         break;
379                 }
380         }
381
382         free(tmp);
383         return ret;
384 }
385
386 static void clear_probe_trace_events(struct probe_trace_event *tevs, int ntevs)
387 {
388         int i;
389
390         for (i = 0; i < ntevs; i++)
391                 clear_probe_trace_event(tevs + i);
392 }
393
394 /* Try to find perf_probe_event with debuginfo */
395 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
396                                           struct probe_trace_event **tevs,
397                                           int max_tevs, const char *target)
398 {
399         bool need_dwarf = perf_probe_event_need_dwarf(pev);
400         struct debuginfo *dinfo;
401         int ntevs, ret = 0;
402
403         dinfo = open_debuginfo(target);
404
405         if (!dinfo) {
406                 if (need_dwarf) {
407                         pr_warning("Failed to open debuginfo file.\n");
408                         return -ENOENT;
409                 }
410                 pr_debug("Could not open debuginfo. Try to use symbols.\n");
411                 return 0;
412         }
413
414         /* Searching trace events corresponding to a probe event */
415         ntevs = debuginfo__find_trace_events(dinfo, pev, tevs, max_tevs);
416
417         debuginfo__delete(dinfo);
418
419         if (ntevs > 0) {        /* Succeeded to find trace events */
420                 pr_debug("find %d probe_trace_events.\n", ntevs);
421                 if (target) {
422                         if (pev->uprobes)
423                                 ret = add_exec_to_probe_trace_events(*tevs,
424                                                  ntevs, target);
425                         else
426                                 ret = add_module_to_probe_trace_events(*tevs,
427                                                  ntevs, target);
428                 }
429                 if (ret < 0) {
430                         clear_probe_trace_events(*tevs, ntevs);
431                         zfree(tevs);
432                 }
433                 return ret < 0 ? ret : ntevs;
434         }
435
436         if (ntevs == 0) {       /* No error but failed to find probe point. */
437                 pr_warning("Probe point '%s' not found.\n",
438                            synthesize_perf_probe_point(&pev->point));
439                 return -ENOENT;
440         }
441         /* Error path : ntevs < 0 */
442         pr_debug("An error occurred in debuginfo analysis (%d).\n", ntevs);
443         if (ntevs == -EBADF) {
444                 pr_warning("Warning: No dwarf info found in the vmlinux - "
445                         "please rebuild kernel with CONFIG_DEBUG_INFO=y.\n");
446                 if (!need_dwarf) {
447                         pr_debug("Trying to use symbols.\n");
448                         return 0;
449                 }
450         }
451         return ntevs;
452 }
453
454 /*
455  * Find a src file from a DWARF tag path. Prepend optional source path prefix
456  * and chop off leading directories that do not exist. Result is passed back as
457  * a newly allocated path on success.
458  * Return 0 if file was found and readable, -errno otherwise.
459  */
460 static int get_real_path(const char *raw_path, const char *comp_dir,
461                          char **new_path)
462 {
463         const char *prefix = symbol_conf.source_prefix;
464
465         if (!prefix) {
466                 if (raw_path[0] != '/' && comp_dir)
467                         /* If not an absolute path, try to use comp_dir */
468                         prefix = comp_dir;
469                 else {
470                         if (access(raw_path, R_OK) == 0) {
471                                 *new_path = strdup(raw_path);
472                                 return 0;
473                         } else
474                                 return -errno;
475                 }
476         }
477
478         *new_path = malloc((strlen(prefix) + strlen(raw_path) + 2));
479         if (!*new_path)
480                 return -ENOMEM;
481
482         for (;;) {
483                 sprintf(*new_path, "%s/%s", prefix, raw_path);
484
485                 if (access(*new_path, R_OK) == 0)
486                         return 0;
487
488                 if (!symbol_conf.source_prefix)
489                         /* In case of searching comp_dir, don't retry */
490                         return -errno;
491
492                 switch (errno) {
493                 case ENAMETOOLONG:
494                 case ENOENT:
495                 case EROFS:
496                 case EFAULT:
497                         raw_path = strchr(++raw_path, '/');
498                         if (!raw_path) {
499                                 zfree(new_path);
500                                 return -ENOENT;
501                         }
502                         continue;
503
504                 default:
505                         zfree(new_path);
506                         return -errno;
507                 }
508         }
509 }
510
511 #define LINEBUF_SIZE 256
512 #define NR_ADDITIONAL_LINES 2
513
514 static int __show_one_line(FILE *fp, int l, bool skip, bool show_num)
515 {
516         char buf[LINEBUF_SIZE];
517         const char *color = show_num ? "" : PERF_COLOR_BLUE;
518         const char *prefix = NULL;
519
520         do {
521                 if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
522                         goto error;
523                 if (skip)
524                         continue;
525                 if (!prefix) {
526                         prefix = show_num ? "%7d  " : "         ";
527                         color_fprintf(stdout, color, prefix, l);
528                 }
529                 color_fprintf(stdout, color, "%s", buf);
530
531         } while (strchr(buf, '\n') == NULL);
532
533         return 1;
534 error:
535         if (ferror(fp)) {
536                 pr_warning("File read error: %s\n", strerror(errno));
537                 return -1;
538         }
539         return 0;
540 }
541
542 static int _show_one_line(FILE *fp, int l, bool skip, bool show_num)
543 {
544         int rv = __show_one_line(fp, l, skip, show_num);
545         if (rv == 0) {
546                 pr_warning("Source file is shorter than expected.\n");
547                 rv = -1;
548         }
549         return rv;
550 }
551
552 #define show_one_line_with_num(f,l)     _show_one_line(f,l,false,true)
553 #define show_one_line(f,l)              _show_one_line(f,l,false,false)
554 #define skip_one_line(f,l)              _show_one_line(f,l,true,false)
555 #define show_one_line_or_eof(f,l)       __show_one_line(f,l,false,false)
556
557 /*
558  * Show line-range always requires debuginfo to find source file and
559  * line number.
560  */
561 static int __show_line_range(struct line_range *lr, const char *module)
562 {
563         int l = 1;
564         struct int_node *ln;
565         struct debuginfo *dinfo;
566         FILE *fp;
567         int ret;
568         char *tmp;
569
570         /* Search a line range */
571         dinfo = open_debuginfo(module);
572         if (!dinfo) {
573                 pr_warning("Failed to open debuginfo file.\n");
574                 return -ENOENT;
575         }
576
577         ret = debuginfo__find_line_range(dinfo, lr);
578         debuginfo__delete(dinfo);
579         if (ret == 0) {
580                 pr_warning("Specified source line is not found.\n");
581                 return -ENOENT;
582         } else if (ret < 0) {
583                 pr_warning("Debuginfo analysis failed. (%d)\n", ret);
584                 return ret;
585         }
586
587         /* Convert source file path */
588         tmp = lr->path;
589         ret = get_real_path(tmp, lr->comp_dir, &lr->path);
590         free(tmp);      /* Free old path */
591         if (ret < 0) {
592                 pr_warning("Failed to find source file. (%d)\n", ret);
593                 return ret;
594         }
595
596         setup_pager();
597
598         if (lr->function)
599                 fprintf(stdout, "<%s@%s:%d>\n", lr->function, lr->path,
600                         lr->start - lr->offset);
601         else
602                 fprintf(stdout, "<%s:%d>\n", lr->path, lr->start);
603
604         fp = fopen(lr->path, "r");
605         if (fp == NULL) {
606                 pr_warning("Failed to open %s: %s\n", lr->path,
607                            strerror(errno));
608                 return -errno;
609         }
610         /* Skip to starting line number */
611         while (l < lr->start) {
612                 ret = skip_one_line(fp, l++);
613                 if (ret < 0)
614                         goto end;
615         }
616
617         intlist__for_each(ln, lr->line_list) {
618                 for (; ln->i > l; l++) {
619                         ret = show_one_line(fp, l - lr->offset);
620                         if (ret < 0)
621                                 goto end;
622                 }
623                 ret = show_one_line_with_num(fp, l++ - lr->offset);
624                 if (ret < 0)
625                         goto end;
626         }
627
628         if (lr->end == INT_MAX)
629                 lr->end = l + NR_ADDITIONAL_LINES;
630         while (l <= lr->end) {
631                 ret = show_one_line_or_eof(fp, l++ - lr->offset);
632                 if (ret <= 0)
633                         break;
634         }
635 end:
636         fclose(fp);
637         return ret;
638 }
639
640 int show_line_range(struct line_range *lr, const char *module)
641 {
642         int ret;
643
644         ret = init_symbol_maps(false);
645         if (ret < 0)
646                 return ret;
647         ret = __show_line_range(lr, module);
648         exit_symbol_maps();
649
650         return ret;
651 }
652
653 static int show_available_vars_at(struct debuginfo *dinfo,
654                                   struct perf_probe_event *pev,
655                                   int max_vls, struct strfilter *_filter,
656                                   bool externs)
657 {
658         char *buf;
659         int ret, i, nvars;
660         struct str_node *node;
661         struct variable_list *vls = NULL, *vl;
662         const char *var;
663
664         buf = synthesize_perf_probe_point(&pev->point);
665         if (!buf)
666                 return -EINVAL;
667         pr_debug("Searching variables at %s\n", buf);
668
669         ret = debuginfo__find_available_vars_at(dinfo, pev, &vls,
670                                                 max_vls, externs);
671         if (ret <= 0) {
672                 pr_err("Failed to find variables at %s (%d)\n", buf, ret);
673                 goto end;
674         }
675         /* Some variables are found */
676         fprintf(stdout, "Available variables at %s\n", buf);
677         for (i = 0; i < ret; i++) {
678                 vl = &vls[i];
679                 /*
680                  * A probe point might be converted to
681                  * several trace points.
682                  */
683                 fprintf(stdout, "\t@<%s+%lu>\n", vl->point.symbol,
684                         vl->point.offset);
685                 zfree(&vl->point.symbol);
686                 nvars = 0;
687                 if (vl->vars) {
688                         strlist__for_each(node, vl->vars) {
689                                 var = strchr(node->s, '\t') + 1;
690                                 if (strfilter__compare(_filter, var)) {
691                                         fprintf(stdout, "\t\t%s\n", node->s);
692                                         nvars++;
693                                 }
694                         }
695                         strlist__delete(vl->vars);
696                 }
697                 if (nvars == 0)
698                         fprintf(stdout, "\t\t(No matched variables)\n");
699         }
700         free(vls);
701 end:
702         free(buf);
703         return ret;
704 }
705
706 /* Show available variables on given probe point */
707 int show_available_vars(struct perf_probe_event *pevs, int npevs,
708                         int max_vls, const char *module,
709                         struct strfilter *_filter, bool externs)
710 {
711         int i, ret = 0;
712         struct debuginfo *dinfo;
713
714         ret = init_symbol_maps(false);
715         if (ret < 0)
716                 return ret;
717
718         dinfo = open_debuginfo(module);
719         if (!dinfo) {
720                 pr_warning("Failed to open debuginfo file.\n");
721                 ret = -ENOENT;
722                 goto out;
723         }
724
725         setup_pager();
726
727         for (i = 0; i < npevs && ret >= 0; i++)
728                 ret = show_available_vars_at(dinfo, &pevs[i], max_vls, _filter,
729                                              externs);
730
731         debuginfo__delete(dinfo);
732 out:
733         exit_symbol_maps();
734         return ret;
735 }
736
737 #else   /* !HAVE_DWARF_SUPPORT */
738
739 static int kprobe_convert_to_perf_probe(struct probe_trace_point *tp,
740                                         struct perf_probe_point *pp)
741 {
742         return convert_to_perf_probe_point(tp, pp);
743 }
744
745 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
746                                 struct probe_trace_event **tevs __maybe_unused,
747                                 int max_tevs __maybe_unused,
748                                 const char *target __maybe_unused)
749 {
750         if (perf_probe_event_need_dwarf(pev)) {
751                 pr_warning("Debuginfo-analysis is not supported.\n");
752                 return -ENOSYS;
753         }
754
755         return 0;
756 }
757
758 int show_line_range(struct line_range *lr __maybe_unused,
759                     const char *module __maybe_unused)
760 {
761         pr_warning("Debuginfo-analysis is not supported.\n");
762         return -ENOSYS;
763 }
764
765 int show_available_vars(struct perf_probe_event *pevs __maybe_unused,
766                         int npevs __maybe_unused, int max_vls __maybe_unused,
767                         const char *module __maybe_unused,
768                         struct strfilter *filter __maybe_unused,
769                         bool externs __maybe_unused)
770 {
771         pr_warning("Debuginfo-analysis is not supported.\n");
772         return -ENOSYS;
773 }
774 #endif
775
776 void line_range__clear(struct line_range *lr)
777 {
778         free(lr->function);
779         free(lr->file);
780         free(lr->path);
781         free(lr->comp_dir);
782         intlist__delete(lr->line_list);
783         memset(lr, 0, sizeof(*lr));
784 }
785
786 int line_range__init(struct line_range *lr)
787 {
788         memset(lr, 0, sizeof(*lr));
789         lr->line_list = intlist__new(NULL);
790         if (!lr->line_list)
791                 return -ENOMEM;
792         else
793                 return 0;
794 }
795
796 static int parse_line_num(char **ptr, int *val, const char *what)
797 {
798         const char *start = *ptr;
799
800         errno = 0;
801         *val = strtol(*ptr, ptr, 0);
802         if (errno || *ptr == start) {
803                 semantic_error("'%s' is not a valid number.\n", what);
804                 return -EINVAL;
805         }
806         return 0;
807 }
808
809 /*
810  * Stuff 'lr' according to the line range described by 'arg'.
811  * The line range syntax is described by:
812  *
813  *         SRC[:SLN[+NUM|-ELN]]
814  *         FNC[@SRC][:SLN[+NUM|-ELN]]
815  */
816 int parse_line_range_desc(const char *arg, struct line_range *lr)
817 {
818         char *range, *file, *name = strdup(arg);
819         int err;
820
821         if (!name)
822                 return -ENOMEM;
823
824         lr->start = 0;
825         lr->end = INT_MAX;
826
827         range = strchr(name, ':');
828         if (range) {
829                 *range++ = '\0';
830
831                 err = parse_line_num(&range, &lr->start, "start line");
832                 if (err)
833                         goto err;
834
835                 if (*range == '+' || *range == '-') {
836                         const char c = *range++;
837
838                         err = parse_line_num(&range, &lr->end, "end line");
839                         if (err)
840                                 goto err;
841
842                         if (c == '+') {
843                                 lr->end += lr->start;
844                                 /*
845                                  * Adjust the number of lines here.
846                                  * If the number of lines == 1, the
847                                  * the end of line should be equal to
848                                  * the start of line.
849                                  */
850                                 lr->end--;
851                         }
852                 }
853
854                 pr_debug("Line range is %d to %d\n", lr->start, lr->end);
855
856                 err = -EINVAL;
857                 if (lr->start > lr->end) {
858                         semantic_error("Start line must be smaller"
859                                        " than end line.\n");
860                         goto err;
861                 }
862                 if (*range != '\0') {
863                         semantic_error("Tailing with invalid str '%s'.\n", range);
864                         goto err;
865                 }
866         }
867
868         file = strchr(name, '@');
869         if (file) {
870                 *file = '\0';
871                 lr->file = strdup(++file);
872                 if (lr->file == NULL) {
873                         err = -ENOMEM;
874                         goto err;
875                 }
876                 lr->function = name;
877         } else if (strchr(name, '.'))
878                 lr->file = name;
879         else
880                 lr->function = name;
881
882         return 0;
883 err:
884         free(name);
885         return err;
886 }
887
888 /* Check the name is good for event/group */
889 static bool check_event_name(const char *name)
890 {
891         if (!isalpha(*name) && *name != '_')
892                 return false;
893         while (*++name != '\0') {
894                 if (!isalpha(*name) && !isdigit(*name) && *name != '_')
895                         return false;
896         }
897         return true;
898 }
899
900 /* Parse probepoint definition. */
901 static int parse_perf_probe_point(char *arg, struct perf_probe_event *pev)
902 {
903         struct perf_probe_point *pp = &pev->point;
904         char *ptr, *tmp;
905         char c, nc = 0;
906         /*
907          * <Syntax>
908          * perf probe [EVENT=]SRC[:LN|;PTN]
909          * perf probe [EVENT=]FUNC[@SRC][+OFFS|%return|:LN|;PAT]
910          *
911          * TODO:Group name support
912          */
913
914         ptr = strpbrk(arg, ";=@+%");
915         if (ptr && *ptr == '=') {       /* Event name */
916                 *ptr = '\0';
917                 tmp = ptr + 1;
918                 if (strchr(arg, ':')) {
919                         semantic_error("Group name is not supported yet.\n");
920                         return -ENOTSUP;
921                 }
922                 if (!check_event_name(arg)) {
923                         semantic_error("%s is bad for event name -it must "
924                                        "follow C symbol-naming rule.\n", arg);
925                         return -EINVAL;
926                 }
927                 pev->event = strdup(arg);
928                 if (pev->event == NULL)
929                         return -ENOMEM;
930                 pev->group = NULL;
931                 arg = tmp;
932         }
933
934         ptr = strpbrk(arg, ";:+@%");
935         if (ptr) {
936                 nc = *ptr;
937                 *ptr++ = '\0';
938         }
939
940         tmp = strdup(arg);
941         if (tmp == NULL)
942                 return -ENOMEM;
943
944         /* Check arg is function or file and copy it */
945         if (strchr(tmp, '.'))   /* File */
946                 pp->file = tmp;
947         else                    /* Function */
948                 pp->function = tmp;
949
950         /* Parse other options */
951         while (ptr) {
952                 arg = ptr;
953                 c = nc;
954                 if (c == ';') { /* Lazy pattern must be the last part */
955                         pp->lazy_line = strdup(arg);
956                         if (pp->lazy_line == NULL)
957                                 return -ENOMEM;
958                         break;
959                 }
960                 ptr = strpbrk(arg, ";:+@%");
961                 if (ptr) {
962                         nc = *ptr;
963                         *ptr++ = '\0';
964                 }
965                 switch (c) {
966                 case ':':       /* Line number */
967                         pp->line = strtoul(arg, &tmp, 0);
968                         if (*tmp != '\0') {
969                                 semantic_error("There is non-digit char"
970                                                " in line number.\n");
971                                 return -EINVAL;
972                         }
973                         break;
974                 case '+':       /* Byte offset from a symbol */
975                         pp->offset = strtoul(arg, &tmp, 0);
976                         if (*tmp != '\0') {
977                                 semantic_error("There is non-digit character"
978                                                 " in offset.\n");
979                                 return -EINVAL;
980                         }
981                         break;
982                 case '@':       /* File name */
983                         if (pp->file) {
984                                 semantic_error("SRC@SRC is not allowed.\n");
985                                 return -EINVAL;
986                         }
987                         pp->file = strdup(arg);
988                         if (pp->file == NULL)
989                                 return -ENOMEM;
990                         break;
991                 case '%':       /* Probe places */
992                         if (strcmp(arg, "return") == 0) {
993                                 pp->retprobe = 1;
994                         } else {        /* Others not supported yet */
995                                 semantic_error("%%%s is not supported.\n", arg);
996                                 return -ENOTSUP;
997                         }
998                         break;
999                 default:        /* Buggy case */
1000                         pr_err("This program has a bug at %s:%d.\n",
1001                                 __FILE__, __LINE__);
1002                         return -ENOTSUP;
1003                         break;
1004                 }
1005         }
1006
1007         /* Exclusion check */
1008         if (pp->lazy_line && pp->line) {
1009                 semantic_error("Lazy pattern can't be used with"
1010                                " line number.\n");
1011                 return -EINVAL;
1012         }
1013
1014         if (pp->lazy_line && pp->offset) {
1015                 semantic_error("Lazy pattern can't be used with offset.\n");
1016                 return -EINVAL;
1017         }
1018
1019         if (pp->line && pp->offset) {
1020                 semantic_error("Offset can't be used with line number.\n");
1021                 return -EINVAL;
1022         }
1023
1024         if (!pp->line && !pp->lazy_line && pp->file && !pp->function) {
1025                 semantic_error("File always requires line number or "
1026                                "lazy pattern.\n");
1027                 return -EINVAL;
1028         }
1029
1030         if (pp->offset && !pp->function) {
1031                 semantic_error("Offset requires an entry function.\n");
1032                 return -EINVAL;
1033         }
1034
1035         if (pp->retprobe && !pp->function) {
1036                 semantic_error("Return probe requires an entry function.\n");
1037                 return -EINVAL;
1038         }
1039
1040         if ((pp->offset || pp->line || pp->lazy_line) && pp->retprobe) {
1041                 semantic_error("Offset/Line/Lazy pattern can't be used with "
1042                                "return probe.\n");
1043                 return -EINVAL;
1044         }
1045
1046         pr_debug("symbol:%s file:%s line:%d offset:%lu return:%d lazy:%s\n",
1047                  pp->function, pp->file, pp->line, pp->offset, pp->retprobe,
1048                  pp->lazy_line);
1049         return 0;
1050 }
1051
1052 /* Parse perf-probe event argument */
1053 static int parse_perf_probe_arg(char *str, struct perf_probe_arg *arg)
1054 {
1055         char *tmp, *goodname;
1056         struct perf_probe_arg_field **fieldp;
1057
1058         pr_debug("parsing arg: %s into ", str);
1059
1060         tmp = strchr(str, '=');
1061         if (tmp) {
1062                 arg->name = strndup(str, tmp - str);
1063                 if (arg->name == NULL)
1064                         return -ENOMEM;
1065                 pr_debug("name:%s ", arg->name);
1066                 str = tmp + 1;
1067         }
1068
1069         tmp = strchr(str, ':');
1070         if (tmp) {      /* Type setting */
1071                 *tmp = '\0';
1072                 arg->type = strdup(tmp + 1);
1073                 if (arg->type == NULL)
1074                         return -ENOMEM;
1075                 pr_debug("type:%s ", arg->type);
1076         }
1077
1078         tmp = strpbrk(str, "-.[");
1079         if (!is_c_varname(str) || !tmp) {
1080                 /* A variable, register, symbol or special value */
1081                 arg->var = strdup(str);
1082                 if (arg->var == NULL)
1083                         return -ENOMEM;
1084                 pr_debug("%s\n", arg->var);
1085                 return 0;
1086         }
1087
1088         /* Structure fields or array element */
1089         arg->var = strndup(str, tmp - str);
1090         if (arg->var == NULL)
1091                 return -ENOMEM;
1092         goodname = arg->var;
1093         pr_debug("%s, ", arg->var);
1094         fieldp = &arg->field;
1095
1096         do {
1097                 *fieldp = zalloc(sizeof(struct perf_probe_arg_field));
1098                 if (*fieldp == NULL)
1099                         return -ENOMEM;
1100                 if (*tmp == '[') {      /* Array */
1101                         str = tmp;
1102                         (*fieldp)->index = strtol(str + 1, &tmp, 0);
1103                         (*fieldp)->ref = true;
1104                         if (*tmp != ']' || tmp == str + 1) {
1105                                 semantic_error("Array index must be a"
1106                                                 " number.\n");
1107                                 return -EINVAL;
1108                         }
1109                         tmp++;
1110                         if (*tmp == '\0')
1111                                 tmp = NULL;
1112                 } else {                /* Structure */
1113                         if (*tmp == '.') {
1114                                 str = tmp + 1;
1115                                 (*fieldp)->ref = false;
1116                         } else if (tmp[1] == '>') {
1117                                 str = tmp + 2;
1118                                 (*fieldp)->ref = true;
1119                         } else {
1120                                 semantic_error("Argument parse error: %s\n",
1121                                                str);
1122                                 return -EINVAL;
1123                         }
1124                         tmp = strpbrk(str, "-.[");
1125                 }
1126                 if (tmp) {
1127                         (*fieldp)->name = strndup(str, tmp - str);
1128                         if ((*fieldp)->name == NULL)
1129                                 return -ENOMEM;
1130                         if (*str != '[')
1131                                 goodname = (*fieldp)->name;
1132                         pr_debug("%s(%d), ", (*fieldp)->name, (*fieldp)->ref);
1133                         fieldp = &(*fieldp)->next;
1134                 }
1135         } while (tmp);
1136         (*fieldp)->name = strdup(str);
1137         if ((*fieldp)->name == NULL)
1138                 return -ENOMEM;
1139         if (*str != '[')
1140                 goodname = (*fieldp)->name;
1141         pr_debug("%s(%d)\n", (*fieldp)->name, (*fieldp)->ref);
1142
1143         /* If no name is specified, set the last field name (not array index)*/
1144         if (!arg->name) {
1145                 arg->name = strdup(goodname);
1146                 if (arg->name == NULL)
1147                         return -ENOMEM;
1148         }
1149         return 0;
1150 }
1151
1152 /* Parse perf-probe event command */
1153 int parse_perf_probe_command(const char *cmd, struct perf_probe_event *pev)
1154 {
1155         char **argv;
1156         int argc, i, ret = 0;
1157
1158         argv = argv_split(cmd, &argc);
1159         if (!argv) {
1160                 pr_debug("Failed to split arguments.\n");
1161                 return -ENOMEM;
1162         }
1163         if (argc - 1 > MAX_PROBE_ARGS) {
1164                 semantic_error("Too many probe arguments (%d).\n", argc - 1);
1165                 ret = -ERANGE;
1166                 goto out;
1167         }
1168         /* Parse probe point */
1169         ret = parse_perf_probe_point(argv[0], pev);
1170         if (ret < 0)
1171                 goto out;
1172
1173         /* Copy arguments and ensure return probe has no C argument */
1174         pev->nargs = argc - 1;
1175         pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1176         if (pev->args == NULL) {
1177                 ret = -ENOMEM;
1178                 goto out;
1179         }
1180         for (i = 0; i < pev->nargs && ret >= 0; i++) {
1181                 ret = parse_perf_probe_arg(argv[i + 1], &pev->args[i]);
1182                 if (ret >= 0 &&
1183                     is_c_varname(pev->args[i].var) && pev->point.retprobe) {
1184                         semantic_error("You can't specify local variable for"
1185                                        " kretprobe.\n");
1186                         ret = -EINVAL;
1187                 }
1188         }
1189 out:
1190         argv_free(argv);
1191
1192         return ret;
1193 }
1194
1195 /* Return true if this perf_probe_event requires debuginfo */
1196 bool perf_probe_event_need_dwarf(struct perf_probe_event *pev)
1197 {
1198         int i;
1199
1200         if (pev->point.file || pev->point.line || pev->point.lazy_line)
1201                 return true;
1202
1203         for (i = 0; i < pev->nargs; i++)
1204                 if (is_c_varname(pev->args[i].var))
1205                         return true;
1206
1207         return false;
1208 }
1209
1210 /* Parse probe_events event into struct probe_point */
1211 static int parse_probe_trace_command(const char *cmd,
1212                                      struct probe_trace_event *tev)
1213 {
1214         struct probe_trace_point *tp = &tev->point;
1215         char pr;
1216         char *p;
1217         char *argv0_str = NULL, *fmt, *fmt1_str, *fmt2_str, *fmt3_str;
1218         int ret, i, argc;
1219         char **argv;
1220
1221         pr_debug("Parsing probe_events: %s\n", cmd);
1222         argv = argv_split(cmd, &argc);
1223         if (!argv) {
1224                 pr_debug("Failed to split arguments.\n");
1225                 return -ENOMEM;
1226         }
1227         if (argc < 2) {
1228                 semantic_error("Too few probe arguments.\n");
1229                 ret = -ERANGE;
1230                 goto out;
1231         }
1232
1233         /* Scan event and group name. */
1234         argv0_str = strdup(argv[0]);
1235         if (argv0_str == NULL) {
1236                 ret = -ENOMEM;
1237                 goto out;
1238         }
1239         fmt1_str = strtok_r(argv0_str, ":", &fmt);
1240         fmt2_str = strtok_r(NULL, "/", &fmt);
1241         fmt3_str = strtok_r(NULL, " \t", &fmt);
1242         if (fmt1_str == NULL || strlen(fmt1_str) != 1 || fmt2_str == NULL
1243             || fmt3_str == NULL) {
1244                 semantic_error("Failed to parse event name: %s\n", argv[0]);
1245                 ret = -EINVAL;
1246                 goto out;
1247         }
1248         pr = fmt1_str[0];
1249         tev->group = strdup(fmt2_str);
1250         tev->event = strdup(fmt3_str);
1251         if (tev->group == NULL || tev->event == NULL) {
1252                 ret = -ENOMEM;
1253                 goto out;
1254         }
1255         pr_debug("Group:%s Event:%s probe:%c\n", tev->group, tev->event, pr);
1256
1257         tp->retprobe = (pr == 'r');
1258
1259         /* Scan module name(if there), function name and offset */
1260         p = strchr(argv[1], ':');
1261         if (p) {
1262                 tp->module = strndup(argv[1], p - argv[1]);
1263                 p++;
1264         } else
1265                 p = argv[1];
1266         fmt1_str = strtok_r(p, "+", &fmt);
1267         tp->symbol = strdup(fmt1_str);
1268         if (tp->symbol == NULL) {
1269                 ret = -ENOMEM;
1270                 goto out;
1271         }
1272         fmt2_str = strtok_r(NULL, "", &fmt);
1273         if (fmt2_str == NULL)
1274                 tp->offset = 0;
1275         else
1276                 tp->offset = strtoul(fmt2_str, NULL, 10);
1277
1278         tev->nargs = argc - 2;
1279         tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
1280         if (tev->args == NULL) {
1281                 ret = -ENOMEM;
1282                 goto out;
1283         }
1284         for (i = 0; i < tev->nargs; i++) {
1285                 p = strchr(argv[i + 2], '=');
1286                 if (p)  /* We don't need which register is assigned. */
1287                         *p++ = '\0';
1288                 else
1289                         p = argv[i + 2];
1290                 tev->args[i].name = strdup(argv[i + 2]);
1291                 /* TODO: parse regs and offset */
1292                 tev->args[i].value = strdup(p);
1293                 if (tev->args[i].name == NULL || tev->args[i].value == NULL) {
1294                         ret = -ENOMEM;
1295                         goto out;
1296                 }
1297         }
1298         ret = 0;
1299 out:
1300         free(argv0_str);
1301         argv_free(argv);
1302         return ret;
1303 }
1304
1305 /* Compose only probe arg */
1306 int synthesize_perf_probe_arg(struct perf_probe_arg *pa, char *buf, size_t len)
1307 {
1308         struct perf_probe_arg_field *field = pa->field;
1309         int ret;
1310         char *tmp = buf;
1311
1312         if (pa->name && pa->var)
1313                 ret = e_snprintf(tmp, len, "%s=%s", pa->name, pa->var);
1314         else
1315                 ret = e_snprintf(tmp, len, "%s", pa->name ? pa->name : pa->var);
1316         if (ret <= 0)
1317                 goto error;
1318         tmp += ret;
1319         len -= ret;
1320
1321         while (field) {
1322                 if (field->name[0] == '[')
1323                         ret = e_snprintf(tmp, len, "%s", field->name);
1324                 else
1325                         ret = e_snprintf(tmp, len, "%s%s",
1326                                          field->ref ? "->" : ".", field->name);
1327                 if (ret <= 0)
1328                         goto error;
1329                 tmp += ret;
1330                 len -= ret;
1331                 field = field->next;
1332         }
1333
1334         if (pa->type) {
1335                 ret = e_snprintf(tmp, len, ":%s", pa->type);
1336                 if (ret <= 0)
1337                         goto error;
1338                 tmp += ret;
1339                 len -= ret;
1340         }
1341
1342         return tmp - buf;
1343 error:
1344         pr_debug("Failed to synthesize perf probe argument: %s\n",
1345                  strerror(-ret));
1346         return ret;
1347 }
1348
1349 /* Compose only probe point (not argument) */
1350 static char *synthesize_perf_probe_point(struct perf_probe_point *pp)
1351 {
1352         char *buf, *tmp;
1353         char offs[32] = "", line[32] = "", file[32] = "";
1354         int ret, len;
1355
1356         buf = zalloc(MAX_CMDLEN);
1357         if (buf == NULL) {
1358                 ret = -ENOMEM;
1359                 goto error;
1360         }
1361         if (pp->offset) {
1362                 ret = e_snprintf(offs, 32, "+%lu", pp->offset);
1363                 if (ret <= 0)
1364                         goto error;
1365         }
1366         if (pp->line) {
1367                 ret = e_snprintf(line, 32, ":%d", pp->line);
1368                 if (ret <= 0)
1369                         goto error;
1370         }
1371         if (pp->file) {
1372                 tmp = pp->file;
1373                 len = strlen(tmp);
1374                 if (len > 30) {
1375                         tmp = strchr(pp->file + len - 30, '/');
1376                         tmp = tmp ? tmp + 1 : pp->file + len - 30;
1377                 }
1378                 ret = e_snprintf(file, 32, "@%s", tmp);
1379                 if (ret <= 0)
1380                         goto error;
1381         }
1382
1383         if (pp->function)
1384                 ret = e_snprintf(buf, MAX_CMDLEN, "%s%s%s%s%s", pp->function,
1385                                  offs, pp->retprobe ? "%return" : "", line,
1386                                  file);
1387         else
1388                 ret = e_snprintf(buf, MAX_CMDLEN, "%s%s", file, line);
1389         if (ret <= 0)
1390                 goto error;
1391
1392         return buf;
1393 error:
1394         pr_debug("Failed to synthesize perf probe point: %s\n",
1395                  strerror(-ret));
1396         free(buf);
1397         return NULL;
1398 }
1399
1400 #if 0
1401 char *synthesize_perf_probe_command(struct perf_probe_event *pev)
1402 {
1403         char *buf;
1404         int i, len, ret;
1405
1406         buf = synthesize_perf_probe_point(&pev->point);
1407         if (!buf)
1408                 return NULL;
1409
1410         len = strlen(buf);
1411         for (i = 0; i < pev->nargs; i++) {
1412                 ret = e_snprintf(&buf[len], MAX_CMDLEN - len, " %s",
1413                                  pev->args[i].name);
1414                 if (ret <= 0) {
1415                         free(buf);
1416                         return NULL;
1417                 }
1418                 len += ret;
1419         }
1420
1421         return buf;
1422 }
1423 #endif
1424
1425 static int __synthesize_probe_trace_arg_ref(struct probe_trace_arg_ref *ref,
1426                                              char **buf, size_t *buflen,
1427                                              int depth)
1428 {
1429         int ret;
1430         if (ref->next) {
1431                 depth = __synthesize_probe_trace_arg_ref(ref->next, buf,
1432                                                          buflen, depth + 1);
1433                 if (depth < 0)
1434                         goto out;
1435         }
1436
1437         ret = e_snprintf(*buf, *buflen, "%+ld(", ref->offset);
1438         if (ret < 0)
1439                 depth = ret;
1440         else {
1441                 *buf += ret;
1442                 *buflen -= ret;
1443         }
1444 out:
1445         return depth;
1446
1447 }
1448
1449 static int synthesize_probe_trace_arg(struct probe_trace_arg *arg,
1450                                        char *buf, size_t buflen)
1451 {
1452         struct probe_trace_arg_ref *ref = arg->ref;
1453         int ret, depth = 0;
1454         char *tmp = buf;
1455
1456         /* Argument name or separator */
1457         if (arg->name)
1458                 ret = e_snprintf(buf, buflen, " %s=", arg->name);
1459         else
1460                 ret = e_snprintf(buf, buflen, " ");
1461         if (ret < 0)
1462                 return ret;
1463         buf += ret;
1464         buflen -= ret;
1465
1466         /* Special case: @XXX */
1467         if (arg->value[0] == '@' && arg->ref)
1468                         ref = ref->next;
1469
1470         /* Dereferencing arguments */
1471         if (ref) {
1472                 depth = __synthesize_probe_trace_arg_ref(ref, &buf,
1473                                                           &buflen, 1);
1474                 if (depth < 0)
1475                         return depth;
1476         }
1477
1478         /* Print argument value */
1479         if (arg->value[0] == '@' && arg->ref)
1480                 ret = e_snprintf(buf, buflen, "%s%+ld", arg->value,
1481                                  arg->ref->offset);
1482         else
1483                 ret = e_snprintf(buf, buflen, "%s", arg->value);
1484         if (ret < 0)
1485                 return ret;
1486         buf += ret;
1487         buflen -= ret;
1488
1489         /* Closing */
1490         while (depth--) {
1491                 ret = e_snprintf(buf, buflen, ")");
1492                 if (ret < 0)
1493                         return ret;
1494                 buf += ret;
1495                 buflen -= ret;
1496         }
1497         /* Print argument type */
1498         if (arg->type) {
1499                 ret = e_snprintf(buf, buflen, ":%s", arg->type);
1500                 if (ret <= 0)
1501                         return ret;
1502                 buf += ret;
1503         }
1504
1505         return buf - tmp;
1506 }
1507
1508 char *synthesize_probe_trace_command(struct probe_trace_event *tev)
1509 {
1510         struct probe_trace_point *tp = &tev->point;
1511         char *buf;
1512         int i, len, ret;
1513
1514         buf = zalloc(MAX_CMDLEN);
1515         if (buf == NULL)
1516                 return NULL;
1517
1518         if (tev->uprobes)
1519                 len = e_snprintf(buf, MAX_CMDLEN, "%c:%s/%s %s:%s",
1520                                  tp->retprobe ? 'r' : 'p',
1521                                  tev->group, tev->event,
1522                                  tp->module, tp->symbol);
1523         else
1524                 len = e_snprintf(buf, MAX_CMDLEN, "%c:%s/%s %s%s%s+%lu",
1525                                  tp->retprobe ? 'r' : 'p',
1526                                  tev->group, tev->event,
1527                                  tp->module ?: "", tp->module ? ":" : "",
1528                                  tp->symbol, tp->offset);
1529
1530         if (len <= 0)
1531                 goto error;
1532
1533         for (i = 0; i < tev->nargs; i++) {
1534                 ret = synthesize_probe_trace_arg(&tev->args[i], buf + len,
1535                                                   MAX_CMDLEN - len);
1536                 if (ret <= 0)
1537                         goto error;
1538                 len += ret;
1539         }
1540
1541         return buf;
1542 error:
1543         free(buf);
1544         return NULL;
1545 }
1546
1547 static int convert_to_perf_probe_event(struct probe_trace_event *tev,
1548                                struct perf_probe_event *pev, bool is_kprobe)
1549 {
1550         char buf[64] = "";
1551         int i, ret;
1552
1553         /* Convert event/group name */
1554         pev->event = strdup(tev->event);
1555         pev->group = strdup(tev->group);
1556         if (pev->event == NULL || pev->group == NULL)
1557                 return -ENOMEM;
1558
1559         /* Convert trace_point to probe_point */
1560         if (is_kprobe)
1561                 ret = kprobe_convert_to_perf_probe(&tev->point, &pev->point);
1562         else
1563                 ret = convert_to_perf_probe_point(&tev->point, &pev->point);
1564
1565         if (ret < 0)
1566                 return ret;
1567
1568         /* Convert trace_arg to probe_arg */
1569         pev->nargs = tev->nargs;
1570         pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1571         if (pev->args == NULL)
1572                 return -ENOMEM;
1573         for (i = 0; i < tev->nargs && ret >= 0; i++) {
1574                 if (tev->args[i].name)
1575                         pev->args[i].name = strdup(tev->args[i].name);
1576                 else {
1577                         ret = synthesize_probe_trace_arg(&tev->args[i],
1578                                                           buf, 64);
1579                         pev->args[i].name = strdup(buf);
1580                 }
1581                 if (pev->args[i].name == NULL && ret >= 0)
1582                         ret = -ENOMEM;
1583         }
1584
1585         if (ret < 0)
1586                 clear_perf_probe_event(pev);
1587
1588         return ret;
1589 }
1590
1591 void clear_perf_probe_event(struct perf_probe_event *pev)
1592 {
1593         struct perf_probe_point *pp = &pev->point;
1594         struct perf_probe_arg_field *field, *next;
1595         int i;
1596
1597         free(pev->event);
1598         free(pev->group);
1599         free(pp->file);
1600         free(pp->function);
1601         free(pp->lazy_line);
1602
1603         for (i = 0; i < pev->nargs; i++) {
1604                 free(pev->args[i].name);
1605                 free(pev->args[i].var);
1606                 free(pev->args[i].type);
1607                 field = pev->args[i].field;
1608                 while (field) {
1609                         next = field->next;
1610                         zfree(&field->name);
1611                         free(field);
1612                         field = next;
1613                 }
1614         }
1615         free(pev->args);
1616         memset(pev, 0, sizeof(*pev));
1617 }
1618
1619 static void clear_probe_trace_event(struct probe_trace_event *tev)
1620 {
1621         struct probe_trace_arg_ref *ref, *next;
1622         int i;
1623
1624         free(tev->event);
1625         free(tev->group);
1626         free(tev->point.symbol);
1627         free(tev->point.module);
1628         for (i = 0; i < tev->nargs; i++) {
1629                 free(tev->args[i].name);
1630                 free(tev->args[i].value);
1631                 free(tev->args[i].type);
1632                 ref = tev->args[i].ref;
1633                 while (ref) {
1634                         next = ref->next;
1635                         free(ref);
1636                         ref = next;
1637                 }
1638         }
1639         free(tev->args);
1640         memset(tev, 0, sizeof(*tev));
1641 }
1642
1643 static void print_warn_msg(const char *file, bool is_kprobe)
1644 {
1645
1646         if (errno == ENOENT) {
1647                 const char *config;
1648
1649                 if (!is_kprobe)
1650                         config = "CONFIG_UPROBE_EVENTS";
1651                 else
1652                         config = "CONFIG_KPROBE_EVENTS";
1653
1654                 pr_warning("%s file does not exist - please rebuild kernel"
1655                                 " with %s.\n", file, config);
1656         } else
1657                 pr_warning("Failed to open %s file: %s\n", file,
1658                                 strerror(errno));
1659 }
1660
1661 static int open_probe_events(const char *trace_file, bool readwrite,
1662                                 bool is_kprobe)
1663 {
1664         char buf[PATH_MAX];
1665         const char *__debugfs;
1666         int ret;
1667
1668         __debugfs = debugfs_find_mountpoint();
1669         if (__debugfs == NULL) {
1670                 pr_warning("Debugfs is not mounted.\n");
1671                 return -ENOENT;
1672         }
1673
1674         ret = e_snprintf(buf, PATH_MAX, "%s/%s", __debugfs, trace_file);
1675         if (ret >= 0) {
1676                 pr_debug("Opening %s write=%d\n", buf, readwrite);
1677                 if (readwrite && !probe_event_dry_run)
1678                         ret = open(buf, O_RDWR, O_APPEND);
1679                 else
1680                         ret = open(buf, O_RDONLY, 0);
1681
1682                 if (ret < 0)
1683                         print_warn_msg(buf, is_kprobe);
1684         }
1685         return ret;
1686 }
1687
1688 static int open_kprobe_events(bool readwrite)
1689 {
1690         return open_probe_events("tracing/kprobe_events", readwrite, true);
1691 }
1692
1693 static int open_uprobe_events(bool readwrite)
1694 {
1695         return open_probe_events("tracing/uprobe_events", readwrite, false);
1696 }
1697
1698 /* Get raw string list of current kprobe_events  or uprobe_events */
1699 static struct strlist *get_probe_trace_command_rawlist(int fd)
1700 {
1701         int ret, idx;
1702         FILE *fp;
1703         char buf[MAX_CMDLEN];
1704         char *p;
1705         struct strlist *sl;
1706
1707         sl = strlist__new(true, NULL);
1708
1709         fp = fdopen(dup(fd), "r");
1710         while (!feof(fp)) {
1711                 p = fgets(buf, MAX_CMDLEN, fp);
1712                 if (!p)
1713                         break;
1714
1715                 idx = strlen(p) - 1;
1716                 if (p[idx] == '\n')
1717                         p[idx] = '\0';
1718                 ret = strlist__add(sl, buf);
1719                 if (ret < 0) {
1720                         pr_debug("strlist__add failed: %s\n", strerror(-ret));
1721                         strlist__delete(sl);
1722                         return NULL;
1723                 }
1724         }
1725         fclose(fp);
1726
1727         return sl;
1728 }
1729
1730 /* Show an event */
1731 static int show_perf_probe_event(struct perf_probe_event *pev)
1732 {
1733         int i, ret;
1734         char buf[128];
1735         char *place;
1736
1737         /* Synthesize only event probe point */
1738         place = synthesize_perf_probe_point(&pev->point);
1739         if (!place)
1740                 return -EINVAL;
1741
1742         ret = e_snprintf(buf, 128, "%s:%s", pev->group, pev->event);
1743         if (ret < 0)
1744                 return ret;
1745
1746         printf("  %-20s (on %s", buf, place);
1747
1748         if (pev->nargs > 0) {
1749                 printf(" with");
1750                 for (i = 0; i < pev->nargs; i++) {
1751                         ret = synthesize_perf_probe_arg(&pev->args[i],
1752                                                         buf, 128);
1753                         if (ret < 0)
1754                                 break;
1755                         printf(" %s", buf);
1756                 }
1757         }
1758         printf(")\n");
1759         free(place);
1760         return ret;
1761 }
1762
1763 static int __show_perf_probe_events(int fd, bool is_kprobe)
1764 {
1765         int ret = 0;
1766         struct probe_trace_event tev;
1767         struct perf_probe_event pev;
1768         struct strlist *rawlist;
1769         struct str_node *ent;
1770
1771         memset(&tev, 0, sizeof(tev));
1772         memset(&pev, 0, sizeof(pev));
1773
1774         rawlist = get_probe_trace_command_rawlist(fd);
1775         if (!rawlist)
1776                 return -ENOENT;
1777
1778         strlist__for_each(ent, rawlist) {
1779                 ret = parse_probe_trace_command(ent->s, &tev);
1780                 if (ret >= 0) {
1781                         ret = convert_to_perf_probe_event(&tev, &pev,
1782                                                                 is_kprobe);
1783                         if (ret >= 0)
1784                                 ret = show_perf_probe_event(&pev);
1785                 }
1786                 clear_perf_probe_event(&pev);
1787                 clear_probe_trace_event(&tev);
1788                 if (ret < 0)
1789                         break;
1790         }
1791         strlist__delete(rawlist);
1792
1793         return ret;
1794 }
1795
1796 /* List up current perf-probe events */
1797 int show_perf_probe_events(void)
1798 {
1799         int fd, ret;
1800
1801         setup_pager();
1802         fd = open_kprobe_events(false);
1803
1804         if (fd < 0)
1805                 return fd;
1806
1807         ret = init_symbol_maps(false);
1808         if (ret < 0)
1809                 return ret;
1810
1811         ret = __show_perf_probe_events(fd, true);
1812         close(fd);
1813
1814         fd = open_uprobe_events(false);
1815         if (fd >= 0) {
1816                 ret = __show_perf_probe_events(fd, false);
1817                 close(fd);
1818         }
1819
1820         exit_symbol_maps();
1821         return ret;
1822 }
1823
1824 /* Get current perf-probe event names */
1825 static struct strlist *get_probe_trace_event_names(int fd, bool include_group)
1826 {
1827         char buf[128];
1828         struct strlist *sl, *rawlist;
1829         struct str_node *ent;
1830         struct probe_trace_event tev;
1831         int ret = 0;
1832
1833         memset(&tev, 0, sizeof(tev));
1834         rawlist = get_probe_trace_command_rawlist(fd);
1835         sl = strlist__new(true, NULL);
1836         strlist__for_each(ent, rawlist) {
1837                 ret = parse_probe_trace_command(ent->s, &tev);
1838                 if (ret < 0)
1839                         break;
1840                 if (include_group) {
1841                         ret = e_snprintf(buf, 128, "%s:%s", tev.group,
1842                                         tev.event);
1843                         if (ret >= 0)
1844                                 ret = strlist__add(sl, buf);
1845                 } else
1846                         ret = strlist__add(sl, tev.event);
1847                 clear_probe_trace_event(&tev);
1848                 if (ret < 0)
1849                         break;
1850         }
1851         strlist__delete(rawlist);
1852
1853         if (ret < 0) {
1854                 strlist__delete(sl);
1855                 return NULL;
1856         }
1857         return sl;
1858 }
1859
1860 static int write_probe_trace_event(int fd, struct probe_trace_event *tev)
1861 {
1862         int ret = 0;
1863         char *buf = synthesize_probe_trace_command(tev);
1864
1865         if (!buf) {
1866                 pr_debug("Failed to synthesize probe trace event.\n");
1867                 return -EINVAL;
1868         }
1869
1870         pr_debug("Writing event: %s\n", buf);
1871         if (!probe_event_dry_run) {
1872                 ret = write(fd, buf, strlen(buf));
1873                 if (ret <= 0)
1874                         pr_warning("Failed to write event: %s\n",
1875                                    strerror(errno));
1876         }
1877         free(buf);
1878         return ret;
1879 }
1880
1881 static int get_new_event_name(char *buf, size_t len, const char *base,
1882                               struct strlist *namelist, bool allow_suffix)
1883 {
1884         int i, ret;
1885
1886         /* Try no suffix */
1887         ret = e_snprintf(buf, len, "%s", base);
1888         if (ret < 0) {
1889                 pr_debug("snprintf() failed: %s\n", strerror(-ret));
1890                 return ret;
1891         }
1892         if (!strlist__has_entry(namelist, buf))
1893                 return 0;
1894
1895         if (!allow_suffix) {
1896                 pr_warning("Error: event \"%s\" already exists. "
1897                            "(Use -f to force duplicates.)\n", base);
1898                 return -EEXIST;
1899         }
1900
1901         /* Try to add suffix */
1902         for (i = 1; i < MAX_EVENT_INDEX; i++) {
1903                 ret = e_snprintf(buf, len, "%s_%d", base, i);
1904                 if (ret < 0) {
1905                         pr_debug("snprintf() failed: %s\n", strerror(-ret));
1906                         return ret;
1907                 }
1908                 if (!strlist__has_entry(namelist, buf))
1909                         break;
1910         }
1911         if (i == MAX_EVENT_INDEX) {
1912                 pr_warning("Too many events are on the same function.\n");
1913                 ret = -ERANGE;
1914         }
1915
1916         return ret;
1917 }
1918
1919 static int __add_probe_trace_events(struct perf_probe_event *pev,
1920                                      struct probe_trace_event *tevs,
1921                                      int ntevs, bool allow_suffix)
1922 {
1923         int i, fd, ret;
1924         struct probe_trace_event *tev = NULL;
1925         char buf[64];
1926         const char *event, *group;
1927         struct strlist *namelist;
1928
1929         if (pev->uprobes)
1930                 fd = open_uprobe_events(true);
1931         else
1932                 fd = open_kprobe_events(true);
1933
1934         if (fd < 0)
1935                 return fd;
1936         /* Get current event names */
1937         namelist = get_probe_trace_event_names(fd, false);
1938         if (!namelist) {
1939                 pr_debug("Failed to get current event list.\n");
1940                 return -EIO;
1941         }
1942
1943         ret = 0;
1944         printf("Added new event%s\n", (ntevs > 1) ? "s:" : ":");
1945         for (i = 0; i < ntevs; i++) {
1946                 tev = &tevs[i];
1947                 if (pev->event)
1948                         event = pev->event;
1949                 else
1950                         if (pev->point.function)
1951                                 event = pev->point.function;
1952                         else
1953                                 event = tev->point.symbol;
1954                 if (pev->group)
1955                         group = pev->group;
1956                 else
1957                         group = PERFPROBE_GROUP;
1958
1959                 /* Get an unused new event name */
1960                 ret = get_new_event_name(buf, 64, event,
1961                                          namelist, allow_suffix);
1962                 if (ret < 0)
1963                         break;
1964                 event = buf;
1965
1966                 tev->event = strdup(event);
1967                 tev->group = strdup(group);
1968                 if (tev->event == NULL || tev->group == NULL) {
1969                         ret = -ENOMEM;
1970                         break;
1971                 }
1972                 ret = write_probe_trace_event(fd, tev);
1973                 if (ret < 0)
1974                         break;
1975                 /* Add added event name to namelist */
1976                 strlist__add(namelist, event);
1977
1978                 /* Trick here - save current event/group */
1979                 event = pev->event;
1980                 group = pev->group;
1981                 pev->event = tev->event;
1982                 pev->group = tev->group;
1983                 show_perf_probe_event(pev);
1984                 /* Trick here - restore current event/group */
1985                 pev->event = (char *)event;
1986                 pev->group = (char *)group;
1987
1988                 /*
1989                  * Probes after the first probe which comes from same
1990                  * user input are always allowed to add suffix, because
1991                  * there might be several addresses corresponding to
1992                  * one code line.
1993                  */
1994                 allow_suffix = true;
1995         }
1996
1997         if (ret >= 0) {
1998                 /* Show how to use the event. */
1999                 printf("\nYou can now use it in all perf tools, such as:\n\n");
2000                 printf("\tperf record -e %s:%s -aR sleep 1\n\n", tev->group,
2001                          tev->event);
2002         }
2003
2004         strlist__delete(namelist);
2005         close(fd);
2006         return ret;
2007 }
2008
2009 static int convert_to_probe_trace_events(struct perf_probe_event *pev,
2010                                           struct probe_trace_event **tevs,
2011                                           int max_tevs, const char *target)
2012 {
2013         struct symbol *sym;
2014         int ret, i;
2015         struct probe_trace_event *tev;
2016
2017         if (pev->uprobes && !pev->group) {
2018                 /* Replace group name if not given */
2019                 ret = convert_exec_to_group(target, &pev->group);
2020                 if (ret != 0) {
2021                         pr_warning("Failed to make a group name.\n");
2022                         return ret;
2023                 }
2024         }
2025
2026         /* Convert perf_probe_event with debuginfo */
2027         ret = try_to_find_probe_trace_events(pev, tevs, max_tevs, target);
2028         if (ret != 0)
2029                 return ret;     /* Found in debuginfo or got an error */
2030
2031         if (pev->uprobes) {
2032                 ret = convert_name_to_addr(pev, target);
2033                 if (ret < 0)
2034                         return ret;
2035         }
2036
2037         /* Allocate trace event buffer */
2038         tev = *tevs = zalloc(sizeof(struct probe_trace_event));
2039         if (tev == NULL)
2040                 return -ENOMEM;
2041
2042         /* Copy parameters */
2043         tev->point.symbol = strdup(pev->point.function);
2044         if (tev->point.symbol == NULL) {
2045                 ret = -ENOMEM;
2046                 goto error;
2047         }
2048
2049         if (target) {
2050                 tev->point.module = strdup(target);
2051                 if (tev->point.module == NULL) {
2052                         ret = -ENOMEM;
2053                         goto error;
2054                 }
2055         }
2056
2057         tev->point.offset = pev->point.offset;
2058         tev->point.retprobe = pev->point.retprobe;
2059         tev->nargs = pev->nargs;
2060         tev->uprobes = pev->uprobes;
2061
2062         if (tev->nargs) {
2063                 tev->args = zalloc(sizeof(struct probe_trace_arg)
2064                                    * tev->nargs);
2065                 if (tev->args == NULL) {
2066                         ret = -ENOMEM;
2067                         goto error;
2068                 }
2069                 for (i = 0; i < tev->nargs; i++) {
2070                         if (pev->args[i].name) {
2071                                 tev->args[i].name = strdup(pev->args[i].name);
2072                                 if (tev->args[i].name == NULL) {
2073                                         ret = -ENOMEM;
2074                                         goto error;
2075                                 }
2076                         }
2077                         tev->args[i].value = strdup(pev->args[i].var);
2078                         if (tev->args[i].value == NULL) {
2079                                 ret = -ENOMEM;
2080                                 goto error;
2081                         }
2082                         if (pev->args[i].type) {
2083                                 tev->args[i].type = strdup(pev->args[i].type);
2084                                 if (tev->args[i].type == NULL) {
2085                                         ret = -ENOMEM;
2086                                         goto error;
2087                                 }
2088                         }
2089                 }
2090         }
2091
2092         if (pev->uprobes)
2093                 return 1;
2094
2095         /* Currently just checking function name from symbol map */
2096         sym = __find_kernel_function_by_name(tev->point.symbol, NULL);
2097         if (!sym) {
2098                 pr_warning("Kernel symbol \'%s\' not found.\n",
2099                            tev->point.symbol);
2100                 ret = -ENOENT;
2101                 goto error;
2102         } else if (tev->point.offset > sym->end - sym->start) {
2103                 pr_warning("Offset specified is greater than size of %s\n",
2104                            tev->point.symbol);
2105                 ret = -ENOENT;
2106                 goto error;
2107
2108         }
2109
2110         return 1;
2111 error:
2112         clear_probe_trace_event(tev);
2113         free(tev);
2114         *tevs = NULL;
2115         return ret;
2116 }
2117
2118 struct __event_package {
2119         struct perf_probe_event         *pev;
2120         struct probe_trace_event        *tevs;
2121         int                             ntevs;
2122 };
2123
2124 int add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
2125                           int max_tevs, const char *target, bool force_add)
2126 {
2127         int i, j, ret;
2128         struct __event_package *pkgs;
2129
2130         ret = 0;
2131         pkgs = zalloc(sizeof(struct __event_package) * npevs);
2132
2133         if (pkgs == NULL)
2134                 return -ENOMEM;
2135
2136         ret = init_symbol_maps(pevs->uprobes);
2137         if (ret < 0) {
2138                 free(pkgs);
2139                 return ret;
2140         }
2141
2142         /* Loop 1: convert all events */
2143         for (i = 0; i < npevs; i++) {
2144                 pkgs[i].pev = &pevs[i];
2145                 /* Convert with or without debuginfo */
2146                 ret  = convert_to_probe_trace_events(pkgs[i].pev,
2147                                                      &pkgs[i].tevs,
2148                                                      max_tevs,
2149                                                      target);
2150                 if (ret < 0)
2151                         goto end;
2152                 pkgs[i].ntevs = ret;
2153         }
2154
2155         /* Loop 2: add all events */
2156         for (i = 0; i < npevs; i++) {
2157                 ret = __add_probe_trace_events(pkgs[i].pev, pkgs[i].tevs,
2158                                                 pkgs[i].ntevs, force_add);
2159                 if (ret < 0)
2160                         break;
2161         }
2162 end:
2163         /* Loop 3: cleanup and free trace events  */
2164         for (i = 0; i < npevs; i++) {
2165                 for (j = 0; j < pkgs[i].ntevs; j++)
2166                         clear_probe_trace_event(&pkgs[i].tevs[j]);
2167                 zfree(&pkgs[i].tevs);
2168         }
2169         free(pkgs);
2170         exit_symbol_maps();
2171
2172         return ret;
2173 }
2174
2175 static int __del_trace_probe_event(int fd, struct str_node *ent)
2176 {
2177         char *p;
2178         char buf[128];
2179         int ret;
2180
2181         /* Convert from perf-probe event to trace-probe event */
2182         ret = e_snprintf(buf, 128, "-:%s", ent->s);
2183         if (ret < 0)
2184                 goto error;
2185
2186         p = strchr(buf + 2, ':');
2187         if (!p) {
2188                 pr_debug("Internal error: %s should have ':' but not.\n",
2189                          ent->s);
2190                 ret = -ENOTSUP;
2191                 goto error;
2192         }
2193         *p = '/';
2194
2195         pr_debug("Writing event: %s\n", buf);
2196         ret = write(fd, buf, strlen(buf));
2197         if (ret < 0) {
2198                 ret = -errno;
2199                 goto error;
2200         }
2201
2202         printf("Removed event: %s\n", ent->s);
2203         return 0;
2204 error:
2205         pr_warning("Failed to delete event: %s\n", strerror(-ret));
2206         return ret;
2207 }
2208
2209 static int del_trace_probe_event(int fd, const char *buf,
2210                                                   struct strlist *namelist)
2211 {
2212         struct str_node *ent, *n;
2213         int ret = -1;
2214
2215         if (strpbrk(buf, "*?")) { /* Glob-exp */
2216                 strlist__for_each_safe(ent, n, namelist)
2217                         if (strglobmatch(ent->s, buf)) {
2218                                 ret = __del_trace_probe_event(fd, ent);
2219                                 if (ret < 0)
2220                                         break;
2221                                 strlist__remove(namelist, ent);
2222                         }
2223         } else {
2224                 ent = strlist__find(namelist, buf);
2225                 if (ent) {
2226                         ret = __del_trace_probe_event(fd, ent);
2227                         if (ret >= 0)
2228                                 strlist__remove(namelist, ent);
2229                 }
2230         }
2231
2232         return ret;
2233 }
2234
2235 int del_perf_probe_events(struct strlist *dellist)
2236 {
2237         int ret = -1, ufd = -1, kfd = -1;
2238         char buf[128];
2239         const char *group, *event;
2240         char *p, *str;
2241         struct str_node *ent;
2242         struct strlist *namelist = NULL, *unamelist = NULL;
2243
2244         /* Get current event names */
2245         kfd = open_kprobe_events(true);
2246         if (kfd < 0)
2247                 return kfd;
2248
2249         namelist = get_probe_trace_event_names(kfd, true);
2250         ufd = open_uprobe_events(true);
2251
2252         if (ufd >= 0)
2253                 unamelist = get_probe_trace_event_names(ufd, true);
2254
2255         if (namelist == NULL && unamelist == NULL)
2256                 goto error;
2257
2258         strlist__for_each(ent, dellist) {
2259                 str = strdup(ent->s);
2260                 if (str == NULL) {
2261                         ret = -ENOMEM;
2262                         goto error;
2263                 }
2264                 pr_debug("Parsing: %s\n", str);
2265                 p = strchr(str, ':');
2266                 if (p) {
2267                         group = str;
2268                         *p = '\0';
2269                         event = p + 1;
2270                 } else {
2271                         group = "*";
2272                         event = str;
2273                 }
2274
2275                 ret = e_snprintf(buf, 128, "%s:%s", group, event);
2276                 if (ret < 0) {
2277                         pr_err("Failed to copy event.");
2278                         free(str);
2279                         goto error;
2280                 }
2281
2282                 pr_debug("Group: %s, Event: %s\n", group, event);
2283
2284                 if (namelist)
2285                         ret = del_trace_probe_event(kfd, buf, namelist);
2286
2287                 if (unamelist && ret != 0)
2288                         ret = del_trace_probe_event(ufd, buf, unamelist);
2289
2290                 if (ret != 0)
2291                         pr_info("Info: Event \"%s\" does not exist.\n", buf);
2292
2293                 free(str);
2294         }
2295
2296 error:
2297         if (kfd >= 0) {
2298                 strlist__delete(namelist);
2299                 close(kfd);
2300         }
2301
2302         if (ufd >= 0) {
2303                 strlist__delete(unamelist);
2304                 close(ufd);
2305         }
2306
2307         return ret;
2308 }
2309
2310 /* TODO: don't use a global variable for filter ... */
2311 static struct strfilter *available_func_filter;
2312
2313 /*
2314  * If a symbol corresponds to a function with global binding and
2315  * matches filter return 0. For all others return 1.
2316  */
2317 static int filter_available_functions(struct map *map __maybe_unused,
2318                                       struct symbol *sym)
2319 {
2320         if (sym->binding == STB_GLOBAL &&
2321             strfilter__compare(available_func_filter, sym->name))
2322                 return 0;
2323         return 1;
2324 }
2325
2326 int show_available_funcs(const char *target, struct strfilter *_filter,
2327                                         bool user)
2328 {
2329         struct map *map;
2330         int ret;
2331
2332         ret = init_symbol_maps(user);
2333         if (ret < 0)
2334                 return ret;
2335
2336         /* Get a symbol map */
2337         if (user)
2338                 map = dso__new_map(target);
2339         else
2340                 map = kernel_get_module_map(target);
2341         if (!map) {
2342                 pr_err("Failed to get a map for %s\n", (target) ? : "kernel");
2343                 return -EINVAL;
2344         }
2345
2346         /* Load symbols with given filter */
2347         available_func_filter = _filter;
2348         if (map__load(map, filter_available_functions)) {
2349                 pr_err("Failed to load symbols in %s\n", (target) ? : "kernel");
2350                 goto end;
2351         }
2352         if (!dso__sorted_by_name(map->dso, map->type))
2353                 dso__sort_by_name(map->dso, map->type);
2354
2355         /* Show all (filtered) symbols */
2356         setup_pager();
2357         dso__fprintf_symbols_by_name(map->dso, map->type, stdout);
2358 end:
2359         if (user) {
2360                 dso__delete(map->dso);
2361                 map__delete(map);
2362         }
2363         exit_symbol_maps();
2364
2365         return ret;
2366 }
2367
2368 /*
2369  * uprobe_events only accepts address:
2370  * Convert function and any offset to address
2371  */
2372 static int convert_name_to_addr(struct perf_probe_event *pev, const char *exec)
2373 {
2374         struct perf_probe_point *pp = &pev->point;
2375         struct symbol *sym;
2376         struct map *map = NULL;
2377         char *function = NULL;
2378         int ret = -EINVAL;
2379         unsigned long long vaddr = 0;
2380
2381         if (!pp->function) {
2382                 pr_warning("No function specified for uprobes");
2383                 goto out;
2384         }
2385
2386         function = strdup(pp->function);
2387         if (!function) {
2388                 pr_warning("Failed to allocate memory by strdup.\n");
2389                 ret = -ENOMEM;
2390                 goto out;
2391         }
2392
2393         map = dso__new_map(exec);
2394         if (!map) {
2395                 pr_warning("Cannot find appropriate DSO for %s.\n", exec);
2396                 goto out;
2397         }
2398         available_func_filter = strfilter__new(function, NULL);
2399         if (map__load(map, filter_available_functions)) {
2400                 pr_err("Failed to load map.\n");
2401                 goto out;
2402         }
2403
2404         sym = map__find_symbol_by_name(map, function, NULL);
2405         if (!sym) {
2406                 pr_warning("Cannot find %s in DSO %s\n", function, exec);
2407                 goto out;
2408         }
2409
2410         if (map->start > sym->start)
2411                 vaddr = map->start;
2412         vaddr += sym->start + pp->offset + map->pgoff;
2413         pp->offset = 0;
2414
2415         if (!pev->event) {
2416                 pev->event = function;
2417                 function = NULL;
2418         }
2419         if (!pev->group) {
2420                 char *ptr1, *ptr2, *exec_copy;
2421
2422                 pev->group = zalloc(sizeof(char *) * 64);
2423                 exec_copy = strdup(exec);
2424                 if (!exec_copy) {
2425                         ret = -ENOMEM;
2426                         pr_warning("Failed to copy exec string.\n");
2427                         goto out;
2428                 }
2429
2430                 ptr1 = strdup(basename(exec_copy));
2431                 if (ptr1) {
2432                         ptr2 = strpbrk(ptr1, "-._");
2433                         if (ptr2)
2434                                 *ptr2 = '\0';
2435                         e_snprintf(pev->group, 64, "%s_%s", PERFPROBE_GROUP,
2436                                         ptr1);
2437                         free(ptr1);
2438                 }
2439                 free(exec_copy);
2440         }
2441         free(pp->function);
2442         pp->function = zalloc(sizeof(char *) * MAX_PROBE_ARGS);
2443         if (!pp->function) {
2444                 ret = -ENOMEM;
2445                 pr_warning("Failed to allocate memory by zalloc.\n");
2446                 goto out;
2447         }
2448         e_snprintf(pp->function, MAX_PROBE_ARGS, "0x%llx", vaddr);
2449         ret = 0;
2450
2451 out:
2452         if (map) {
2453                 dso__delete(map->dso);
2454                 map__delete(map);
2455         }
2456         if (function)
2457                 free(function);
2458         return ret;
2459 }