Merge branch 'rfc/perf' into perf/core, because it's ready for inclusion
[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)
701 {
702         int ret;
703
704         ret = init_symbol_maps(false);
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(false);
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 {
827         pr_warning("Debuginfo-analysis is not supported.\n");
828         return -ENOSYS;
829 }
830
831 int show_available_vars(struct perf_probe_event *pevs __maybe_unused,
832                         int npevs __maybe_unused, int max_vls __maybe_unused,
833                         const char *module __maybe_unused,
834                         struct strfilter *filter __maybe_unused,
835                         bool externs __maybe_unused)
836 {
837         pr_warning("Debuginfo-analysis is not supported.\n");
838         return -ENOSYS;
839 }
840 #endif
841
842 void line_range__clear(struct line_range *lr)
843 {
844         free(lr->function);
845         free(lr->file);
846         free(lr->path);
847         free(lr->comp_dir);
848         intlist__delete(lr->line_list);
849         memset(lr, 0, sizeof(*lr));
850 }
851
852 int line_range__init(struct line_range *lr)
853 {
854         memset(lr, 0, sizeof(*lr));
855         lr->line_list = intlist__new(NULL);
856         if (!lr->line_list)
857                 return -ENOMEM;
858         else
859                 return 0;
860 }
861
862 static int parse_line_num(char **ptr, int *val, const char *what)
863 {
864         const char *start = *ptr;
865
866         errno = 0;
867         *val = strtol(*ptr, ptr, 0);
868         if (errno || *ptr == start) {
869                 semantic_error("'%s' is not a valid number.\n", what);
870                 return -EINVAL;
871         }
872         return 0;
873 }
874
875 /*
876  * Stuff 'lr' according to the line range described by 'arg'.
877  * The line range syntax is described by:
878  *
879  *         SRC[:SLN[+NUM|-ELN]]
880  *         FNC[@SRC][:SLN[+NUM|-ELN]]
881  */
882 int parse_line_range_desc(const char *arg, struct line_range *lr)
883 {
884         char *range, *file, *name = strdup(arg);
885         int err;
886
887         if (!name)
888                 return -ENOMEM;
889
890         lr->start = 0;
891         lr->end = INT_MAX;
892
893         range = strchr(name, ':');
894         if (range) {
895                 *range++ = '\0';
896
897                 err = parse_line_num(&range, &lr->start, "start line");
898                 if (err)
899                         goto err;
900
901                 if (*range == '+' || *range == '-') {
902                         const char c = *range++;
903
904                         err = parse_line_num(&range, &lr->end, "end line");
905                         if (err)
906                                 goto err;
907
908                         if (c == '+') {
909                                 lr->end += lr->start;
910                                 /*
911                                  * Adjust the number of lines here.
912                                  * If the number of lines == 1, the
913                                  * the end of line should be equal to
914                                  * the start of line.
915                                  */
916                                 lr->end--;
917                         }
918                 }
919
920                 pr_debug("Line range is %d to %d\n", lr->start, lr->end);
921
922                 err = -EINVAL;
923                 if (lr->start > lr->end) {
924                         semantic_error("Start line must be smaller"
925                                        " than end line.\n");
926                         goto err;
927                 }
928                 if (*range != '\0') {
929                         semantic_error("Tailing with invalid str '%s'.\n", range);
930                         goto err;
931                 }
932         }
933
934         file = strchr(name, '@');
935         if (file) {
936                 *file = '\0';
937                 lr->file = strdup(++file);
938                 if (lr->file == NULL) {
939                         err = -ENOMEM;
940                         goto err;
941                 }
942                 lr->function = name;
943         } else if (strchr(name, '.'))
944                 lr->file = name;
945         else
946                 lr->function = name;
947
948         return 0;
949 err:
950         free(name);
951         return err;
952 }
953
954 /* Check the name is good for event/group */
955 static bool check_event_name(const char *name)
956 {
957         if (!isalpha(*name) && *name != '_')
958                 return false;
959         while (*++name != '\0') {
960                 if (!isalpha(*name) && !isdigit(*name) && *name != '_')
961                         return false;
962         }
963         return true;
964 }
965
966 /* Parse probepoint definition. */
967 static int parse_perf_probe_point(char *arg, struct perf_probe_event *pev)
968 {
969         struct perf_probe_point *pp = &pev->point;
970         char *ptr, *tmp;
971         char c, nc = 0;
972         /*
973          * <Syntax>
974          * perf probe [EVENT=]SRC[:LN|;PTN]
975          * perf probe [EVENT=]FUNC[@SRC][+OFFS|%return|:LN|;PAT]
976          *
977          * TODO:Group name support
978          */
979
980         ptr = strpbrk(arg, ";=@+%");
981         if (ptr && *ptr == '=') {       /* Event name */
982                 *ptr = '\0';
983                 tmp = ptr + 1;
984                 if (strchr(arg, ':')) {
985                         semantic_error("Group name is not supported yet.\n");
986                         return -ENOTSUP;
987                 }
988                 if (!check_event_name(arg)) {
989                         semantic_error("%s is bad for event name -it must "
990                                        "follow C symbol-naming rule.\n", arg);
991                         return -EINVAL;
992                 }
993                 pev->event = strdup(arg);
994                 if (pev->event == NULL)
995                         return -ENOMEM;
996                 pev->group = NULL;
997                 arg = tmp;
998         }
999
1000         ptr = strpbrk(arg, ";:+@%");
1001         if (ptr) {
1002                 nc = *ptr;
1003                 *ptr++ = '\0';
1004         }
1005
1006         tmp = strdup(arg);
1007         if (tmp == NULL)
1008                 return -ENOMEM;
1009
1010         /* Check arg is function or file and copy it */
1011         if (strchr(tmp, '.'))   /* File */
1012                 pp->file = tmp;
1013         else                    /* Function */
1014                 pp->function = tmp;
1015
1016         /* Parse other options */
1017         while (ptr) {
1018                 arg = ptr;
1019                 c = nc;
1020                 if (c == ';') { /* Lazy pattern must be the last part */
1021                         pp->lazy_line = strdup(arg);
1022                         if (pp->lazy_line == NULL)
1023                                 return -ENOMEM;
1024                         break;
1025                 }
1026                 ptr = strpbrk(arg, ";:+@%");
1027                 if (ptr) {
1028                         nc = *ptr;
1029                         *ptr++ = '\0';
1030                 }
1031                 switch (c) {
1032                 case ':':       /* Line number */
1033                         pp->line = strtoul(arg, &tmp, 0);
1034                         if (*tmp != '\0') {
1035                                 semantic_error("There is non-digit char"
1036                                                " in line number.\n");
1037                                 return -EINVAL;
1038                         }
1039                         break;
1040                 case '+':       /* Byte offset from a symbol */
1041                         pp->offset = strtoul(arg, &tmp, 0);
1042                         if (*tmp != '\0') {
1043                                 semantic_error("There is non-digit character"
1044                                                 " in offset.\n");
1045                                 return -EINVAL;
1046                         }
1047                         break;
1048                 case '@':       /* File name */
1049                         if (pp->file) {
1050                                 semantic_error("SRC@SRC is not allowed.\n");
1051                                 return -EINVAL;
1052                         }
1053                         pp->file = strdup(arg);
1054                         if (pp->file == NULL)
1055                                 return -ENOMEM;
1056                         break;
1057                 case '%':       /* Probe places */
1058                         if (strcmp(arg, "return") == 0) {
1059                                 pp->retprobe = 1;
1060                         } else {        /* Others not supported yet */
1061                                 semantic_error("%%%s is not supported.\n", arg);
1062                                 return -ENOTSUP;
1063                         }
1064                         break;
1065                 default:        /* Buggy case */
1066                         pr_err("This program has a bug at %s:%d.\n",
1067                                 __FILE__, __LINE__);
1068                         return -ENOTSUP;
1069                         break;
1070                 }
1071         }
1072
1073         /* Exclusion check */
1074         if (pp->lazy_line && pp->line) {
1075                 semantic_error("Lazy pattern can't be used with"
1076                                " line number.\n");
1077                 return -EINVAL;
1078         }
1079
1080         if (pp->lazy_line && pp->offset) {
1081                 semantic_error("Lazy pattern can't be used with offset.\n");
1082                 return -EINVAL;
1083         }
1084
1085         if (pp->line && pp->offset) {
1086                 semantic_error("Offset can't be used with line number.\n");
1087                 return -EINVAL;
1088         }
1089
1090         if (!pp->line && !pp->lazy_line && pp->file && !pp->function) {
1091                 semantic_error("File always requires line number or "
1092                                "lazy pattern.\n");
1093                 return -EINVAL;
1094         }
1095
1096         if (pp->offset && !pp->function) {
1097                 semantic_error("Offset requires an entry function.\n");
1098                 return -EINVAL;
1099         }
1100
1101         if (pp->retprobe && !pp->function) {
1102                 semantic_error("Return probe requires an entry function.\n");
1103                 return -EINVAL;
1104         }
1105
1106         if ((pp->offset || pp->line || pp->lazy_line) && pp->retprobe) {
1107                 semantic_error("Offset/Line/Lazy pattern can't be used with "
1108                                "return probe.\n");
1109                 return -EINVAL;
1110         }
1111
1112         pr_debug("symbol:%s file:%s line:%d offset:%lu return:%d lazy:%s\n",
1113                  pp->function, pp->file, pp->line, pp->offset, pp->retprobe,
1114                  pp->lazy_line);
1115         return 0;
1116 }
1117
1118 /* Parse perf-probe event argument */
1119 static int parse_perf_probe_arg(char *str, struct perf_probe_arg *arg)
1120 {
1121         char *tmp, *goodname;
1122         struct perf_probe_arg_field **fieldp;
1123
1124         pr_debug("parsing arg: %s into ", str);
1125
1126         tmp = strchr(str, '=');
1127         if (tmp) {
1128                 arg->name = strndup(str, tmp - str);
1129                 if (arg->name == NULL)
1130                         return -ENOMEM;
1131                 pr_debug("name:%s ", arg->name);
1132                 str = tmp + 1;
1133         }
1134
1135         tmp = strchr(str, ':');
1136         if (tmp) {      /* Type setting */
1137                 *tmp = '\0';
1138                 arg->type = strdup(tmp + 1);
1139                 if (arg->type == NULL)
1140                         return -ENOMEM;
1141                 pr_debug("type:%s ", arg->type);
1142         }
1143
1144         tmp = strpbrk(str, "-.[");
1145         if (!is_c_varname(str) || !tmp) {
1146                 /* A variable, register, symbol or special value */
1147                 arg->var = strdup(str);
1148                 if (arg->var == NULL)
1149                         return -ENOMEM;
1150                 pr_debug("%s\n", arg->var);
1151                 return 0;
1152         }
1153
1154         /* Structure fields or array element */
1155         arg->var = strndup(str, tmp - str);
1156         if (arg->var == NULL)
1157                 return -ENOMEM;
1158         goodname = arg->var;
1159         pr_debug("%s, ", arg->var);
1160         fieldp = &arg->field;
1161
1162         do {
1163                 *fieldp = zalloc(sizeof(struct perf_probe_arg_field));
1164                 if (*fieldp == NULL)
1165                         return -ENOMEM;
1166                 if (*tmp == '[') {      /* Array */
1167                         str = tmp;
1168                         (*fieldp)->index = strtol(str + 1, &tmp, 0);
1169                         (*fieldp)->ref = true;
1170                         if (*tmp != ']' || tmp == str + 1) {
1171                                 semantic_error("Array index must be a"
1172                                                 " number.\n");
1173                                 return -EINVAL;
1174                         }
1175                         tmp++;
1176                         if (*tmp == '\0')
1177                                 tmp = NULL;
1178                 } else {                /* Structure */
1179                         if (*tmp == '.') {
1180                                 str = tmp + 1;
1181                                 (*fieldp)->ref = false;
1182                         } else if (tmp[1] == '>') {
1183                                 str = tmp + 2;
1184                                 (*fieldp)->ref = true;
1185                         } else {
1186                                 semantic_error("Argument parse error: %s\n",
1187                                                str);
1188                                 return -EINVAL;
1189                         }
1190                         tmp = strpbrk(str, "-.[");
1191                 }
1192                 if (tmp) {
1193                         (*fieldp)->name = strndup(str, tmp - str);
1194                         if ((*fieldp)->name == NULL)
1195                                 return -ENOMEM;
1196                         if (*str != '[')
1197                                 goodname = (*fieldp)->name;
1198                         pr_debug("%s(%d), ", (*fieldp)->name, (*fieldp)->ref);
1199                         fieldp = &(*fieldp)->next;
1200                 }
1201         } while (tmp);
1202         (*fieldp)->name = strdup(str);
1203         if ((*fieldp)->name == NULL)
1204                 return -ENOMEM;
1205         if (*str != '[')
1206                 goodname = (*fieldp)->name;
1207         pr_debug("%s(%d)\n", (*fieldp)->name, (*fieldp)->ref);
1208
1209         /* If no name is specified, set the last field name (not array index)*/
1210         if (!arg->name) {
1211                 arg->name = strdup(goodname);
1212                 if (arg->name == NULL)
1213                         return -ENOMEM;
1214         }
1215         return 0;
1216 }
1217
1218 /* Parse perf-probe event command */
1219 int parse_perf_probe_command(const char *cmd, struct perf_probe_event *pev)
1220 {
1221         char **argv;
1222         int argc, i, ret = 0;
1223
1224         argv = argv_split(cmd, &argc);
1225         if (!argv) {
1226                 pr_debug("Failed to split arguments.\n");
1227                 return -ENOMEM;
1228         }
1229         if (argc - 1 > MAX_PROBE_ARGS) {
1230                 semantic_error("Too many probe arguments (%d).\n", argc - 1);
1231                 ret = -ERANGE;
1232                 goto out;
1233         }
1234         /* Parse probe point */
1235         ret = parse_perf_probe_point(argv[0], pev);
1236         if (ret < 0)
1237                 goto out;
1238
1239         /* Copy arguments and ensure return probe has no C argument */
1240         pev->nargs = argc - 1;
1241         pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1242         if (pev->args == NULL) {
1243                 ret = -ENOMEM;
1244                 goto out;
1245         }
1246         for (i = 0; i < pev->nargs && ret >= 0; i++) {
1247                 ret = parse_perf_probe_arg(argv[i + 1], &pev->args[i]);
1248                 if (ret >= 0 &&
1249                     is_c_varname(pev->args[i].var) && pev->point.retprobe) {
1250                         semantic_error("You can't specify local variable for"
1251                                        " kretprobe.\n");
1252                         ret = -EINVAL;
1253                 }
1254         }
1255 out:
1256         argv_free(argv);
1257
1258         return ret;
1259 }
1260
1261 /* Return true if this perf_probe_event requires debuginfo */
1262 bool perf_probe_event_need_dwarf(struct perf_probe_event *pev)
1263 {
1264         int i;
1265
1266         if (pev->point.file || pev->point.line || pev->point.lazy_line)
1267                 return true;
1268
1269         for (i = 0; i < pev->nargs; i++)
1270                 if (is_c_varname(pev->args[i].var))
1271                         return true;
1272
1273         return false;
1274 }
1275
1276 /* Parse probe_events event into struct probe_point */
1277 static int parse_probe_trace_command(const char *cmd,
1278                                      struct probe_trace_event *tev)
1279 {
1280         struct probe_trace_point *tp = &tev->point;
1281         char pr;
1282         char *p;
1283         char *argv0_str = NULL, *fmt, *fmt1_str, *fmt2_str, *fmt3_str;
1284         int ret, i, argc;
1285         char **argv;
1286
1287         pr_debug("Parsing probe_events: %s\n", cmd);
1288         argv = argv_split(cmd, &argc);
1289         if (!argv) {
1290                 pr_debug("Failed to split arguments.\n");
1291                 return -ENOMEM;
1292         }
1293         if (argc < 2) {
1294                 semantic_error("Too few probe arguments.\n");
1295                 ret = -ERANGE;
1296                 goto out;
1297         }
1298
1299         /* Scan event and group name. */
1300         argv0_str = strdup(argv[0]);
1301         if (argv0_str == NULL) {
1302                 ret = -ENOMEM;
1303                 goto out;
1304         }
1305         fmt1_str = strtok_r(argv0_str, ":", &fmt);
1306         fmt2_str = strtok_r(NULL, "/", &fmt);
1307         fmt3_str = strtok_r(NULL, " \t", &fmt);
1308         if (fmt1_str == NULL || strlen(fmt1_str) != 1 || fmt2_str == NULL
1309             || fmt3_str == NULL) {
1310                 semantic_error("Failed to parse event name: %s\n", argv[0]);
1311                 ret = -EINVAL;
1312                 goto out;
1313         }
1314         pr = fmt1_str[0];
1315         tev->group = strdup(fmt2_str);
1316         tev->event = strdup(fmt3_str);
1317         if (tev->group == NULL || tev->event == NULL) {
1318                 ret = -ENOMEM;
1319                 goto out;
1320         }
1321         pr_debug("Group:%s Event:%s probe:%c\n", tev->group, tev->event, pr);
1322
1323         tp->retprobe = (pr == 'r');
1324
1325         /* Scan module name(if there), function name and offset */
1326         p = strchr(argv[1], ':');
1327         if (p) {
1328                 tp->module = strndup(argv[1], p - argv[1]);
1329                 p++;
1330         } else
1331                 p = argv[1];
1332         fmt1_str = strtok_r(p, "+", &fmt);
1333         if (fmt1_str[0] == '0') /* only the address started with 0x */
1334                 tp->address = strtoul(fmt1_str, NULL, 0);
1335         else {
1336                 /* Only the symbol-based probe has offset */
1337                 tp->symbol = strdup(fmt1_str);
1338                 if (tp->symbol == NULL) {
1339                         ret = -ENOMEM;
1340                         goto out;
1341                 }
1342                 fmt2_str = strtok_r(NULL, "", &fmt);
1343                 if (fmt2_str == NULL)
1344                         tp->offset = 0;
1345                 else
1346                         tp->offset = strtoul(fmt2_str, NULL, 10);
1347         }
1348
1349         tev->nargs = argc - 2;
1350         tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
1351         if (tev->args == NULL) {
1352                 ret = -ENOMEM;
1353                 goto out;
1354         }
1355         for (i = 0; i < tev->nargs; i++) {
1356                 p = strchr(argv[i + 2], '=');
1357                 if (p)  /* We don't need which register is assigned. */
1358                         *p++ = '\0';
1359                 else
1360                         p = argv[i + 2];
1361                 tev->args[i].name = strdup(argv[i + 2]);
1362                 /* TODO: parse regs and offset */
1363                 tev->args[i].value = strdup(p);
1364                 if (tev->args[i].name == NULL || tev->args[i].value == NULL) {
1365                         ret = -ENOMEM;
1366                         goto out;
1367                 }
1368         }
1369         ret = 0;
1370 out:
1371         free(argv0_str);
1372         argv_free(argv);
1373         return ret;
1374 }
1375
1376 /* Compose only probe arg */
1377 int synthesize_perf_probe_arg(struct perf_probe_arg *pa, char *buf, size_t len)
1378 {
1379         struct perf_probe_arg_field *field = pa->field;
1380         int ret;
1381         char *tmp = buf;
1382
1383         if (pa->name && pa->var)
1384                 ret = e_snprintf(tmp, len, "%s=%s", pa->name, pa->var);
1385         else
1386                 ret = e_snprintf(tmp, len, "%s", pa->name ? pa->name : pa->var);
1387         if (ret <= 0)
1388                 goto error;
1389         tmp += ret;
1390         len -= ret;
1391
1392         while (field) {
1393                 if (field->name[0] == '[')
1394                         ret = e_snprintf(tmp, len, "%s", field->name);
1395                 else
1396                         ret = e_snprintf(tmp, len, "%s%s",
1397                                          field->ref ? "->" : ".", field->name);
1398                 if (ret <= 0)
1399                         goto error;
1400                 tmp += ret;
1401                 len -= ret;
1402                 field = field->next;
1403         }
1404
1405         if (pa->type) {
1406                 ret = e_snprintf(tmp, len, ":%s", pa->type);
1407                 if (ret <= 0)
1408                         goto error;
1409                 tmp += ret;
1410                 len -= ret;
1411         }
1412
1413         return tmp - buf;
1414 error:
1415         pr_debug("Failed to synthesize perf probe argument: %d\n", ret);
1416         return ret;
1417 }
1418
1419 /* Compose only probe point (not argument) */
1420 static char *synthesize_perf_probe_point(struct perf_probe_point *pp)
1421 {
1422         char *buf, *tmp;
1423         char offs[32] = "", line[32] = "", file[32] = "";
1424         int ret, len;
1425
1426         buf = zalloc(MAX_CMDLEN);
1427         if (buf == NULL) {
1428                 ret = -ENOMEM;
1429                 goto error;
1430         }
1431         if (pp->offset) {
1432                 ret = e_snprintf(offs, 32, "+%lu", pp->offset);
1433                 if (ret <= 0)
1434                         goto error;
1435         }
1436         if (pp->line) {
1437                 ret = e_snprintf(line, 32, ":%d", pp->line);
1438                 if (ret <= 0)
1439                         goto error;
1440         }
1441         if (pp->file) {
1442                 tmp = pp->file;
1443                 len = strlen(tmp);
1444                 if (len > 30) {
1445                         tmp = strchr(pp->file + len - 30, '/');
1446                         tmp = tmp ? tmp + 1 : pp->file + len - 30;
1447                 }
1448                 ret = e_snprintf(file, 32, "@%s", tmp);
1449                 if (ret <= 0)
1450                         goto error;
1451         }
1452
1453         if (pp->function)
1454                 ret = e_snprintf(buf, MAX_CMDLEN, "%s%s%s%s%s", pp->function,
1455                                  offs, pp->retprobe ? "%return" : "", line,
1456                                  file);
1457         else
1458                 ret = e_snprintf(buf, MAX_CMDLEN, "%s%s", file, line);
1459         if (ret <= 0)
1460                 goto error;
1461
1462         return buf;
1463 error:
1464         pr_debug("Failed to synthesize perf probe point: %d\n", ret);
1465         free(buf);
1466         return NULL;
1467 }
1468
1469 #if 0
1470 char *synthesize_perf_probe_command(struct perf_probe_event *pev)
1471 {
1472         char *buf;
1473         int i, len, ret;
1474
1475         buf = synthesize_perf_probe_point(&pev->point);
1476         if (!buf)
1477                 return NULL;
1478
1479         len = strlen(buf);
1480         for (i = 0; i < pev->nargs; i++) {
1481                 ret = e_snprintf(&buf[len], MAX_CMDLEN - len, " %s",
1482                                  pev->args[i].name);
1483                 if (ret <= 0) {
1484                         free(buf);
1485                         return NULL;
1486                 }
1487                 len += ret;
1488         }
1489
1490         return buf;
1491 }
1492 #endif
1493
1494 static int __synthesize_probe_trace_arg_ref(struct probe_trace_arg_ref *ref,
1495                                              char **buf, size_t *buflen,
1496                                              int depth)
1497 {
1498         int ret;
1499         if (ref->next) {
1500                 depth = __synthesize_probe_trace_arg_ref(ref->next, buf,
1501                                                          buflen, depth + 1);
1502                 if (depth < 0)
1503                         goto out;
1504         }
1505
1506         ret = e_snprintf(*buf, *buflen, "%+ld(", ref->offset);
1507         if (ret < 0)
1508                 depth = ret;
1509         else {
1510                 *buf += ret;
1511                 *buflen -= ret;
1512         }
1513 out:
1514         return depth;
1515
1516 }
1517
1518 static int synthesize_probe_trace_arg(struct probe_trace_arg *arg,
1519                                        char *buf, size_t buflen)
1520 {
1521         struct probe_trace_arg_ref *ref = arg->ref;
1522         int ret, depth = 0;
1523         char *tmp = buf;
1524
1525         /* Argument name or separator */
1526         if (arg->name)
1527                 ret = e_snprintf(buf, buflen, " %s=", arg->name);
1528         else
1529                 ret = e_snprintf(buf, buflen, " ");
1530         if (ret < 0)
1531                 return ret;
1532         buf += ret;
1533         buflen -= ret;
1534
1535         /* Special case: @XXX */
1536         if (arg->value[0] == '@' && arg->ref)
1537                         ref = ref->next;
1538
1539         /* Dereferencing arguments */
1540         if (ref) {
1541                 depth = __synthesize_probe_trace_arg_ref(ref, &buf,
1542                                                           &buflen, 1);
1543                 if (depth < 0)
1544                         return depth;
1545         }
1546
1547         /* Print argument value */
1548         if (arg->value[0] == '@' && arg->ref)
1549                 ret = e_snprintf(buf, buflen, "%s%+ld", arg->value,
1550                                  arg->ref->offset);
1551         else
1552                 ret = e_snprintf(buf, buflen, "%s", arg->value);
1553         if (ret < 0)
1554                 return ret;
1555         buf += ret;
1556         buflen -= ret;
1557
1558         /* Closing */
1559         while (depth--) {
1560                 ret = e_snprintf(buf, buflen, ")");
1561                 if (ret < 0)
1562                         return ret;
1563                 buf += ret;
1564                 buflen -= ret;
1565         }
1566         /* Print argument type */
1567         if (arg->type) {
1568                 ret = e_snprintf(buf, buflen, ":%s", arg->type);
1569                 if (ret <= 0)
1570                         return ret;
1571                 buf += ret;
1572         }
1573
1574         return buf - tmp;
1575 }
1576
1577 char *synthesize_probe_trace_command(struct probe_trace_event *tev)
1578 {
1579         struct probe_trace_point *tp = &tev->point;
1580         char *buf;
1581         int i, len, ret;
1582
1583         buf = zalloc(MAX_CMDLEN);
1584         if (buf == NULL)
1585                 return NULL;
1586
1587         len = e_snprintf(buf, MAX_CMDLEN, "%c:%s/%s ", tp->retprobe ? 'r' : 'p',
1588                          tev->group, tev->event);
1589         if (len <= 0)
1590                 goto error;
1591
1592         /* Uprobes must have tp->address and tp->module */
1593         if (tev->uprobes && (!tp->address || !tp->module))
1594                 goto error;
1595
1596         /* Use the tp->address for uprobes */
1597         if (tev->uprobes)
1598                 ret = e_snprintf(buf + len, MAX_CMDLEN - len, "%s:0x%lx",
1599                                  tp->module, tp->address);
1600         else
1601                 ret = e_snprintf(buf + len, MAX_CMDLEN - len, "%s%s%s+%lu",
1602                                  tp->module ?: "", tp->module ? ":" : "",
1603                                  tp->symbol, tp->offset);
1604
1605         if (ret <= 0)
1606                 goto error;
1607         len += ret;
1608
1609         for (i = 0; i < tev->nargs; i++) {
1610                 ret = synthesize_probe_trace_arg(&tev->args[i], buf + len,
1611                                                   MAX_CMDLEN - len);
1612                 if (ret <= 0)
1613                         goto error;
1614                 len += ret;
1615         }
1616
1617         return buf;
1618 error:
1619         free(buf);
1620         return NULL;
1621 }
1622
1623 static int find_perf_probe_point_from_map(struct probe_trace_point *tp,
1624                                           struct perf_probe_point *pp,
1625                                           bool is_kprobe)
1626 {
1627         struct symbol *sym = NULL;
1628         struct map *map;
1629         u64 addr;
1630         int ret = -ENOENT;
1631
1632         if (!is_kprobe) {
1633                 map = dso__new_map(tp->module);
1634                 if (!map)
1635                         goto out;
1636                 addr = tp->address;
1637                 sym = map__find_symbol(map, addr, NULL);
1638         } else {
1639                 addr = kernel_get_symbol_address_by_name(tp->symbol, true);
1640                 if (addr) {
1641                         addr += tp->offset;
1642                         sym = __find_kernel_function(addr, &map);
1643                 }
1644         }
1645         if (!sym)
1646                 goto out;
1647
1648         pp->retprobe = tp->retprobe;
1649         pp->offset = addr - map->unmap_ip(map, sym->start);
1650         pp->function = strdup(sym->name);
1651         ret = pp->function ? 0 : -ENOMEM;
1652
1653 out:
1654         if (map && !is_kprobe) {
1655                 dso__delete(map->dso);
1656                 map__delete(map);
1657         }
1658
1659         return ret;
1660 }
1661
1662 static int convert_to_perf_probe_point(struct probe_trace_point *tp,
1663                                         struct perf_probe_point *pp,
1664                                         bool is_kprobe)
1665 {
1666         char buf[128];
1667         int ret;
1668
1669         ret = find_perf_probe_point_from_dwarf(tp, pp, is_kprobe);
1670         if (!ret)
1671                 return 0;
1672         ret = find_perf_probe_point_from_map(tp, pp, is_kprobe);
1673         if (!ret)
1674                 return 0;
1675
1676         pr_debug("Failed to find probe point from both of dwarf and map.\n");
1677
1678         if (tp->symbol) {
1679                 pp->function = strdup(tp->symbol);
1680                 pp->offset = tp->offset;
1681         } else if (!tp->module && !is_kprobe) {
1682                 ret = e_snprintf(buf, 128, "0x%" PRIx64, (u64)tp->address);
1683                 if (ret < 0)
1684                         return ret;
1685                 pp->function = strdup(buf);
1686                 pp->offset = 0;
1687         }
1688         if (pp->function == NULL)
1689                 return -ENOMEM;
1690
1691         pp->retprobe = tp->retprobe;
1692
1693         return 0;
1694 }
1695
1696 static int convert_to_perf_probe_event(struct probe_trace_event *tev,
1697                                struct perf_probe_event *pev, bool is_kprobe)
1698 {
1699         char buf[64] = "";
1700         int i, ret;
1701
1702         /* Convert event/group name */
1703         pev->event = strdup(tev->event);
1704         pev->group = strdup(tev->group);
1705         if (pev->event == NULL || pev->group == NULL)
1706                 return -ENOMEM;
1707
1708         /* Convert trace_point to probe_point */
1709         ret = convert_to_perf_probe_point(&tev->point, &pev->point, is_kprobe);
1710         if (ret < 0)
1711                 return ret;
1712
1713         /* Convert trace_arg to probe_arg */
1714         pev->nargs = tev->nargs;
1715         pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1716         if (pev->args == NULL)
1717                 return -ENOMEM;
1718         for (i = 0; i < tev->nargs && ret >= 0; i++) {
1719                 if (tev->args[i].name)
1720                         pev->args[i].name = strdup(tev->args[i].name);
1721                 else {
1722                         ret = synthesize_probe_trace_arg(&tev->args[i],
1723                                                           buf, 64);
1724                         pev->args[i].name = strdup(buf);
1725                 }
1726                 if (pev->args[i].name == NULL && ret >= 0)
1727                         ret = -ENOMEM;
1728         }
1729
1730         if (ret < 0)
1731                 clear_perf_probe_event(pev);
1732
1733         return ret;
1734 }
1735
1736 void clear_perf_probe_event(struct perf_probe_event *pev)
1737 {
1738         struct perf_probe_point *pp = &pev->point;
1739         struct perf_probe_arg_field *field, *next;
1740         int i;
1741
1742         free(pev->event);
1743         free(pev->group);
1744         free(pp->file);
1745         free(pp->function);
1746         free(pp->lazy_line);
1747
1748         for (i = 0; i < pev->nargs; i++) {
1749                 free(pev->args[i].name);
1750                 free(pev->args[i].var);
1751                 free(pev->args[i].type);
1752                 field = pev->args[i].field;
1753                 while (field) {
1754                         next = field->next;
1755                         zfree(&field->name);
1756                         free(field);
1757                         field = next;
1758                 }
1759         }
1760         free(pev->args);
1761         memset(pev, 0, sizeof(*pev));
1762 }
1763
1764 static void clear_probe_trace_event(struct probe_trace_event *tev)
1765 {
1766         struct probe_trace_arg_ref *ref, *next;
1767         int i;
1768
1769         free(tev->event);
1770         free(tev->group);
1771         free(tev->point.symbol);
1772         free(tev->point.module);
1773         for (i = 0; i < tev->nargs; i++) {
1774                 free(tev->args[i].name);
1775                 free(tev->args[i].value);
1776                 free(tev->args[i].type);
1777                 ref = tev->args[i].ref;
1778                 while (ref) {
1779                         next = ref->next;
1780                         free(ref);
1781                         ref = next;
1782                 }
1783         }
1784         free(tev->args);
1785         memset(tev, 0, sizeof(*tev));
1786 }
1787
1788 static void print_open_warning(int err, bool is_kprobe)
1789 {
1790         char sbuf[STRERR_BUFSIZE];
1791
1792         if (err == -ENOENT) {
1793                 const char *config;
1794
1795                 if (!is_kprobe)
1796                         config = "CONFIG_UPROBE_EVENTS";
1797                 else
1798                         config = "CONFIG_KPROBE_EVENTS";
1799
1800                 pr_warning("%cprobe_events file does not exist"
1801                            " - please rebuild kernel with %s.\n",
1802                            is_kprobe ? 'k' : 'u', config);
1803         } else if (err == -ENOTSUP)
1804                 pr_warning("Debugfs is not mounted.\n");
1805         else
1806                 pr_warning("Failed to open %cprobe_events: %s\n",
1807                            is_kprobe ? 'k' : 'u',
1808                            strerror_r(-err, sbuf, sizeof(sbuf)));
1809 }
1810
1811 static void print_both_open_warning(int kerr, int uerr)
1812 {
1813         /* Both kprobes and uprobes are disabled, warn it. */
1814         if (kerr == -ENOTSUP && uerr == -ENOTSUP)
1815                 pr_warning("Debugfs is not mounted.\n");
1816         else if (kerr == -ENOENT && uerr == -ENOENT)
1817                 pr_warning("Please rebuild kernel with CONFIG_KPROBE_EVENTS "
1818                            "or/and CONFIG_UPROBE_EVENTS.\n");
1819         else {
1820                 char sbuf[STRERR_BUFSIZE];
1821                 pr_warning("Failed to open kprobe events: %s.\n",
1822                            strerror_r(-kerr, sbuf, sizeof(sbuf)));
1823                 pr_warning("Failed to open uprobe events: %s.\n",
1824                            strerror_r(-uerr, sbuf, sizeof(sbuf)));
1825         }
1826 }
1827
1828 static int open_probe_events(const char *trace_file, bool readwrite)
1829 {
1830         char buf[PATH_MAX];
1831         const char *__debugfs;
1832         int ret;
1833
1834         __debugfs = debugfs_find_mountpoint();
1835         if (__debugfs == NULL)
1836                 return -ENOTSUP;
1837
1838         ret = e_snprintf(buf, PATH_MAX, "%s/%s", __debugfs, trace_file);
1839         if (ret >= 0) {
1840                 pr_debug("Opening %s write=%d\n", buf, readwrite);
1841                 if (readwrite && !probe_event_dry_run)
1842                         ret = open(buf, O_RDWR, O_APPEND);
1843                 else
1844                         ret = open(buf, O_RDONLY, 0);
1845
1846                 if (ret < 0)
1847                         ret = -errno;
1848         }
1849         return ret;
1850 }
1851
1852 static int open_kprobe_events(bool readwrite)
1853 {
1854         return open_probe_events("tracing/kprobe_events", readwrite);
1855 }
1856
1857 static int open_uprobe_events(bool readwrite)
1858 {
1859         return open_probe_events("tracing/uprobe_events", readwrite);
1860 }
1861
1862 /* Get raw string list of current kprobe_events  or uprobe_events */
1863 static struct strlist *get_probe_trace_command_rawlist(int fd)
1864 {
1865         int ret, idx;
1866         FILE *fp;
1867         char buf[MAX_CMDLEN];
1868         char *p;
1869         struct strlist *sl;
1870
1871         sl = strlist__new(true, NULL);
1872
1873         fp = fdopen(dup(fd), "r");
1874         while (!feof(fp)) {
1875                 p = fgets(buf, MAX_CMDLEN, fp);
1876                 if (!p)
1877                         break;
1878
1879                 idx = strlen(p) - 1;
1880                 if (p[idx] == '\n')
1881                         p[idx] = '\0';
1882                 ret = strlist__add(sl, buf);
1883                 if (ret < 0) {
1884                         pr_debug("strlist__add failed (%d)\n", ret);
1885                         strlist__delete(sl);
1886                         return NULL;
1887                 }
1888         }
1889         fclose(fp);
1890
1891         return sl;
1892 }
1893
1894 /* Show an event */
1895 static int show_perf_probe_event(struct perf_probe_event *pev,
1896                                  const char *module)
1897 {
1898         int i, ret;
1899         char buf[128];
1900         char *place;
1901
1902         /* Synthesize only event probe point */
1903         place = synthesize_perf_probe_point(&pev->point);
1904         if (!place)
1905                 return -EINVAL;
1906
1907         ret = e_snprintf(buf, 128, "%s:%s", pev->group, pev->event);
1908         if (ret < 0)
1909                 return ret;
1910
1911         printf("  %-20s (on %s", buf, place);
1912         if (module)
1913                 printf(" in %s", module);
1914
1915         if (pev->nargs > 0) {
1916                 printf(" with");
1917                 for (i = 0; i < pev->nargs; i++) {
1918                         ret = synthesize_perf_probe_arg(&pev->args[i],
1919                                                         buf, 128);
1920                         if (ret < 0)
1921                                 break;
1922                         printf(" %s", buf);
1923                 }
1924         }
1925         printf(")\n");
1926         free(place);
1927         return ret;
1928 }
1929
1930 static int __show_perf_probe_events(int fd, bool is_kprobe)
1931 {
1932         int ret = 0;
1933         struct probe_trace_event tev;
1934         struct perf_probe_event pev;
1935         struct strlist *rawlist;
1936         struct str_node *ent;
1937
1938         memset(&tev, 0, sizeof(tev));
1939         memset(&pev, 0, sizeof(pev));
1940
1941         rawlist = get_probe_trace_command_rawlist(fd);
1942         if (!rawlist)
1943                 return -ENOMEM;
1944
1945         strlist__for_each(ent, rawlist) {
1946                 ret = parse_probe_trace_command(ent->s, &tev);
1947                 if (ret >= 0) {
1948                         ret = convert_to_perf_probe_event(&tev, &pev,
1949                                                                 is_kprobe);
1950                         if (ret >= 0)
1951                                 ret = show_perf_probe_event(&pev,
1952                                                             tev.point.module);
1953                 }
1954                 clear_perf_probe_event(&pev);
1955                 clear_probe_trace_event(&tev);
1956                 if (ret < 0)
1957                         break;
1958         }
1959         strlist__delete(rawlist);
1960
1961         return ret;
1962 }
1963
1964 /* List up current perf-probe events */
1965 int show_perf_probe_events(void)
1966 {
1967         int kp_fd, up_fd, ret;
1968
1969         setup_pager();
1970
1971         ret = init_symbol_maps(false);
1972         if (ret < 0)
1973                 return ret;
1974
1975         kp_fd = open_kprobe_events(false);
1976         if (kp_fd >= 0) {
1977                 ret = __show_perf_probe_events(kp_fd, true);
1978                 close(kp_fd);
1979                 if (ret < 0)
1980                         goto out;
1981         }
1982
1983         up_fd = open_uprobe_events(false);
1984         if (kp_fd < 0 && up_fd < 0) {
1985                 print_both_open_warning(kp_fd, up_fd);
1986                 ret = kp_fd;
1987                 goto out;
1988         }
1989
1990         if (up_fd >= 0) {
1991                 ret = __show_perf_probe_events(up_fd, false);
1992                 close(up_fd);
1993         }
1994 out:
1995         exit_symbol_maps();
1996         return ret;
1997 }
1998
1999 /* Get current perf-probe event names */
2000 static struct strlist *get_probe_trace_event_names(int fd, bool include_group)
2001 {
2002         char buf[128];
2003         struct strlist *sl, *rawlist;
2004         struct str_node *ent;
2005         struct probe_trace_event tev;
2006         int ret = 0;
2007
2008         memset(&tev, 0, sizeof(tev));
2009         rawlist = get_probe_trace_command_rawlist(fd);
2010         if (!rawlist)
2011                 return NULL;
2012         sl = strlist__new(true, NULL);
2013         strlist__for_each(ent, rawlist) {
2014                 ret = parse_probe_trace_command(ent->s, &tev);
2015                 if (ret < 0)
2016                         break;
2017                 if (include_group) {
2018                         ret = e_snprintf(buf, 128, "%s:%s", tev.group,
2019                                         tev.event);
2020                         if (ret >= 0)
2021                                 ret = strlist__add(sl, buf);
2022                 } else
2023                         ret = strlist__add(sl, tev.event);
2024                 clear_probe_trace_event(&tev);
2025                 if (ret < 0)
2026                         break;
2027         }
2028         strlist__delete(rawlist);
2029
2030         if (ret < 0) {
2031                 strlist__delete(sl);
2032                 return NULL;
2033         }
2034         return sl;
2035 }
2036
2037 static int write_probe_trace_event(int fd, struct probe_trace_event *tev)
2038 {
2039         int ret = 0;
2040         char *buf = synthesize_probe_trace_command(tev);
2041         char sbuf[STRERR_BUFSIZE];
2042
2043         if (!buf) {
2044                 pr_debug("Failed to synthesize probe trace event.\n");
2045                 return -EINVAL;
2046         }
2047
2048         pr_debug("Writing event: %s\n", buf);
2049         if (!probe_event_dry_run) {
2050                 ret = write(fd, buf, strlen(buf));
2051                 if (ret <= 0)
2052                         pr_warning("Failed to write event: %s\n",
2053                                    strerror_r(errno, sbuf, sizeof(sbuf)));
2054         }
2055         free(buf);
2056         return ret;
2057 }
2058
2059 static int get_new_event_name(char *buf, size_t len, const char *base,
2060                               struct strlist *namelist, bool allow_suffix)
2061 {
2062         int i, ret;
2063
2064         /* Try no suffix */
2065         ret = e_snprintf(buf, len, "%s", base);
2066         if (ret < 0) {
2067                 pr_debug("snprintf() failed: %d\n", ret);
2068                 return ret;
2069         }
2070         if (!strlist__has_entry(namelist, buf))
2071                 return 0;
2072
2073         if (!allow_suffix) {
2074                 pr_warning("Error: event \"%s\" already exists. "
2075                            "(Use -f to force duplicates.)\n", base);
2076                 return -EEXIST;
2077         }
2078
2079         /* Try to add suffix */
2080         for (i = 1; i < MAX_EVENT_INDEX; i++) {
2081                 ret = e_snprintf(buf, len, "%s_%d", base, i);
2082                 if (ret < 0) {
2083                         pr_debug("snprintf() failed: %d\n", ret);
2084                         return ret;
2085                 }
2086                 if (!strlist__has_entry(namelist, buf))
2087                         break;
2088         }
2089         if (i == MAX_EVENT_INDEX) {
2090                 pr_warning("Too many events are on the same function.\n");
2091                 ret = -ERANGE;
2092         }
2093
2094         return ret;
2095 }
2096
2097 static int __add_probe_trace_events(struct perf_probe_event *pev,
2098                                      struct probe_trace_event *tevs,
2099                                      int ntevs, bool allow_suffix)
2100 {
2101         int i, fd, ret;
2102         struct probe_trace_event *tev = NULL;
2103         char buf[64];
2104         const char *event, *group;
2105         struct strlist *namelist;
2106
2107         if (pev->uprobes)
2108                 fd = open_uprobe_events(true);
2109         else
2110                 fd = open_kprobe_events(true);
2111
2112         if (fd < 0) {
2113                 print_open_warning(fd, !pev->uprobes);
2114                 return fd;
2115         }
2116
2117         /* Get current event names */
2118         namelist = get_probe_trace_event_names(fd, false);
2119         if (!namelist) {
2120                 pr_debug("Failed to get current event list.\n");
2121                 return -EIO;
2122         }
2123
2124         ret = 0;
2125         printf("Added new event%s\n", (ntevs > 1) ? "s:" : ":");
2126         for (i = 0; i < ntevs; i++) {
2127                 tev = &tevs[i];
2128                 if (pev->event)
2129                         event = pev->event;
2130                 else
2131                         if (pev->point.function)
2132                                 event = pev->point.function;
2133                         else
2134                                 event = tev->point.symbol;
2135                 if (pev->group)
2136                         group = pev->group;
2137                 else
2138                         group = PERFPROBE_GROUP;
2139
2140                 /* Get an unused new event name */
2141                 ret = get_new_event_name(buf, 64, event,
2142                                          namelist, allow_suffix);
2143                 if (ret < 0)
2144                         break;
2145                 event = buf;
2146
2147                 tev->event = strdup(event);
2148                 tev->group = strdup(group);
2149                 if (tev->event == NULL || tev->group == NULL) {
2150                         ret = -ENOMEM;
2151                         break;
2152                 }
2153                 ret = write_probe_trace_event(fd, tev);
2154                 if (ret < 0)
2155                         break;
2156                 /* Add added event name to namelist */
2157                 strlist__add(namelist, event);
2158
2159                 /* Trick here - save current event/group */
2160                 event = pev->event;
2161                 group = pev->group;
2162                 pev->event = tev->event;
2163                 pev->group = tev->group;
2164                 show_perf_probe_event(pev, tev->point.module);
2165                 /* Trick here - restore current event/group */
2166                 pev->event = (char *)event;
2167                 pev->group = (char *)group;
2168
2169                 /*
2170                  * Probes after the first probe which comes from same
2171                  * user input are always allowed to add suffix, because
2172                  * there might be several addresses corresponding to
2173                  * one code line.
2174                  */
2175                 allow_suffix = true;
2176         }
2177
2178         if (ret >= 0) {
2179                 /* Show how to use the event. */
2180                 printf("\nYou can now use it in all perf tools, such as:\n\n");
2181                 printf("\tperf record -e %s:%s -aR sleep 1\n\n", tev->group,
2182                          tev->event);
2183         }
2184
2185         strlist__delete(namelist);
2186         close(fd);
2187         return ret;
2188 }
2189
2190 static char *looking_function_name;
2191 static int num_matched_functions;
2192
2193 static int probe_function_filter(struct map *map __maybe_unused,
2194                                       struct symbol *sym)
2195 {
2196         if ((sym->binding == STB_GLOBAL || sym->binding == STB_LOCAL) &&
2197             strcmp(looking_function_name, sym->name) == 0) {
2198                 num_matched_functions++;
2199                 return 0;
2200         }
2201         return 1;
2202 }
2203
2204 #define strdup_or_goto(str, label)      \
2205         ({ char *__p = strdup(str); if (!__p) goto label; __p; })
2206
2207 /*
2208  * Find probe function addresses from map.
2209  * Return an error or the number of found probe_trace_event
2210  */
2211 static int find_probe_trace_events_from_map(struct perf_probe_event *pev,
2212                                             struct probe_trace_event **tevs,
2213                                             int max_tevs, const char *target)
2214 {
2215         struct map *map = NULL;
2216         struct kmap *kmap = NULL;
2217         struct ref_reloc_sym *reloc_sym = NULL;
2218         struct symbol *sym;
2219         struct rb_node *nd;
2220         struct probe_trace_event *tev;
2221         struct perf_probe_point *pp = &pev->point;
2222         struct probe_trace_point *tp;
2223         int ret, i;
2224
2225         /* Init maps of given executable or kernel */
2226         if (pev->uprobes)
2227                 map = dso__new_map(target);
2228         else
2229                 map = kernel_get_module_map(target);
2230         if (!map) {
2231                 ret = -EINVAL;
2232                 goto out;
2233         }
2234
2235         /*
2236          * Load matched symbols: Since the different local symbols may have
2237          * same name but different addresses, this lists all the symbols.
2238          */
2239         num_matched_functions = 0;
2240         looking_function_name = pp->function;
2241         ret = map__load(map, probe_function_filter);
2242         if (ret || num_matched_functions == 0) {
2243                 pr_err("Failed to find symbol %s in %s\n", pp->function,
2244                         target ? : "kernel");
2245                 ret = -ENOENT;
2246                 goto out;
2247         } else if (num_matched_functions > max_tevs) {
2248                 pr_err("Too many functions matched in %s\n",
2249                         target ? : "kernel");
2250                 ret = -E2BIG;
2251                 goto out;
2252         }
2253
2254         if (!pev->uprobes) {
2255                 kmap = map__kmap(map);
2256                 reloc_sym = kmap->ref_reloc_sym;
2257                 if (!reloc_sym) {
2258                         pr_warning("Relocated base symbol is not found!\n");
2259                         ret = -EINVAL;
2260                         goto out;
2261                 }
2262         }
2263
2264         /* Setup result trace-probe-events */
2265         *tevs = zalloc(sizeof(*tev) * num_matched_functions);
2266         if (!*tevs) {
2267                 ret = -ENOMEM;
2268                 goto out;
2269         }
2270
2271         ret = 0;
2272         map__for_each_symbol(map, sym, nd) {
2273                 tev = (*tevs) + ret;
2274                 tp = &tev->point;
2275                 if (ret == num_matched_functions) {
2276                         pr_warning("Too many symbols are listed. Skip it.\n");
2277                         break;
2278                 }
2279                 ret++;
2280
2281                 if (pp->offset > sym->end - sym->start) {
2282                         pr_warning("Offset %ld is bigger than the size of %s\n",
2283                                    pp->offset, sym->name);
2284                         ret = -ENOENT;
2285                         goto err_out;
2286                 }
2287                 /* Add one probe point */
2288                 tp->address = map->unmap_ip(map, sym->start) + pp->offset;
2289                 if (reloc_sym) {
2290                         tp->symbol = strdup_or_goto(reloc_sym->name, nomem_out);
2291                         tp->offset = tp->address - reloc_sym->addr;
2292                 } else {
2293                         tp->symbol = strdup_or_goto(sym->name, nomem_out);
2294                         tp->offset = pp->offset;
2295                 }
2296                 tp->retprobe = pp->retprobe;
2297                 if (target)
2298                         tev->point.module = strdup_or_goto(target, nomem_out);
2299                 tev->uprobes = pev->uprobes;
2300                 tev->nargs = pev->nargs;
2301                 if (tev->nargs) {
2302                         tev->args = zalloc(sizeof(struct probe_trace_arg) *
2303                                            tev->nargs);
2304                         if (tev->args == NULL)
2305                                 goto nomem_out;
2306                 }
2307                 for (i = 0; i < tev->nargs; i++) {
2308                         if (pev->args[i].name)
2309                                 tev->args[i].name =
2310                                         strdup_or_goto(pev->args[i].name,
2311                                                         nomem_out);
2312
2313                         tev->args[i].value = strdup_or_goto(pev->args[i].var,
2314                                                             nomem_out);
2315                         if (pev->args[i].type)
2316                                 tev->args[i].type =
2317                                         strdup_or_goto(pev->args[i].type,
2318                                                         nomem_out);
2319                 }
2320         }
2321
2322 out:
2323         if (map && pev->uprobes) {
2324                 /* Only when using uprobe(exec) map needs to be released */
2325                 dso__delete(map->dso);
2326                 map__delete(map);
2327         }
2328         return ret;
2329
2330 nomem_out:
2331         ret = -ENOMEM;
2332 err_out:
2333         clear_probe_trace_events(*tevs, num_matched_functions);
2334         zfree(tevs);
2335         goto out;
2336 }
2337
2338 static int convert_to_probe_trace_events(struct perf_probe_event *pev,
2339                                           struct probe_trace_event **tevs,
2340                                           int max_tevs, const char *target)
2341 {
2342         int ret;
2343
2344         if (pev->uprobes && !pev->group) {
2345                 /* Replace group name if not given */
2346                 ret = convert_exec_to_group(target, &pev->group);
2347                 if (ret != 0) {
2348                         pr_warning("Failed to make a group name.\n");
2349                         return ret;
2350                 }
2351         }
2352
2353         /* Convert perf_probe_event with debuginfo */
2354         ret = try_to_find_probe_trace_events(pev, tevs, max_tevs, target);
2355         if (ret != 0)
2356                 return ret;     /* Found in debuginfo or got an error */
2357
2358         return find_probe_trace_events_from_map(pev, tevs, max_tevs, target);
2359 }
2360
2361 struct __event_package {
2362         struct perf_probe_event         *pev;
2363         struct probe_trace_event        *tevs;
2364         int                             ntevs;
2365 };
2366
2367 int add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
2368                           int max_tevs, const char *target, bool force_add)
2369 {
2370         int i, j, ret;
2371         struct __event_package *pkgs;
2372
2373         ret = 0;
2374         pkgs = zalloc(sizeof(struct __event_package) * npevs);
2375
2376         if (pkgs == NULL)
2377                 return -ENOMEM;
2378
2379         ret = init_symbol_maps(pevs->uprobes);
2380         if (ret < 0) {
2381                 free(pkgs);
2382                 return ret;
2383         }
2384
2385         /* Loop 1: convert all events */
2386         for (i = 0; i < npevs; i++) {
2387                 pkgs[i].pev = &pevs[i];
2388                 /* Convert with or without debuginfo */
2389                 ret  = convert_to_probe_trace_events(pkgs[i].pev,
2390                                                      &pkgs[i].tevs,
2391                                                      max_tevs,
2392                                                      target);
2393                 if (ret < 0)
2394                         goto end;
2395                 pkgs[i].ntevs = ret;
2396         }
2397
2398         /* Loop 2: add all events */
2399         for (i = 0; i < npevs; i++) {
2400                 ret = __add_probe_trace_events(pkgs[i].pev, pkgs[i].tevs,
2401                                                 pkgs[i].ntevs, force_add);
2402                 if (ret < 0)
2403                         break;
2404         }
2405 end:
2406         /* Loop 3: cleanup and free trace events  */
2407         for (i = 0; i < npevs; i++) {
2408                 for (j = 0; j < pkgs[i].ntevs; j++)
2409                         clear_probe_trace_event(&pkgs[i].tevs[j]);
2410                 zfree(&pkgs[i].tevs);
2411         }
2412         free(pkgs);
2413         exit_symbol_maps();
2414
2415         return ret;
2416 }
2417
2418 static int __del_trace_probe_event(int fd, struct str_node *ent)
2419 {
2420         char *p;
2421         char buf[128];
2422         int ret;
2423
2424         /* Convert from perf-probe event to trace-probe event */
2425         ret = e_snprintf(buf, 128, "-:%s", ent->s);
2426         if (ret < 0)
2427                 goto error;
2428
2429         p = strchr(buf + 2, ':');
2430         if (!p) {
2431                 pr_debug("Internal error: %s should have ':' but not.\n",
2432                          ent->s);
2433                 ret = -ENOTSUP;
2434                 goto error;
2435         }
2436         *p = '/';
2437
2438         pr_debug("Writing event: %s\n", buf);
2439         ret = write(fd, buf, strlen(buf));
2440         if (ret < 0) {
2441                 ret = -errno;
2442                 goto error;
2443         }
2444
2445         printf("Removed event: %s\n", ent->s);
2446         return 0;
2447 error:
2448         pr_warning("Failed to delete event: %s\n",
2449                    strerror_r(-ret, buf, sizeof(buf)));
2450         return ret;
2451 }
2452
2453 static int del_trace_probe_event(int fd, const char *buf,
2454                                                   struct strlist *namelist)
2455 {
2456         struct str_node *ent, *n;
2457         int ret = -1;
2458
2459         if (strpbrk(buf, "*?")) { /* Glob-exp */
2460                 strlist__for_each_safe(ent, n, namelist)
2461                         if (strglobmatch(ent->s, buf)) {
2462                                 ret = __del_trace_probe_event(fd, ent);
2463                                 if (ret < 0)
2464                                         break;
2465                                 strlist__remove(namelist, ent);
2466                         }
2467         } else {
2468                 ent = strlist__find(namelist, buf);
2469                 if (ent) {
2470                         ret = __del_trace_probe_event(fd, ent);
2471                         if (ret >= 0)
2472                                 strlist__remove(namelist, ent);
2473                 }
2474         }
2475
2476         return ret;
2477 }
2478
2479 int del_perf_probe_events(struct strlist *dellist)
2480 {
2481         int ret = -1, ufd = -1, kfd = -1;
2482         char buf[128];
2483         const char *group, *event;
2484         char *p, *str;
2485         struct str_node *ent;
2486         struct strlist *namelist = NULL, *unamelist = NULL;
2487
2488         /* Get current event names */
2489         kfd = open_kprobe_events(true);
2490         if (kfd >= 0)
2491                 namelist = get_probe_trace_event_names(kfd, true);
2492
2493         ufd = open_uprobe_events(true);
2494         if (ufd >= 0)
2495                 unamelist = get_probe_trace_event_names(ufd, true);
2496
2497         if (kfd < 0 && ufd < 0) {
2498                 print_both_open_warning(kfd, ufd);
2499                 goto error;
2500         }
2501
2502         if (namelist == NULL && unamelist == NULL)
2503                 goto error;
2504
2505         strlist__for_each(ent, dellist) {
2506                 str = strdup(ent->s);
2507                 if (str == NULL) {
2508                         ret = -ENOMEM;
2509                         goto error;
2510                 }
2511                 pr_debug("Parsing: %s\n", str);
2512                 p = strchr(str, ':');
2513                 if (p) {
2514                         group = str;
2515                         *p = '\0';
2516                         event = p + 1;
2517                 } else {
2518                         group = "*";
2519                         event = str;
2520                 }
2521
2522                 ret = e_snprintf(buf, 128, "%s:%s", group, event);
2523                 if (ret < 0) {
2524                         pr_err("Failed to copy event.");
2525                         free(str);
2526                         goto error;
2527                 }
2528
2529                 pr_debug("Group: %s, Event: %s\n", group, event);
2530
2531                 if (namelist)
2532                         ret = del_trace_probe_event(kfd, buf, namelist);
2533
2534                 if (unamelist && ret != 0)
2535                         ret = del_trace_probe_event(ufd, buf, unamelist);
2536
2537                 if (ret != 0)
2538                         pr_info("Info: Event \"%s\" does not exist.\n", buf);
2539
2540                 free(str);
2541         }
2542
2543 error:
2544         if (kfd >= 0) {
2545                 strlist__delete(namelist);
2546                 close(kfd);
2547         }
2548
2549         if (ufd >= 0) {
2550                 strlist__delete(unamelist);
2551                 close(ufd);
2552         }
2553
2554         return ret;
2555 }
2556
2557 /* TODO: don't use a global variable for filter ... */
2558 static struct strfilter *available_func_filter;
2559
2560 /*
2561  * If a symbol corresponds to a function with global binding and
2562  * matches filter return 0. For all others return 1.
2563  */
2564 static int filter_available_functions(struct map *map __maybe_unused,
2565                                       struct symbol *sym)
2566 {
2567         if ((sym->binding == STB_GLOBAL || sym->binding == STB_LOCAL) &&
2568             strfilter__compare(available_func_filter, sym->name))
2569                 return 0;
2570         return 1;
2571 }
2572
2573 int show_available_funcs(const char *target, struct strfilter *_filter,
2574                                         bool user)
2575 {
2576         struct map *map;
2577         int ret;
2578
2579         ret = init_symbol_maps(user);
2580         if (ret < 0)
2581                 return ret;
2582
2583         /* Get a symbol map */
2584         if (user)
2585                 map = dso__new_map(target);
2586         else
2587                 map = kernel_get_module_map(target);
2588         if (!map) {
2589                 pr_err("Failed to get a map for %s\n", (target) ? : "kernel");
2590                 return -EINVAL;
2591         }
2592
2593         /* Load symbols with given filter */
2594         available_func_filter = _filter;
2595         if (map__load(map, filter_available_functions)) {
2596                 pr_err("Failed to load symbols in %s\n", (target) ? : "kernel");
2597                 goto end;
2598         }
2599         if (!dso__sorted_by_name(map->dso, map->type))
2600                 dso__sort_by_name(map->dso, map->type);
2601
2602         /* Show all (filtered) symbols */
2603         setup_pager();
2604         dso__fprintf_symbols_by_name(map->dso, map->type, stdout);
2605 end:
2606         if (user) {
2607                 dso__delete(map->dso);
2608                 map__delete(map);
2609         }
2610         exit_symbol_maps();
2611
2612         return ret;
2613 }
2614