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