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