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