GNU Linux-libre 4.4.289-gnu1
[releases.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/fs.h>
44 #include "trace-event.h"        /* For __maybe_unused */
45 #include "probe-event.h"
46 #include "probe-finder.h"
47 #include "probe-file.h"
48 #include "session.h"
49
50 #define MAX_CMDLEN 256
51 #define PERFPROBE_GROUP "probe"
52
53 bool probe_event_dry_run;       /* Dry run flag */
54 struct probe_conf probe_conf;
55
56 #define semantic_error(msg ...) pr_err("Semantic error :" msg)
57
58 int e_snprintf(char *str, size_t size, const char *format, ...)
59 {
60         int ret;
61         va_list ap;
62         va_start(ap, format);
63         ret = vsnprintf(str, size, format, ap);
64         va_end(ap);
65         if (ret >= (int)size)
66                 ret = -E2BIG;
67         return ret;
68 }
69
70 static char *synthesize_perf_probe_point(struct perf_probe_point *pp);
71 static struct machine *host_machine;
72
73 /* Initialize symbol maps and path of vmlinux/modules */
74 int init_probe_symbol_maps(bool user_only)
75 {
76         int ret;
77
78         symbol_conf.sort_by_name = true;
79         symbol_conf.allow_aliases = true;
80         ret = symbol__init(NULL);
81         if (ret < 0) {
82                 pr_debug("Failed to init symbol map.\n");
83                 goto out;
84         }
85
86         if (host_machine || user_only)  /* already initialized */
87                 return 0;
88
89         if (symbol_conf.vmlinux_name)
90                 pr_debug("Use vmlinux: %s\n", symbol_conf.vmlinux_name);
91
92         host_machine = machine__new_host();
93         if (!host_machine) {
94                 pr_debug("machine__new_host() failed.\n");
95                 symbol__exit();
96                 ret = -1;
97         }
98 out:
99         if (ret < 0)
100                 pr_warning("Failed to init vmlinux path.\n");
101         return ret;
102 }
103
104 void exit_probe_symbol_maps(void)
105 {
106         if (host_machine) {
107                 machine__delete(host_machine);
108                 host_machine = NULL;
109         }
110         symbol__exit();
111 }
112
113 static struct symbol *__find_kernel_function_by_name(const char *name,
114                                                      struct map **mapp)
115 {
116         return machine__find_kernel_function_by_name(host_machine, name, mapp,
117                                                      NULL);
118 }
119
120 static struct symbol *__find_kernel_function(u64 addr, struct map **mapp)
121 {
122         return machine__find_kernel_function(host_machine, addr, mapp, NULL);
123 }
124
125 static struct ref_reloc_sym *kernel_get_ref_reloc_sym(struct map **pmap)
126 {
127         /* kmap->ref_reloc_sym should be set if host_machine is initialized */
128         struct kmap *kmap;
129         struct map *map = machine__kernel_map(host_machine);
130
131         if (map__load(map, NULL) < 0)
132                 return NULL;
133
134         kmap = map__kmap(map);
135         if (!kmap)
136                 return NULL;
137
138         if (pmap)
139                 *pmap = map;
140
141         return kmap->ref_reloc_sym;
142 }
143
144 static int kernel_get_symbol_address_by_name(const char *name, u64 *addr,
145                                              bool reloc, bool reladdr)
146 {
147         struct ref_reloc_sym *reloc_sym;
148         struct symbol *sym;
149         struct map *map;
150
151         /* ref_reloc_sym is just a label. Need a special fix*/
152         reloc_sym = kernel_get_ref_reloc_sym(NULL);
153         if (reloc_sym && strcmp(name, reloc_sym->name) == 0)
154                 *addr = (reloc) ? reloc_sym->addr : reloc_sym->unrelocated_addr;
155         else {
156                 sym = __find_kernel_function_by_name(name, &map);
157                 if (!sym)
158                         return -ENOENT;
159                 *addr = map->unmap_ip(map, sym->start) -
160                         ((reloc) ? 0 : map->reloc) -
161                         ((reladdr) ? map->start : 0);
162         }
163         return 0;
164 }
165
166 static struct map *kernel_get_module_map(const char *module)
167 {
168         struct map_groups *grp = &host_machine->kmaps;
169         struct maps *maps = &grp->maps[MAP__FUNCTION];
170         struct map *pos;
171
172         /* A file path -- this is an offline module */
173         if (module && strchr(module, '/'))
174                 return machine__findnew_module_map(host_machine, 0, module);
175
176         if (!module)
177                 module = "kernel";
178
179         for (pos = maps__first(maps); pos; pos = map__next(pos)) {
180                 if (strncmp(pos->dso->short_name + 1, module,
181                             pos->dso->short_name_len - 2) == 0) {
182                         return pos;
183                 }
184         }
185         return NULL;
186 }
187
188 static struct map *get_target_map(const char *target, bool user)
189 {
190         /* Init maps of given executable or kernel */
191         if (user)
192                 return dso__new_map(target);
193         else
194                 return kernel_get_module_map(target);
195 }
196
197 static void put_target_map(struct map *map, bool user)
198 {
199         if (map && user) {
200                 /* Only the user map needs to be released */
201                 map__put(map);
202         }
203 }
204
205
206 static int convert_exec_to_group(const char *exec, char **result)
207 {
208         char *ptr1, *ptr2, *exec_copy;
209         char buf[64];
210         int ret;
211
212         exec_copy = strdup(exec);
213         if (!exec_copy)
214                 return -ENOMEM;
215
216         ptr1 = basename(exec_copy);
217         if (!ptr1) {
218                 ret = -EINVAL;
219                 goto out;
220         }
221
222         ptr2 = strpbrk(ptr1, "-._");
223         if (ptr2)
224                 *ptr2 = '\0';
225         ret = e_snprintf(buf, 64, "%s_%s", PERFPROBE_GROUP, ptr1);
226         if (ret < 0)
227                 goto out;
228
229         *result = strdup(buf);
230         ret = *result ? 0 : -ENOMEM;
231
232 out:
233         free(exec_copy);
234         return ret;
235 }
236
237 static void clear_perf_probe_point(struct perf_probe_point *pp)
238 {
239         free(pp->file);
240         free(pp->function);
241         free(pp->lazy_line);
242 }
243
244 static void clear_probe_trace_events(struct probe_trace_event *tevs, int ntevs)
245 {
246         int i;
247
248         for (i = 0; i < ntevs; i++)
249                 clear_probe_trace_event(tevs + i);
250 }
251
252 static bool kprobe_blacklist__listed(unsigned long address);
253 static bool kprobe_warn_out_range(const char *symbol, unsigned long address)
254 {
255         u64 etext_addr = 0;
256         int ret;
257
258         /* Get the address of _etext for checking non-probable text symbol */
259         ret = kernel_get_symbol_address_by_name("_etext", &etext_addr,
260                                                 false, false);
261
262         if (ret == 0 && etext_addr < address)
263                 pr_warning("%s is out of .text, skip it.\n", symbol);
264         else if (kprobe_blacklist__listed(address))
265                 pr_warning("%s is blacklisted function, skip it.\n", symbol);
266         else
267                 return false;
268
269         return true;
270 }
271
272 #ifdef HAVE_DWARF_SUPPORT
273
274 static int kernel_get_module_dso(const char *module, struct dso **pdso)
275 {
276         struct dso *dso;
277         struct map *map;
278         const char *vmlinux_name;
279         int ret = 0;
280
281         if (module) {
282                 char module_name[128];
283
284                 snprintf(module_name, sizeof(module_name), "[%s]", module);
285                 map = map_groups__find_by_name(&host_machine->kmaps, MAP__FUNCTION, module_name);
286                 if (map) {
287                         dso = map->dso;
288                         goto found;
289                 }
290                 pr_debug("Failed to find module %s.\n", module);
291                 return -ENOENT;
292         }
293
294         map = machine__kernel_map(host_machine);
295         dso = map->dso;
296
297         vmlinux_name = symbol_conf.vmlinux_name;
298         dso->load_errno = 0;
299         if (vmlinux_name)
300                 ret = dso__load_vmlinux(dso, map, vmlinux_name, false, NULL);
301         else
302                 ret = dso__load_vmlinux_path(dso, map, NULL);
303 found:
304         *pdso = dso;
305         return ret;
306 }
307
308 /*
309  * Some binaries like glibc have special symbols which are on the symbol
310  * table, but not in the debuginfo. If we can find the address of the
311  * symbol from map, we can translate the address back to the probe point.
312  */
313 static int find_alternative_probe_point(struct debuginfo *dinfo,
314                                         struct perf_probe_point *pp,
315                                         struct perf_probe_point *result,
316                                         const char *target, bool uprobes)
317 {
318         struct map *map = NULL;
319         struct symbol *sym;
320         u64 address = 0;
321         int ret = -ENOENT;
322
323         /* This can work only for function-name based one */
324         if (!pp->function || pp->file)
325                 return -ENOTSUP;
326
327         map = get_target_map(target, uprobes);
328         if (!map)
329                 return -EINVAL;
330
331         /* Find the address of given function */
332         map__for_each_symbol_by_name(map, pp->function, sym) {
333                 if (uprobes)
334                         address = sym->start;
335                 else
336                         address = map->unmap_ip(map, sym->start);
337                 break;
338         }
339         if (!address) {
340                 ret = -ENOENT;
341                 goto out;
342         }
343         pr_debug("Symbol %s address found : %" PRIx64 "\n",
344                         pp->function, address);
345
346         ret = debuginfo__find_probe_point(dinfo, (unsigned long)address,
347                                           result);
348         if (ret <= 0)
349                 ret = (!ret) ? -ENOENT : ret;
350         else {
351                 result->offset += pp->offset;
352                 result->line += pp->line;
353                 result->retprobe = pp->retprobe;
354                 ret = 0;
355         }
356
357 out:
358         put_target_map(map, uprobes);
359         return ret;
360
361 }
362
363 static int get_alternative_probe_event(struct debuginfo *dinfo,
364                                        struct perf_probe_event *pev,
365                                        struct perf_probe_point *tmp)
366 {
367         int ret;
368
369         memcpy(tmp, &pev->point, sizeof(*tmp));
370         memset(&pev->point, 0, sizeof(pev->point));
371         ret = find_alternative_probe_point(dinfo, tmp, &pev->point,
372                                            pev->target, pev->uprobes);
373         if (ret < 0)
374                 memcpy(&pev->point, tmp, sizeof(*tmp));
375
376         return ret;
377 }
378
379 static int get_alternative_line_range(struct debuginfo *dinfo,
380                                       struct line_range *lr,
381                                       const char *target, bool user)
382 {
383         struct perf_probe_point pp = { .function = lr->function,
384                                        .file = lr->file,
385                                        .line = lr->start };
386         struct perf_probe_point result;
387         int ret, len = 0;
388
389         memset(&result, 0, sizeof(result));
390
391         if (lr->end != INT_MAX)
392                 len = lr->end - lr->start;
393         ret = find_alternative_probe_point(dinfo, &pp, &result,
394                                            target, user);
395         if (!ret) {
396                 lr->function = result.function;
397                 lr->file = result.file;
398                 lr->start = result.line;
399                 if (lr->end != INT_MAX)
400                         lr->end = lr->start + len;
401                 clear_perf_probe_point(&pp);
402         }
403         return ret;
404 }
405
406 /* Open new debuginfo of given module */
407 static struct debuginfo *open_debuginfo(const char *module, bool silent)
408 {
409         const char *path = module;
410         char reason[STRERR_BUFSIZE];
411         struct debuginfo *ret = NULL;
412         struct dso *dso = NULL;
413         int err;
414
415         if (!module || !strchr(module, '/')) {
416                 err = kernel_get_module_dso(module, &dso);
417                 if (err < 0) {
418                         if (!dso || dso->load_errno == 0) {
419                                 if (!strerror_r(-err, reason, STRERR_BUFSIZE))
420                                         strcpy(reason, "(unknown)");
421                         } else
422                                 dso__strerror_load(dso, reason, STRERR_BUFSIZE);
423                         if (!silent)
424                                 pr_err("Failed to find the path for %s: %s\n",
425                                         module ?: "kernel", reason);
426                         return NULL;
427                 }
428                 path = dso->long_name;
429         }
430         ret = debuginfo__new(path);
431         if (!ret && !silent) {
432                 pr_warning("The %s file has no debug information.\n", path);
433                 if (!module || !strtailcmp(path, ".ko"))
434                         pr_warning("Rebuild with CONFIG_DEBUG_INFO=y, ");
435                 else
436                         pr_warning("Rebuild with -g, ");
437                 pr_warning("or install an appropriate debuginfo package.\n");
438         }
439         return ret;
440 }
441
442 /* For caching the last debuginfo */
443 static struct debuginfo *debuginfo_cache;
444 static char *debuginfo_cache_path;
445
446 static struct debuginfo *debuginfo_cache__open(const char *module, bool silent)
447 {
448         const char *path = module;
449
450         /* If the module is NULL, it should be the kernel. */
451         if (!module)
452                 path = "kernel";
453
454         if (debuginfo_cache_path && !strcmp(debuginfo_cache_path, path))
455                 goto out;
456
457         /* Copy module path */
458         free(debuginfo_cache_path);
459         debuginfo_cache_path = strdup(path);
460         if (!debuginfo_cache_path) {
461                 debuginfo__delete(debuginfo_cache);
462                 debuginfo_cache = NULL;
463                 goto out;
464         }
465
466         debuginfo_cache = open_debuginfo(module, silent);
467         if (!debuginfo_cache)
468                 zfree(&debuginfo_cache_path);
469 out:
470         return debuginfo_cache;
471 }
472
473 static void debuginfo_cache__exit(void)
474 {
475         debuginfo__delete(debuginfo_cache);
476         debuginfo_cache = NULL;
477         zfree(&debuginfo_cache_path);
478 }
479
480
481 static int get_text_start_address(const char *exec, unsigned long *address)
482 {
483         Elf *elf;
484         GElf_Ehdr ehdr;
485         GElf_Shdr shdr;
486         int fd, ret = -ENOENT;
487
488         fd = open(exec, O_RDONLY);
489         if (fd < 0)
490                 return -errno;
491
492         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
493         if (elf == NULL)
494                 return -EINVAL;
495
496         if (gelf_getehdr(elf, &ehdr) == NULL)
497                 goto out;
498
499         if (!elf_section_by_name(elf, &ehdr, &shdr, ".text", NULL))
500                 goto out;
501
502         *address = shdr.sh_addr - shdr.sh_offset;
503         ret = 0;
504 out:
505         elf_end(elf);
506         return ret;
507 }
508
509 /*
510  * Convert trace point to probe point with debuginfo
511  */
512 static int find_perf_probe_point_from_dwarf(struct probe_trace_point *tp,
513                                             struct perf_probe_point *pp,
514                                             bool is_kprobe)
515 {
516         struct debuginfo *dinfo = NULL;
517         unsigned long stext = 0;
518         u64 addr = tp->address;
519         int ret = -ENOENT;
520
521         /* convert the address to dwarf address */
522         if (!is_kprobe) {
523                 if (!addr) {
524                         ret = -EINVAL;
525                         goto error;
526                 }
527                 ret = get_text_start_address(tp->module, &stext);
528                 if (ret < 0)
529                         goto error;
530                 addr += stext;
531         } else if (tp->symbol) {
532                 /* If the module is given, this returns relative address */
533                 ret = kernel_get_symbol_address_by_name(tp->symbol, &addr,
534                                                         false, !!tp->module);
535                 if (ret != 0)
536                         goto error;
537                 addr += tp->offset;
538         }
539
540         pr_debug("try to find information at %" PRIx64 " in %s\n", addr,
541                  tp->module ? : "kernel");
542
543         dinfo = debuginfo_cache__open(tp->module, verbose == 0);
544         if (dinfo)
545                 ret = debuginfo__find_probe_point(dinfo,
546                                                  (unsigned long)addr, pp);
547         else
548                 ret = -ENOENT;
549
550         if (ret > 0) {
551                 pp->retprobe = tp->retprobe;
552                 return 0;
553         }
554 error:
555         pr_debug("Failed to find corresponding probes from debuginfo.\n");
556         return ret ? : -ENOENT;
557 }
558
559 static int add_exec_to_probe_trace_events(struct probe_trace_event *tevs,
560                                           int ntevs, const char *exec)
561 {
562         int i, ret = 0;
563         unsigned long stext = 0;
564
565         if (!exec)
566                 return 0;
567
568         ret = get_text_start_address(exec, &stext);
569         if (ret < 0)
570                 return ret;
571
572         for (i = 0; i < ntevs && ret >= 0; i++) {
573                 /* point.address is the addres of point.symbol + point.offset */
574                 tevs[i].point.address -= stext;
575                 tevs[i].point.module = strdup(exec);
576                 if (!tevs[i].point.module) {
577                         ret = -ENOMEM;
578                         break;
579                 }
580                 tevs[i].uprobes = true;
581         }
582
583         return ret;
584 }
585
586 static int add_module_to_probe_trace_events(struct probe_trace_event *tevs,
587                                             int ntevs, const char *module)
588 {
589         int i, ret = 0;
590         char *tmp;
591
592         if (!module)
593                 return 0;
594
595         tmp = strrchr(module, '/');
596         if (tmp) {
597                 /* This is a module path -- get the module name */
598                 module = strdup(tmp + 1);
599                 if (!module)
600                         return -ENOMEM;
601                 tmp = strchr(module, '.');
602                 if (tmp)
603                         *tmp = '\0';
604                 tmp = (char *)module;   /* For free() */
605         }
606
607         for (i = 0; i < ntevs; i++) {
608                 tevs[i].point.module = strdup(module);
609                 if (!tevs[i].point.module) {
610                         ret = -ENOMEM;
611                         break;
612                 }
613         }
614
615         free(tmp);
616         return ret;
617 }
618
619 /* Post processing the probe events */
620 static int post_process_probe_trace_events(struct probe_trace_event *tevs,
621                                            int ntevs, const char *module,
622                                            bool uprobe)
623 {
624         struct ref_reloc_sym *reloc_sym;
625         struct map *map;
626         char *tmp;
627         int i, skipped = 0;
628
629         if (uprobe)
630                 return add_exec_to_probe_trace_events(tevs, ntevs, module);
631
632         /* Note that currently ref_reloc_sym based probe is not for drivers */
633         if (module)
634                 return add_module_to_probe_trace_events(tevs, ntevs, module);
635
636         reloc_sym = kernel_get_ref_reloc_sym(&map);
637         if (!reloc_sym) {
638                 pr_warning("Relocated base symbol is not found!\n");
639                 return -EINVAL;
640         }
641
642         for (i = 0; i < ntevs; i++) {
643                 if (!tevs[i].point.address || tevs[i].point.retprobe)
644                         continue;
645                 /*
646                  * If we found a wrong one, mark it by NULL symbol.
647                  * Since addresses in debuginfo is same as objdump, we need
648                  * to convert it to addresses on memory.
649                  */
650                 if (kprobe_warn_out_range(tevs[i].point.symbol,
651                         map__objdump_2mem(map, tevs[i].point.address))) {
652                         tmp = NULL;
653                         skipped++;
654                 } else {
655                         tmp = strdup(reloc_sym->name);
656                         if (!tmp)
657                                 return -ENOMEM;
658                 }
659                 /* If we have no realname, use symbol for it */
660                 if (!tevs[i].point.realname)
661                         tevs[i].point.realname = tevs[i].point.symbol;
662                 else
663                         free(tevs[i].point.symbol);
664                 tevs[i].point.symbol = tmp;
665                 tevs[i].point.offset = tevs[i].point.address -
666                                        reloc_sym->unrelocated_addr;
667         }
668         return skipped;
669 }
670
671 /* Try to find perf_probe_event with debuginfo */
672 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
673                                           struct probe_trace_event **tevs)
674 {
675         bool need_dwarf = perf_probe_event_need_dwarf(pev);
676         struct perf_probe_point tmp;
677         struct debuginfo *dinfo;
678         int ntevs, ret = 0;
679
680         dinfo = open_debuginfo(pev->target, !need_dwarf);
681         if (!dinfo) {
682                 if (need_dwarf)
683                         return -ENOENT;
684                 pr_debug("Could not open debuginfo. Try to use symbols.\n");
685                 return 0;
686         }
687
688         pr_debug("Try to find probe point from debuginfo.\n");
689         /* Searching trace events corresponding to a probe event */
690         ntevs = debuginfo__find_trace_events(dinfo, pev, tevs);
691
692         if (ntevs == 0) {  /* Not found, retry with an alternative */
693                 ret = get_alternative_probe_event(dinfo, pev, &tmp);
694                 if (!ret) {
695                         ntevs = debuginfo__find_trace_events(dinfo, pev, tevs);
696                         /*
697                          * Write back to the original probe_event for
698                          * setting appropriate (user given) event name
699                          */
700                         clear_perf_probe_point(&pev->point);
701                         memcpy(&pev->point, &tmp, sizeof(tmp));
702                 }
703         }
704
705         debuginfo__delete(dinfo);
706
707         if (ntevs > 0) {        /* Succeeded to find trace events */
708                 pr_debug("Found %d probe_trace_events.\n", ntevs);
709                 ret = post_process_probe_trace_events(*tevs, ntevs,
710                                                 pev->target, pev->uprobes);
711                 if (ret < 0 || ret == ntevs) {
712                         clear_probe_trace_events(*tevs, ntevs);
713                         zfree(tevs);
714                 }
715                 if (ret != ntevs)
716                         return ret < 0 ? ret : ntevs;
717                 ntevs = 0;
718                 /* Fall through */
719         }
720
721         if (ntevs == 0) {       /* No error but failed to find probe point. */
722                 pr_warning("Probe point '%s' not found.\n",
723                            synthesize_perf_probe_point(&pev->point));
724                 return -ENOENT;
725         }
726         /* Error path : ntevs < 0 */
727         pr_debug("An error occurred in debuginfo analysis (%d).\n", ntevs);
728         if (ntevs < 0) {
729                 if (ntevs == -EBADF)
730                         pr_warning("Warning: No dwarf info found in the vmlinux - "
731                                 "please rebuild kernel with CONFIG_DEBUG_INFO=y.\n");
732                 if (!need_dwarf) {
733                         pr_debug("Trying to use symbols.\n");
734                         return 0;
735                 }
736         }
737         return ntevs;
738 }
739
740 #define LINEBUF_SIZE 256
741 #define NR_ADDITIONAL_LINES 2
742
743 static int __show_one_line(FILE *fp, int l, bool skip, bool show_num)
744 {
745         char buf[LINEBUF_SIZE], sbuf[STRERR_BUFSIZE];
746         const char *color = show_num ? "" : PERF_COLOR_BLUE;
747         const char *prefix = NULL;
748
749         do {
750                 if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
751                         goto error;
752                 if (skip)
753                         continue;
754                 if (!prefix) {
755                         prefix = show_num ? "%7d  " : "         ";
756                         color_fprintf(stdout, color, prefix, l);
757                 }
758                 color_fprintf(stdout, color, "%s", buf);
759
760         } while (strchr(buf, '\n') == NULL);
761
762         return 1;
763 error:
764         if (ferror(fp)) {
765                 pr_warning("File read error: %s\n",
766                            strerror_r(errno, sbuf, sizeof(sbuf)));
767                 return -1;
768         }
769         return 0;
770 }
771
772 static int _show_one_line(FILE *fp, int l, bool skip, bool show_num)
773 {
774         int rv = __show_one_line(fp, l, skip, show_num);
775         if (rv == 0) {
776                 pr_warning("Source file is shorter than expected.\n");
777                 rv = -1;
778         }
779         return rv;
780 }
781
782 #define show_one_line_with_num(f,l)     _show_one_line(f,l,false,true)
783 #define show_one_line(f,l)              _show_one_line(f,l,false,false)
784 #define skip_one_line(f,l)              _show_one_line(f,l,true,false)
785 #define show_one_line_or_eof(f,l)       __show_one_line(f,l,false,false)
786
787 /*
788  * Show line-range always requires debuginfo to find source file and
789  * line number.
790  */
791 static int __show_line_range(struct line_range *lr, const char *module,
792                              bool user)
793 {
794         int l = 1;
795         struct int_node *ln;
796         struct debuginfo *dinfo;
797         FILE *fp;
798         int ret;
799         char *tmp;
800         char sbuf[STRERR_BUFSIZE];
801
802         /* Search a line range */
803         dinfo = open_debuginfo(module, false);
804         if (!dinfo)
805                 return -ENOENT;
806
807         ret = debuginfo__find_line_range(dinfo, lr);
808         if (!ret) {     /* Not found, retry with an alternative */
809                 ret = get_alternative_line_range(dinfo, lr, module, user);
810                 if (!ret)
811                         ret = debuginfo__find_line_range(dinfo, lr);
812         }
813         debuginfo__delete(dinfo);
814         if (ret == 0 || ret == -ENOENT) {
815                 pr_warning("Specified source line is not found.\n");
816                 return -ENOENT;
817         } else if (ret < 0) {
818                 pr_warning("Debuginfo analysis failed.\n");
819                 return ret;
820         }
821
822         /* Convert source file path */
823         tmp = lr->path;
824         ret = get_real_path(tmp, lr->comp_dir, &lr->path);
825
826         /* Free old path when new path is assigned */
827         if (tmp != lr->path)
828                 free(tmp);
829
830         if (ret < 0) {
831                 pr_warning("Failed to find source file path.\n");
832                 return ret;
833         }
834
835         setup_pager();
836
837         if (lr->function)
838                 fprintf(stdout, "<%s@%s:%d>\n", lr->function, lr->path,
839                         lr->start - lr->offset);
840         else
841                 fprintf(stdout, "<%s:%d>\n", lr->path, lr->start);
842
843         fp = fopen(lr->path, "r");
844         if (fp == NULL) {
845                 pr_warning("Failed to open %s: %s\n", lr->path,
846                            strerror_r(errno, sbuf, sizeof(sbuf)));
847                 return -errno;
848         }
849         /* Skip to starting line number */
850         while (l < lr->start) {
851                 ret = skip_one_line(fp, l++);
852                 if (ret < 0)
853                         goto end;
854         }
855
856         intlist__for_each(ln, lr->line_list) {
857                 for (; ln->i > l; l++) {
858                         ret = show_one_line(fp, l - lr->offset);
859                         if (ret < 0)
860                                 goto end;
861                 }
862                 ret = show_one_line_with_num(fp, l++ - lr->offset);
863                 if (ret < 0)
864                         goto end;
865         }
866
867         if (lr->end == INT_MAX)
868                 lr->end = l + NR_ADDITIONAL_LINES;
869         while (l <= lr->end) {
870                 ret = show_one_line_or_eof(fp, l++ - lr->offset);
871                 if (ret <= 0)
872                         break;
873         }
874 end:
875         fclose(fp);
876         return ret;
877 }
878
879 int show_line_range(struct line_range *lr, const char *module, bool user)
880 {
881         int ret;
882
883         ret = init_probe_symbol_maps(user);
884         if (ret < 0)
885                 return ret;
886         ret = __show_line_range(lr, module, user);
887         exit_probe_symbol_maps();
888
889         return ret;
890 }
891
892 static int show_available_vars_at(struct debuginfo *dinfo,
893                                   struct perf_probe_event *pev,
894                                   struct strfilter *_filter)
895 {
896         char *buf;
897         int ret, i, nvars;
898         struct str_node *node;
899         struct variable_list *vls = NULL, *vl;
900         struct perf_probe_point tmp;
901         const char *var;
902
903         buf = synthesize_perf_probe_point(&pev->point);
904         if (!buf)
905                 return -EINVAL;
906         pr_debug("Searching variables at %s\n", buf);
907
908         ret = debuginfo__find_available_vars_at(dinfo, pev, &vls);
909         if (!ret) {  /* Not found, retry with an alternative */
910                 ret = get_alternative_probe_event(dinfo, pev, &tmp);
911                 if (!ret) {
912                         ret = debuginfo__find_available_vars_at(dinfo, pev,
913                                                                 &vls);
914                         /* Release the old probe_point */
915                         clear_perf_probe_point(&tmp);
916                 }
917         }
918         if (ret <= 0) {
919                 if (ret == 0 || ret == -ENOENT) {
920                         pr_err("Failed to find the address of %s\n", buf);
921                         ret = -ENOENT;
922                 } else
923                         pr_warning("Debuginfo analysis failed.\n");
924                 goto end;
925         }
926
927         /* Some variables are found */
928         fprintf(stdout, "Available variables at %s\n", buf);
929         for (i = 0; i < ret; i++) {
930                 vl = &vls[i];
931                 /*
932                  * A probe point might be converted to
933                  * several trace points.
934                  */
935                 fprintf(stdout, "\t@<%s+%lu>\n", vl->point.symbol,
936                         vl->point.offset);
937                 zfree(&vl->point.symbol);
938                 nvars = 0;
939                 if (vl->vars) {
940                         strlist__for_each(node, vl->vars) {
941                                 var = strchr(node->s, '\t') + 1;
942                                 if (strfilter__compare(_filter, var)) {
943                                         fprintf(stdout, "\t\t%s\n", node->s);
944                                         nvars++;
945                                 }
946                         }
947                         strlist__delete(vl->vars);
948                 }
949                 if (nvars == 0)
950                         fprintf(stdout, "\t\t(No matched variables)\n");
951         }
952         free(vls);
953 end:
954         free(buf);
955         return ret;
956 }
957
958 /* Show available variables on given probe point */
959 int show_available_vars(struct perf_probe_event *pevs, int npevs,
960                         struct strfilter *_filter)
961 {
962         int i, ret = 0;
963         struct debuginfo *dinfo;
964
965         ret = init_probe_symbol_maps(pevs->uprobes);
966         if (ret < 0)
967                 return ret;
968
969         dinfo = open_debuginfo(pevs->target, false);
970         if (!dinfo) {
971                 ret = -ENOENT;
972                 goto out;
973         }
974
975         setup_pager();
976
977         for (i = 0; i < npevs && ret >= 0; i++)
978                 ret = show_available_vars_at(dinfo, &pevs[i], _filter);
979
980         debuginfo__delete(dinfo);
981 out:
982         exit_probe_symbol_maps();
983         return ret;
984 }
985
986 #else   /* !HAVE_DWARF_SUPPORT */
987
988 static void debuginfo_cache__exit(void)
989 {
990 }
991
992 static int
993 find_perf_probe_point_from_dwarf(struct probe_trace_point *tp __maybe_unused,
994                                  struct perf_probe_point *pp __maybe_unused,
995                                  bool is_kprobe __maybe_unused)
996 {
997         return -ENOSYS;
998 }
999
1000 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
1001                                 struct probe_trace_event **tevs __maybe_unused)
1002 {
1003         if (perf_probe_event_need_dwarf(pev)) {
1004                 pr_warning("Debuginfo-analysis is not supported.\n");
1005                 return -ENOSYS;
1006         }
1007
1008         return 0;
1009 }
1010
1011 int show_line_range(struct line_range *lr __maybe_unused,
1012                     const char *module __maybe_unused,
1013                     bool user __maybe_unused)
1014 {
1015         pr_warning("Debuginfo-analysis is not supported.\n");
1016         return -ENOSYS;
1017 }
1018
1019 int show_available_vars(struct perf_probe_event *pevs __maybe_unused,
1020                         int npevs __maybe_unused,
1021                         struct strfilter *filter __maybe_unused)
1022 {
1023         pr_warning("Debuginfo-analysis is not supported.\n");
1024         return -ENOSYS;
1025 }
1026 #endif
1027
1028 void line_range__clear(struct line_range *lr)
1029 {
1030         free(lr->function);
1031         free(lr->file);
1032         free(lr->path);
1033         free(lr->comp_dir);
1034         intlist__delete(lr->line_list);
1035         memset(lr, 0, sizeof(*lr));
1036 }
1037
1038 int line_range__init(struct line_range *lr)
1039 {
1040         memset(lr, 0, sizeof(*lr));
1041         lr->line_list = intlist__new(NULL);
1042         if (!lr->line_list)
1043                 return -ENOMEM;
1044         else
1045                 return 0;
1046 }
1047
1048 static int parse_line_num(char **ptr, int *val, const char *what)
1049 {
1050         const char *start = *ptr;
1051
1052         errno = 0;
1053         *val = strtol(*ptr, ptr, 0);
1054         if (errno || *ptr == start) {
1055                 semantic_error("'%s' is not a valid number.\n", what);
1056                 return -EINVAL;
1057         }
1058         return 0;
1059 }
1060
1061 /* Check the name is good for event, group or function */
1062 static bool is_c_func_name(const char *name)
1063 {
1064         if (!isalpha(*name) && *name != '_')
1065                 return false;
1066         while (*++name != '\0') {
1067                 if (!isalpha(*name) && !isdigit(*name) && *name != '_')
1068                         return false;
1069         }
1070         return true;
1071 }
1072
1073 /*
1074  * Stuff 'lr' according to the line range described by 'arg'.
1075  * The line range syntax is described by:
1076  *
1077  *         SRC[:SLN[+NUM|-ELN]]
1078  *         FNC[@SRC][:SLN[+NUM|-ELN]]
1079  */
1080 int parse_line_range_desc(const char *arg, struct line_range *lr)
1081 {
1082         char *range, *file, *name = strdup(arg);
1083         int err;
1084
1085         if (!name)
1086                 return -ENOMEM;
1087
1088         lr->start = 0;
1089         lr->end = INT_MAX;
1090
1091         range = strchr(name, ':');
1092         if (range) {
1093                 *range++ = '\0';
1094
1095                 err = parse_line_num(&range, &lr->start, "start line");
1096                 if (err)
1097                         goto err;
1098
1099                 if (*range == '+' || *range == '-') {
1100                         const char c = *range++;
1101
1102                         err = parse_line_num(&range, &lr->end, "end line");
1103                         if (err)
1104                                 goto err;
1105
1106                         if (c == '+') {
1107                                 lr->end += lr->start;
1108                                 /*
1109                                  * Adjust the number of lines here.
1110                                  * If the number of lines == 1, the
1111                                  * the end of line should be equal to
1112                                  * the start of line.
1113                                  */
1114                                 lr->end--;
1115                         }
1116                 }
1117
1118                 pr_debug("Line range is %d to %d\n", lr->start, lr->end);
1119
1120                 err = -EINVAL;
1121                 if (lr->start > lr->end) {
1122                         semantic_error("Start line must be smaller"
1123                                        " than end line.\n");
1124                         goto err;
1125                 }
1126                 if (*range != '\0') {
1127                         semantic_error("Tailing with invalid str '%s'.\n", range);
1128                         goto err;
1129                 }
1130         }
1131
1132         file = strchr(name, '@');
1133         if (file) {
1134                 *file = '\0';
1135                 lr->file = strdup(++file);
1136                 if (lr->file == NULL) {
1137                         err = -ENOMEM;
1138                         goto err;
1139                 }
1140                 lr->function = name;
1141         } else if (strchr(name, '/') || strchr(name, '.'))
1142                 lr->file = name;
1143         else if (is_c_func_name(name))/* We reuse it for checking funcname */
1144                 lr->function = name;
1145         else {  /* Invalid name */
1146                 semantic_error("'%s' is not a valid function name.\n", name);
1147                 err = -EINVAL;
1148                 goto err;
1149         }
1150
1151         return 0;
1152 err:
1153         free(name);
1154         return err;
1155 }
1156
1157 /* Parse probepoint definition. */
1158 static int parse_perf_probe_point(char *arg, struct perf_probe_event *pev)
1159 {
1160         struct perf_probe_point *pp = &pev->point;
1161         char *ptr, *tmp;
1162         char c, nc = 0;
1163         bool file_spec = false;
1164         /*
1165          * <Syntax>
1166          * perf probe [EVENT=]SRC[:LN|;PTN]
1167          * perf probe [EVENT=]FUNC[@SRC][+OFFS|%return|:LN|;PAT]
1168          *
1169          * TODO:Group name support
1170          */
1171         if (!arg)
1172                 return -EINVAL;
1173
1174         ptr = strpbrk(arg, ";=@+%");
1175         if (ptr && *ptr == '=') {       /* Event name */
1176                 *ptr = '\0';
1177                 tmp = ptr + 1;
1178                 if (strchr(arg, ':')) {
1179                         semantic_error("Group name is not supported yet.\n");
1180                         return -ENOTSUP;
1181                 }
1182                 if (!is_c_func_name(arg)) {
1183                         semantic_error("%s is bad for event name -it must "
1184                                        "follow C symbol-naming rule.\n", arg);
1185                         return -EINVAL;
1186                 }
1187                 pev->event = strdup(arg);
1188                 if (pev->event == NULL)
1189                         return -ENOMEM;
1190                 pev->group = NULL;
1191                 arg = tmp;
1192         }
1193
1194         /*
1195          * Check arg is function or file name and copy it.
1196          *
1197          * We consider arg to be a file spec if and only if it satisfies
1198          * all of the below criteria::
1199          * - it does not include any of "+@%",
1200          * - it includes one of ":;", and
1201          * - it has a period '.' in the name.
1202          *
1203          * Otherwise, we consider arg to be a function specification.
1204          */
1205         if (!strpbrk(arg, "+@%") && (ptr = strpbrk(arg, ";:")) != NULL) {
1206                 /* This is a file spec if it includes a '.' before ; or : */
1207                 if (memchr(arg, '.', ptr - arg))
1208                         file_spec = true;
1209         }
1210
1211         ptr = strpbrk(arg, ";:+@%");
1212         if (ptr) {
1213                 nc = *ptr;
1214                 *ptr++ = '\0';
1215         }
1216
1217         if (arg[0] == '\0')
1218                 tmp = NULL;
1219         else {
1220                 tmp = strdup(arg);
1221                 if (tmp == NULL)
1222                         return -ENOMEM;
1223         }
1224
1225         if (file_spec)
1226                 pp->file = tmp;
1227         else {
1228                 pp->function = tmp;
1229
1230                 /*
1231                  * Keep pp->function even if this is absolute address,
1232                  * so it can mark whether abs_address is valid.
1233                  * Which make 'perf probe lib.bin 0x0' possible.
1234                  *
1235                  * Note that checking length of tmp is not needed
1236                  * because when we access tmp[1] we know tmp[0] is '0',
1237                  * so tmp[1] should always valid (but could be '\0').
1238                  */
1239                 if (tmp && !strncmp(tmp, "0x", 2)) {
1240                         pp->abs_address = strtoul(pp->function, &tmp, 0);
1241                         if (*tmp != '\0') {
1242                                 semantic_error("Invalid absolute address.\n");
1243                                 return -EINVAL;
1244                         }
1245                 }
1246         }
1247
1248         /* Parse other options */
1249         while (ptr) {
1250                 arg = ptr;
1251                 c = nc;
1252                 if (c == ';') { /* Lazy pattern must be the last part */
1253                         pp->lazy_line = strdup(arg);
1254                         if (pp->lazy_line == NULL)
1255                                 return -ENOMEM;
1256                         break;
1257                 }
1258                 ptr = strpbrk(arg, ";:+@%");
1259                 if (ptr) {
1260                         nc = *ptr;
1261                         *ptr++ = '\0';
1262                 }
1263                 switch (c) {
1264                 case ':':       /* Line number */
1265                         pp->line = strtoul(arg, &tmp, 0);
1266                         if (*tmp != '\0') {
1267                                 semantic_error("There is non-digit char"
1268                                                " in line number.\n");
1269                                 return -EINVAL;
1270                         }
1271                         break;
1272                 case '+':       /* Byte offset from a symbol */
1273                         pp->offset = strtoul(arg, &tmp, 0);
1274                         if (*tmp != '\0') {
1275                                 semantic_error("There is non-digit character"
1276                                                 " in offset.\n");
1277                                 return -EINVAL;
1278                         }
1279                         break;
1280                 case '@':       /* File name */
1281                         if (pp->file) {
1282                                 semantic_error("SRC@SRC is not allowed.\n");
1283                                 return -EINVAL;
1284                         }
1285                         pp->file = strdup(arg);
1286                         if (pp->file == NULL)
1287                                 return -ENOMEM;
1288                         break;
1289                 case '%':       /* Probe places */
1290                         if (strcmp(arg, "return") == 0) {
1291                                 pp->retprobe = 1;
1292                         } else {        /* Others not supported yet */
1293                                 semantic_error("%%%s is not supported.\n", arg);
1294                                 return -ENOTSUP;
1295                         }
1296                         break;
1297                 default:        /* Buggy case */
1298                         pr_err("This program has a bug at %s:%d.\n",
1299                                 __FILE__, __LINE__);
1300                         return -ENOTSUP;
1301                         break;
1302                 }
1303         }
1304
1305         /* Exclusion check */
1306         if (pp->lazy_line && pp->line) {
1307                 semantic_error("Lazy pattern can't be used with"
1308                                " line number.\n");
1309                 return -EINVAL;
1310         }
1311
1312         if (pp->lazy_line && pp->offset) {
1313                 semantic_error("Lazy pattern can't be used with offset.\n");
1314                 return -EINVAL;
1315         }
1316
1317         if (pp->line && pp->offset) {
1318                 semantic_error("Offset can't be used with line number.\n");
1319                 return -EINVAL;
1320         }
1321
1322         if (!pp->line && !pp->lazy_line && pp->file && !pp->function) {
1323                 semantic_error("File always requires line number or "
1324                                "lazy pattern.\n");
1325                 return -EINVAL;
1326         }
1327
1328         if (pp->offset && !pp->function) {
1329                 semantic_error("Offset requires an entry function.\n");
1330                 return -EINVAL;
1331         }
1332
1333         if (pp->retprobe && !pp->function) {
1334                 semantic_error("Return probe requires an entry function.\n");
1335                 return -EINVAL;
1336         }
1337
1338         if ((pp->offset || pp->line || pp->lazy_line) && pp->retprobe) {
1339                 semantic_error("Offset/Line/Lazy pattern can't be used with "
1340                                "return probe.\n");
1341                 return -EINVAL;
1342         }
1343
1344         pr_debug("symbol:%s file:%s line:%d offset:%lu return:%d lazy:%s\n",
1345                  pp->function, pp->file, pp->line, pp->offset, pp->retprobe,
1346                  pp->lazy_line);
1347         return 0;
1348 }
1349
1350 /* Parse perf-probe event argument */
1351 static int parse_perf_probe_arg(char *str, struct perf_probe_arg *arg)
1352 {
1353         char *tmp, *goodname;
1354         struct perf_probe_arg_field **fieldp;
1355
1356         pr_debug("parsing arg: %s into ", str);
1357
1358         tmp = strchr(str, '=');
1359         if (tmp) {
1360                 arg->name = strndup(str, tmp - str);
1361                 if (arg->name == NULL)
1362                         return -ENOMEM;
1363                 pr_debug("name:%s ", arg->name);
1364                 str = tmp + 1;
1365         }
1366
1367         tmp = strchr(str, ':');
1368         if (tmp) {      /* Type setting */
1369                 *tmp = '\0';
1370                 arg->type = strdup(tmp + 1);
1371                 if (arg->type == NULL)
1372                         return -ENOMEM;
1373                 pr_debug("type:%s ", arg->type);
1374         }
1375
1376         tmp = strpbrk(str, "-.[");
1377         if (!is_c_varname(str) || !tmp) {
1378                 /* A variable, register, symbol or special value */
1379                 arg->var = strdup(str);
1380                 if (arg->var == NULL)
1381                         return -ENOMEM;
1382                 pr_debug("%s\n", arg->var);
1383                 return 0;
1384         }
1385
1386         /* Structure fields or array element */
1387         arg->var = strndup(str, tmp - str);
1388         if (arg->var == NULL)
1389                 return -ENOMEM;
1390         goodname = arg->var;
1391         pr_debug("%s, ", arg->var);
1392         fieldp = &arg->field;
1393
1394         do {
1395                 *fieldp = zalloc(sizeof(struct perf_probe_arg_field));
1396                 if (*fieldp == NULL)
1397                         return -ENOMEM;
1398                 if (*tmp == '[') {      /* Array */
1399                         str = tmp;
1400                         (*fieldp)->index = strtol(str + 1, &tmp, 0);
1401                         (*fieldp)->ref = true;
1402                         if (*tmp != ']' || tmp == str + 1) {
1403                                 semantic_error("Array index must be a"
1404                                                 " number.\n");
1405                                 return -EINVAL;
1406                         }
1407                         tmp++;
1408                         if (*tmp == '\0')
1409                                 tmp = NULL;
1410                 } else {                /* Structure */
1411                         if (*tmp == '.') {
1412                                 str = tmp + 1;
1413                                 (*fieldp)->ref = false;
1414                         } else if (tmp[1] == '>') {
1415                                 str = tmp + 2;
1416                                 (*fieldp)->ref = true;
1417                         } else {
1418                                 semantic_error("Argument parse error: %s\n",
1419                                                str);
1420                                 return -EINVAL;
1421                         }
1422                         tmp = strpbrk(str, "-.[");
1423                 }
1424                 if (tmp) {
1425                         (*fieldp)->name = strndup(str, tmp - str);
1426                         if ((*fieldp)->name == NULL)
1427                                 return -ENOMEM;
1428                         if (*str != '[')
1429                                 goodname = (*fieldp)->name;
1430                         pr_debug("%s(%d), ", (*fieldp)->name, (*fieldp)->ref);
1431                         fieldp = &(*fieldp)->next;
1432                 }
1433         } while (tmp);
1434         (*fieldp)->name = strdup(str);
1435         if ((*fieldp)->name == NULL)
1436                 return -ENOMEM;
1437         if (*str != '[')
1438                 goodname = (*fieldp)->name;
1439         pr_debug("%s(%d)\n", (*fieldp)->name, (*fieldp)->ref);
1440
1441         /* If no name is specified, set the last field name (not array index)*/
1442         if (!arg->name) {
1443                 arg->name = strdup(goodname);
1444                 if (arg->name == NULL)
1445                         return -ENOMEM;
1446         }
1447         return 0;
1448 }
1449
1450 /* Parse perf-probe event command */
1451 int parse_perf_probe_command(const char *cmd, struct perf_probe_event *pev)
1452 {
1453         char **argv;
1454         int argc, i, ret = 0;
1455
1456         argv = argv_split(cmd, &argc);
1457         if (!argv) {
1458                 pr_debug("Failed to split arguments.\n");
1459                 return -ENOMEM;
1460         }
1461         if (argc - 1 > MAX_PROBE_ARGS) {
1462                 semantic_error("Too many probe arguments (%d).\n", argc - 1);
1463                 ret = -ERANGE;
1464                 goto out;
1465         }
1466         /* Parse probe point */
1467         ret = parse_perf_probe_point(argv[0], pev);
1468         if (ret < 0)
1469                 goto out;
1470
1471         /* Copy arguments and ensure return probe has no C argument */
1472         pev->nargs = argc - 1;
1473         pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1474         if (pev->args == NULL) {
1475                 ret = -ENOMEM;
1476                 goto out;
1477         }
1478         for (i = 0; i < pev->nargs && ret >= 0; i++) {
1479                 ret = parse_perf_probe_arg(argv[i + 1], &pev->args[i]);
1480                 if (ret >= 0 &&
1481                     is_c_varname(pev->args[i].var) && pev->point.retprobe) {
1482                         semantic_error("You can't specify local variable for"
1483                                        " kretprobe.\n");
1484                         ret = -EINVAL;
1485                 }
1486         }
1487 out:
1488         argv_free(argv);
1489
1490         return ret;
1491 }
1492
1493 /* Return true if this perf_probe_event requires debuginfo */
1494 bool perf_probe_event_need_dwarf(struct perf_probe_event *pev)
1495 {
1496         int i;
1497
1498         if (pev->point.file || pev->point.line || pev->point.lazy_line)
1499                 return true;
1500
1501         for (i = 0; i < pev->nargs; i++)
1502                 if (is_c_varname(pev->args[i].var))
1503                         return true;
1504
1505         return false;
1506 }
1507
1508 /* Parse probe_events event into struct probe_point */
1509 int parse_probe_trace_command(const char *cmd, struct probe_trace_event *tev)
1510 {
1511         struct probe_trace_point *tp = &tev->point;
1512         char pr;
1513         char *p;
1514         char *argv0_str = NULL, *fmt, *fmt1_str, *fmt2_str, *fmt3_str;
1515         int ret, i, argc;
1516         char **argv;
1517
1518         pr_debug("Parsing probe_events: %s\n", cmd);
1519         argv = argv_split(cmd, &argc);
1520         if (!argv) {
1521                 pr_debug("Failed to split arguments.\n");
1522                 return -ENOMEM;
1523         }
1524         if (argc < 2) {
1525                 semantic_error("Too few probe arguments.\n");
1526                 ret = -ERANGE;
1527                 goto out;
1528         }
1529
1530         /* Scan event and group name. */
1531         argv0_str = strdup(argv[0]);
1532         if (argv0_str == NULL) {
1533                 ret = -ENOMEM;
1534                 goto out;
1535         }
1536         fmt1_str = strtok_r(argv0_str, ":", &fmt);
1537         fmt2_str = strtok_r(NULL, "/", &fmt);
1538         fmt3_str = strtok_r(NULL, " \t", &fmt);
1539         if (fmt1_str == NULL || strlen(fmt1_str) != 1 || fmt2_str == NULL
1540             || fmt3_str == NULL) {
1541                 semantic_error("Failed to parse event name: %s\n", argv[0]);
1542                 ret = -EINVAL;
1543                 goto out;
1544         }
1545         pr = fmt1_str[0];
1546         tev->group = strdup(fmt2_str);
1547         tev->event = strdup(fmt3_str);
1548         if (tev->group == NULL || tev->event == NULL) {
1549                 ret = -ENOMEM;
1550                 goto out;
1551         }
1552         pr_debug("Group:%s Event:%s probe:%c\n", tev->group, tev->event, pr);
1553
1554         tp->retprobe = (pr == 'r');
1555
1556         /* Scan module name(if there), function name and offset */
1557         p = strchr(argv[1], ':');
1558         if (p) {
1559                 tp->module = strndup(argv[1], p - argv[1]);
1560                 p++;
1561         } else
1562                 p = argv[1];
1563         fmt1_str = strtok_r(p, "+", &fmt);
1564         /* only the address started with 0x */
1565         if (fmt1_str[0] == '0') {
1566                 /*
1567                  * Fix a special case:
1568                  * if address == 0, kernel reports something like:
1569                  * p:probe_libc/abs_0 /lib/libc-2.18.so:0x          (null) arg1=%ax
1570                  * Newer kernel may fix that, but we want to
1571                  * support old kernel also.
1572                  */
1573                 if (strcmp(fmt1_str, "0x") == 0) {
1574                         if (!argv[2] || strcmp(argv[2], "(null)")) {
1575                                 ret = -EINVAL;
1576                                 goto out;
1577                         }
1578                         tp->address = 0;
1579
1580                         free(argv[2]);
1581                         for (i = 2; argv[i + 1] != NULL; i++)
1582                                 argv[i] = argv[i + 1];
1583
1584                         argv[i] = NULL;
1585                         argc -= 1;
1586                 } else
1587                         tp->address = strtoul(fmt1_str, NULL, 0);
1588         } else {
1589                 /* Only the symbol-based probe has offset */
1590                 tp->symbol = strdup(fmt1_str);
1591                 if (tp->symbol == NULL) {
1592                         ret = -ENOMEM;
1593                         goto out;
1594                 }
1595                 fmt2_str = strtok_r(NULL, "", &fmt);
1596                 if (fmt2_str == NULL)
1597                         tp->offset = 0;
1598                 else
1599                         tp->offset = strtoul(fmt2_str, NULL, 10);
1600         }
1601
1602         tev->nargs = argc - 2;
1603         tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
1604         if (tev->args == NULL) {
1605                 ret = -ENOMEM;
1606                 goto out;
1607         }
1608         for (i = 0; i < tev->nargs; i++) {
1609                 p = strchr(argv[i + 2], '=');
1610                 if (p)  /* We don't need which register is assigned. */
1611                         *p++ = '\0';
1612                 else
1613                         p = argv[i + 2];
1614                 tev->args[i].name = strdup(argv[i + 2]);
1615                 /* TODO: parse regs and offset */
1616                 tev->args[i].value = strdup(p);
1617                 if (tev->args[i].name == NULL || tev->args[i].value == NULL) {
1618                         ret = -ENOMEM;
1619                         goto out;
1620                 }
1621         }
1622         ret = 0;
1623 out:
1624         free(argv0_str);
1625         argv_free(argv);
1626         return ret;
1627 }
1628
1629 /* Compose only probe arg */
1630 int synthesize_perf_probe_arg(struct perf_probe_arg *pa, char *buf, size_t len)
1631 {
1632         struct perf_probe_arg_field *field = pa->field;
1633         int ret;
1634         char *tmp = buf;
1635
1636         if (pa->name && pa->var)
1637                 ret = e_snprintf(tmp, len, "%s=%s", pa->name, pa->var);
1638         else
1639                 ret = e_snprintf(tmp, len, "%s", pa->name ? pa->name : pa->var);
1640         if (ret <= 0)
1641                 goto error;
1642         tmp += ret;
1643         len -= ret;
1644
1645         while (field) {
1646                 if (field->name[0] == '[')
1647                         ret = e_snprintf(tmp, len, "%s", field->name);
1648                 else
1649                         ret = e_snprintf(tmp, len, "%s%s",
1650                                          field->ref ? "->" : ".", field->name);
1651                 if (ret <= 0)
1652                         goto error;
1653                 tmp += ret;
1654                 len -= ret;
1655                 field = field->next;
1656         }
1657
1658         if (pa->type) {
1659                 ret = e_snprintf(tmp, len, ":%s", pa->type);
1660                 if (ret <= 0)
1661                         goto error;
1662                 tmp += ret;
1663                 len -= ret;
1664         }
1665
1666         return tmp - buf;
1667 error:
1668         pr_debug("Failed to synthesize perf probe argument: %d\n", ret);
1669         return ret;
1670 }
1671
1672 /* Compose only probe point (not argument) */
1673 static char *synthesize_perf_probe_point(struct perf_probe_point *pp)
1674 {
1675         char *buf, *tmp;
1676         char offs[32] = "", line[32] = "", file[32] = "";
1677         int ret, len;
1678
1679         buf = zalloc(MAX_CMDLEN);
1680         if (buf == NULL) {
1681                 ret = -ENOMEM;
1682                 goto error;
1683         }
1684         if (pp->offset) {
1685                 ret = e_snprintf(offs, 32, "+%lu", pp->offset);
1686                 if (ret <= 0)
1687                         goto error;
1688         }
1689         if (pp->line) {
1690                 ret = e_snprintf(line, 32, ":%d", pp->line);
1691                 if (ret <= 0)
1692                         goto error;
1693         }
1694         if (pp->file) {
1695                 tmp = pp->file;
1696                 len = strlen(tmp);
1697                 if (len > 30) {
1698                         tmp = strchr(pp->file + len - 30, '/');
1699                         tmp = tmp ? tmp + 1 : pp->file + len - 30;
1700                 }
1701                 ret = e_snprintf(file, 32, "@%s", tmp);
1702                 if (ret <= 0)
1703                         goto error;
1704         }
1705
1706         if (pp->function)
1707                 ret = e_snprintf(buf, MAX_CMDLEN, "%s%s%s%s%s", pp->function,
1708                                  offs, pp->retprobe ? "%return" : "", line,
1709                                  file);
1710         else
1711                 ret = e_snprintf(buf, MAX_CMDLEN, "%s%s", file, line);
1712         if (ret <= 0)
1713                 goto error;
1714
1715         return buf;
1716 error:
1717         pr_debug("Failed to synthesize perf probe point: %d\n", ret);
1718         free(buf);
1719         return NULL;
1720 }
1721
1722 #if 0
1723 char *synthesize_perf_probe_command(struct perf_probe_event *pev)
1724 {
1725         char *buf;
1726         int i, len, ret;
1727
1728         buf = synthesize_perf_probe_point(&pev->point);
1729         if (!buf)
1730                 return NULL;
1731
1732         len = strlen(buf);
1733         for (i = 0; i < pev->nargs; i++) {
1734                 ret = e_snprintf(&buf[len], MAX_CMDLEN - len, " %s",
1735                                  pev->args[i].name);
1736                 if (ret <= 0) {
1737                         free(buf);
1738                         return NULL;
1739                 }
1740                 len += ret;
1741         }
1742
1743         return buf;
1744 }
1745 #endif
1746
1747 static int __synthesize_probe_trace_arg_ref(struct probe_trace_arg_ref *ref,
1748                                              char **buf, size_t *buflen,
1749                                              int depth)
1750 {
1751         int ret;
1752         if (ref->next) {
1753                 depth = __synthesize_probe_trace_arg_ref(ref->next, buf,
1754                                                          buflen, depth + 1);
1755                 if (depth < 0)
1756                         goto out;
1757         }
1758
1759         ret = e_snprintf(*buf, *buflen, "%+ld(", ref->offset);
1760         if (ret < 0)
1761                 depth = ret;
1762         else {
1763                 *buf += ret;
1764                 *buflen -= ret;
1765         }
1766 out:
1767         return depth;
1768
1769 }
1770
1771 static int synthesize_probe_trace_arg(struct probe_trace_arg *arg,
1772                                        char *buf, size_t buflen)
1773 {
1774         struct probe_trace_arg_ref *ref = arg->ref;
1775         int ret, depth = 0;
1776         char *tmp = buf;
1777
1778         /* Argument name or separator */
1779         if (arg->name)
1780                 ret = e_snprintf(buf, buflen, " %s=", arg->name);
1781         else
1782                 ret = e_snprintf(buf, buflen, " ");
1783         if (ret < 0)
1784                 return ret;
1785         buf += ret;
1786         buflen -= ret;
1787
1788         /* Special case: @XXX */
1789         if (arg->value[0] == '@' && arg->ref)
1790                         ref = ref->next;
1791
1792         /* Dereferencing arguments */
1793         if (ref) {
1794                 depth = __synthesize_probe_trace_arg_ref(ref, &buf,
1795                                                           &buflen, 1);
1796                 if (depth < 0)
1797                         return depth;
1798         }
1799
1800         /* Print argument value */
1801         if (arg->value[0] == '@' && arg->ref)
1802                 ret = e_snprintf(buf, buflen, "%s%+ld", arg->value,
1803                                  arg->ref->offset);
1804         else
1805                 ret = e_snprintf(buf, buflen, "%s", arg->value);
1806         if (ret < 0)
1807                 return ret;
1808         buf += ret;
1809         buflen -= ret;
1810
1811         /* Closing */
1812         while (depth--) {
1813                 ret = e_snprintf(buf, buflen, ")");
1814                 if (ret < 0)
1815                         return ret;
1816                 buf += ret;
1817                 buflen -= ret;
1818         }
1819         /* Print argument type */
1820         if (arg->type) {
1821                 ret = e_snprintf(buf, buflen, ":%s", arg->type);
1822                 if (ret <= 0)
1823                         return ret;
1824                 buf += ret;
1825         }
1826
1827         return buf - tmp;
1828 }
1829
1830 char *synthesize_probe_trace_command(struct probe_trace_event *tev)
1831 {
1832         struct probe_trace_point *tp = &tev->point;
1833         char *buf;
1834         int i, len, ret;
1835
1836         buf = zalloc(MAX_CMDLEN);
1837         if (buf == NULL)
1838                 return NULL;
1839
1840         len = e_snprintf(buf, MAX_CMDLEN, "%c:%s/%s ", tp->retprobe ? 'r' : 'p',
1841                          tev->group, tev->event);
1842         if (len <= 0)
1843                 goto error;
1844
1845         /* Uprobes must have tp->module */
1846         if (tev->uprobes && !tp->module)
1847                 goto error;
1848         /*
1849          * If tp->address == 0, then this point must be a
1850          * absolute address uprobe.
1851          * try_to_find_absolute_address() should have made
1852          * tp->symbol to "0x0".
1853          */
1854         if (tev->uprobes && !tp->address) {
1855                 if (!tp->symbol || strcmp(tp->symbol, "0x0"))
1856                         goto error;
1857         }
1858
1859         /* Use the tp->address for uprobes */
1860         if (tev->uprobes)
1861                 ret = e_snprintf(buf + len, MAX_CMDLEN - len, "%s:0x%lx",
1862                                  tp->module, tp->address);
1863         else if (!strncmp(tp->symbol, "0x", 2))
1864                 /* Absolute address. See try_to_find_absolute_address() */
1865                 ret = e_snprintf(buf + len, MAX_CMDLEN - len, "%s%s0x%lx",
1866                                  tp->module ?: "", tp->module ? ":" : "",
1867                                  tp->address);
1868         else
1869                 ret = e_snprintf(buf + len, MAX_CMDLEN - len, "%s%s%s+%lu",
1870                                  tp->module ?: "", tp->module ? ":" : "",
1871                                  tp->symbol, tp->offset);
1872
1873         if (ret <= 0)
1874                 goto error;
1875         len += ret;
1876
1877         for (i = 0; i < tev->nargs; i++) {
1878                 ret = synthesize_probe_trace_arg(&tev->args[i], buf + len,
1879                                                   MAX_CMDLEN - len);
1880                 if (ret <= 0)
1881                         goto error;
1882                 len += ret;
1883         }
1884
1885         return buf;
1886 error:
1887         free(buf);
1888         return NULL;
1889 }
1890
1891 static int find_perf_probe_point_from_map(struct probe_trace_point *tp,
1892                                           struct perf_probe_point *pp,
1893                                           bool is_kprobe)
1894 {
1895         struct symbol *sym = NULL;
1896         struct map *map;
1897         u64 addr = tp->address;
1898         int ret = -ENOENT;
1899
1900         if (!is_kprobe) {
1901                 map = dso__new_map(tp->module);
1902                 if (!map)
1903                         goto out;
1904                 sym = map__find_symbol(map, addr, NULL);
1905         } else {
1906                 if (tp->symbol && !addr) {
1907                         if (kernel_get_symbol_address_by_name(tp->symbol,
1908                                                 &addr, true, false) < 0)
1909                                 goto out;
1910                 }
1911                 if (addr) {
1912                         addr += tp->offset;
1913                         sym = __find_kernel_function(addr, &map);
1914                 }
1915         }
1916
1917         if (!sym)
1918                 goto out;
1919
1920         pp->retprobe = tp->retprobe;
1921         pp->offset = addr - map->unmap_ip(map, sym->start);
1922         pp->function = strdup(sym->name);
1923         ret = pp->function ? 0 : -ENOMEM;
1924
1925 out:
1926         if (map && !is_kprobe) {
1927                 map__put(map);
1928         }
1929
1930         return ret;
1931 }
1932
1933 static int convert_to_perf_probe_point(struct probe_trace_point *tp,
1934                                        struct perf_probe_point *pp,
1935                                        bool is_kprobe)
1936 {
1937         char buf[128];
1938         int ret;
1939
1940         ret = find_perf_probe_point_from_dwarf(tp, pp, is_kprobe);
1941         if (!ret)
1942                 return 0;
1943         ret = find_perf_probe_point_from_map(tp, pp, is_kprobe);
1944         if (!ret)
1945                 return 0;
1946
1947         pr_debug("Failed to find probe point from both of dwarf and map.\n");
1948
1949         if (tp->symbol) {
1950                 pp->function = strdup(tp->symbol);
1951                 pp->offset = tp->offset;
1952         } else {
1953                 ret = e_snprintf(buf, 128, "0x%" PRIx64, (u64)tp->address);
1954                 if (ret < 0)
1955                         return ret;
1956                 pp->function = strdup(buf);
1957                 pp->offset = 0;
1958         }
1959         if (pp->function == NULL)
1960                 return -ENOMEM;
1961
1962         pp->retprobe = tp->retprobe;
1963
1964         return 0;
1965 }
1966
1967 static int convert_to_perf_probe_event(struct probe_trace_event *tev,
1968                                struct perf_probe_event *pev, bool is_kprobe)
1969 {
1970         char buf[64] = "";
1971         int i, ret;
1972
1973         /* Convert event/group name */
1974         pev->event = strdup(tev->event);
1975         pev->group = strdup(tev->group);
1976         if (pev->event == NULL || pev->group == NULL)
1977                 return -ENOMEM;
1978
1979         /* Convert trace_point to probe_point */
1980         ret = convert_to_perf_probe_point(&tev->point, &pev->point, is_kprobe);
1981         if (ret < 0)
1982                 return ret;
1983
1984         /* Convert trace_arg to probe_arg */
1985         pev->nargs = tev->nargs;
1986         pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1987         if (pev->args == NULL)
1988                 return -ENOMEM;
1989         for (i = 0; i < tev->nargs && ret >= 0; i++) {
1990                 if (tev->args[i].name)
1991                         pev->args[i].name = strdup(tev->args[i].name);
1992                 else {
1993                         ret = synthesize_probe_trace_arg(&tev->args[i],
1994                                                           buf, 64);
1995                         pev->args[i].name = strdup(buf);
1996                 }
1997                 if (pev->args[i].name == NULL && ret >= 0)
1998                         ret = -ENOMEM;
1999         }
2000
2001         if (ret < 0)
2002                 clear_perf_probe_event(pev);
2003
2004         return ret;
2005 }
2006
2007 void clear_perf_probe_event(struct perf_probe_event *pev)
2008 {
2009         struct perf_probe_arg_field *field, *next;
2010         int i;
2011
2012         free(pev->event);
2013         free(pev->group);
2014         free(pev->target);
2015         clear_perf_probe_point(&pev->point);
2016
2017         for (i = 0; i < pev->nargs; i++) {
2018                 free(pev->args[i].name);
2019                 free(pev->args[i].var);
2020                 free(pev->args[i].type);
2021                 field = pev->args[i].field;
2022                 while (field) {
2023                         next = field->next;
2024                         zfree(&field->name);
2025                         free(field);
2026                         field = next;
2027                 }
2028         }
2029         free(pev->args);
2030         memset(pev, 0, sizeof(*pev));
2031 }
2032
2033 void clear_probe_trace_event(struct probe_trace_event *tev)
2034 {
2035         struct probe_trace_arg_ref *ref, *next;
2036         int i;
2037
2038         free(tev->event);
2039         free(tev->group);
2040         free(tev->point.symbol);
2041         free(tev->point.realname);
2042         free(tev->point.module);
2043         for (i = 0; i < tev->nargs; i++) {
2044                 free(tev->args[i].name);
2045                 free(tev->args[i].value);
2046                 free(tev->args[i].type);
2047                 ref = tev->args[i].ref;
2048                 while (ref) {
2049                         next = ref->next;
2050                         free(ref);
2051                         ref = next;
2052                 }
2053         }
2054         free(tev->args);
2055         memset(tev, 0, sizeof(*tev));
2056 }
2057
2058 struct kprobe_blacklist_node {
2059         struct list_head list;
2060         unsigned long start;
2061         unsigned long end;
2062         char *symbol;
2063 };
2064
2065 static void kprobe_blacklist__delete(struct list_head *blacklist)
2066 {
2067         struct kprobe_blacklist_node *node;
2068
2069         while (!list_empty(blacklist)) {
2070                 node = list_first_entry(blacklist,
2071                                         struct kprobe_blacklist_node, list);
2072                 list_del(&node->list);
2073                 free(node->symbol);
2074                 free(node);
2075         }
2076 }
2077
2078 static int kprobe_blacklist__load(struct list_head *blacklist)
2079 {
2080         struct kprobe_blacklist_node *node;
2081         const char *__debugfs = debugfs__mountpoint();
2082         char buf[PATH_MAX], *p;
2083         FILE *fp;
2084         int ret;
2085
2086         if (__debugfs == NULL)
2087                 return -ENOTSUP;
2088
2089         ret = e_snprintf(buf, PATH_MAX, "%s/kprobes/blacklist", __debugfs);
2090         if (ret < 0)
2091                 return ret;
2092
2093         fp = fopen(buf, "r");
2094         if (!fp)
2095                 return -errno;
2096
2097         ret = 0;
2098         while (fgets(buf, PATH_MAX, fp)) {
2099                 node = zalloc(sizeof(*node));
2100                 if (!node) {
2101                         ret = -ENOMEM;
2102                         break;
2103                 }
2104                 INIT_LIST_HEAD(&node->list);
2105                 list_add_tail(&node->list, blacklist);
2106                 if (sscanf(buf, "0x%lx-0x%lx", &node->start, &node->end) != 2) {
2107                         ret = -EINVAL;
2108                         break;
2109                 }
2110                 p = strchr(buf, '\t');
2111                 if (p) {
2112                         p++;
2113                         if (p[strlen(p) - 1] == '\n')
2114                                 p[strlen(p) - 1] = '\0';
2115                 } else
2116                         p = (char *)"unknown";
2117                 node->symbol = strdup(p);
2118                 if (!node->symbol) {
2119                         ret = -ENOMEM;
2120                         break;
2121                 }
2122                 pr_debug2("Blacklist: 0x%lx-0x%lx, %s\n",
2123                           node->start, node->end, node->symbol);
2124                 ret++;
2125         }
2126         if (ret < 0)
2127                 kprobe_blacklist__delete(blacklist);
2128         fclose(fp);
2129
2130         return ret;
2131 }
2132
2133 static struct kprobe_blacklist_node *
2134 kprobe_blacklist__find_by_address(struct list_head *blacklist,
2135                                   unsigned long address)
2136 {
2137         struct kprobe_blacklist_node *node;
2138
2139         list_for_each_entry(node, blacklist, list) {
2140                 if (node->start <= address && address <= node->end)
2141                         return node;
2142         }
2143
2144         return NULL;
2145 }
2146
2147 static LIST_HEAD(kprobe_blacklist);
2148
2149 static void kprobe_blacklist__init(void)
2150 {
2151         if (!list_empty(&kprobe_blacklist))
2152                 return;
2153
2154         if (kprobe_blacklist__load(&kprobe_blacklist) < 0)
2155                 pr_debug("No kprobe blacklist support, ignored\n");
2156 }
2157
2158 static void kprobe_blacklist__release(void)
2159 {
2160         kprobe_blacklist__delete(&kprobe_blacklist);
2161 }
2162
2163 static bool kprobe_blacklist__listed(unsigned long address)
2164 {
2165         return !!kprobe_blacklist__find_by_address(&kprobe_blacklist, address);
2166 }
2167
2168 static int perf_probe_event__sprintf(const char *group, const char *event,
2169                                      struct perf_probe_event *pev,
2170                                      const char *module,
2171                                      struct strbuf *result)
2172 {
2173         int i, ret;
2174         char buf[128];
2175         char *place;
2176
2177         /* Synthesize only event probe point */
2178         place = synthesize_perf_probe_point(&pev->point);
2179         if (!place)
2180                 return -EINVAL;
2181
2182         ret = e_snprintf(buf, 128, "%s:%s", group, event);
2183         if (ret < 0)
2184                 goto out;
2185
2186         strbuf_addf(result, "  %-20s (on %s", buf, place);
2187         if (module)
2188                 strbuf_addf(result, " in %s", module);
2189
2190         if (pev->nargs > 0) {
2191                 strbuf_addstr(result, " with");
2192                 for (i = 0; i < pev->nargs; i++) {
2193                         ret = synthesize_perf_probe_arg(&pev->args[i],
2194                                                         buf, 128);
2195                         if (ret < 0)
2196                                 goto out;
2197                         strbuf_addf(result, " %s", buf);
2198                 }
2199         }
2200         strbuf_addch(result, ')');
2201 out:
2202         free(place);
2203         return ret;
2204 }
2205
2206 /* Show an event */
2207 int show_perf_probe_event(const char *group, const char *event,
2208                           struct perf_probe_event *pev,
2209                           const char *module, bool use_stdout)
2210 {
2211         struct strbuf buf = STRBUF_INIT;
2212         int ret;
2213
2214         ret = perf_probe_event__sprintf(group, event, pev, module, &buf);
2215         if (ret >= 0) {
2216                 if (use_stdout)
2217                         printf("%s\n", buf.buf);
2218                 else
2219                         pr_info("%s\n", buf.buf);
2220         }
2221         strbuf_release(&buf);
2222
2223         return ret;
2224 }
2225
2226 static bool filter_probe_trace_event(struct probe_trace_event *tev,
2227                                      struct strfilter *filter)
2228 {
2229         char tmp[128];
2230
2231         /* At first, check the event name itself */
2232         if (strfilter__compare(filter, tev->event))
2233                 return true;
2234
2235         /* Next, check the combination of name and group */
2236         if (e_snprintf(tmp, 128, "%s:%s", tev->group, tev->event) < 0)
2237                 return false;
2238         return strfilter__compare(filter, tmp);
2239 }
2240
2241 static int __show_perf_probe_events(int fd, bool is_kprobe,
2242                                     struct strfilter *filter)
2243 {
2244         int ret = 0;
2245         struct probe_trace_event tev;
2246         struct perf_probe_event pev;
2247         struct strlist *rawlist;
2248         struct str_node *ent;
2249
2250         memset(&tev, 0, sizeof(tev));
2251         memset(&pev, 0, sizeof(pev));
2252
2253         rawlist = probe_file__get_rawlist(fd);
2254         if (!rawlist)
2255                 return -ENOMEM;
2256
2257         strlist__for_each(ent, rawlist) {
2258                 ret = parse_probe_trace_command(ent->s, &tev);
2259                 if (ret >= 0) {
2260                         if (!filter_probe_trace_event(&tev, filter))
2261                                 goto next;
2262                         ret = convert_to_perf_probe_event(&tev, &pev,
2263                                                                 is_kprobe);
2264                         if (ret < 0)
2265                                 goto next;
2266                         ret = show_perf_probe_event(pev.group, pev.event,
2267                                                     &pev, tev.point.module,
2268                                                     true);
2269                 }
2270 next:
2271                 clear_perf_probe_event(&pev);
2272                 clear_probe_trace_event(&tev);
2273                 if (ret < 0)
2274                         break;
2275         }
2276         strlist__delete(rawlist);
2277         /* Cleanup cached debuginfo if needed */
2278         debuginfo_cache__exit();
2279
2280         return ret;
2281 }
2282
2283 /* List up current perf-probe events */
2284 int show_perf_probe_events(struct strfilter *filter)
2285 {
2286         int kp_fd, up_fd, ret;
2287
2288         setup_pager();
2289
2290         ret = init_probe_symbol_maps(false);
2291         if (ret < 0)
2292                 return ret;
2293
2294         ret = probe_file__open_both(&kp_fd, &up_fd, 0);
2295         if (ret < 0)
2296                 return ret;
2297
2298         if (kp_fd >= 0)
2299                 ret = __show_perf_probe_events(kp_fd, true, filter);
2300         if (up_fd >= 0 && ret >= 0)
2301                 ret = __show_perf_probe_events(up_fd, false, filter);
2302         if (kp_fd > 0)
2303                 close(kp_fd);
2304         if (up_fd > 0)
2305                 close(up_fd);
2306         exit_probe_symbol_maps();
2307
2308         return ret;
2309 }
2310
2311 static int get_new_event_name(char *buf, size_t len, const char *base,
2312                               struct strlist *namelist, bool allow_suffix)
2313 {
2314         int i, ret;
2315         char *p, *nbase;
2316
2317         if (*base == '.')
2318                 base++;
2319         nbase = strdup(base);
2320         if (!nbase)
2321                 return -ENOMEM;
2322
2323         /* Cut off the dot suffixes (e.g. .const, .isra)*/
2324         p = strchr(nbase, '.');
2325         if (p && p != nbase)
2326                 *p = '\0';
2327
2328         /* Try no suffix number */
2329         ret = e_snprintf(buf, len, "%s", nbase);
2330         if (ret < 0) {
2331                 pr_debug("snprintf() failed: %d\n", ret);
2332                 goto out;
2333         }
2334         if (!strlist__has_entry(namelist, buf))
2335                 goto out;
2336
2337         if (!allow_suffix) {
2338                 pr_warning("Error: event \"%s\" already exists. "
2339                            "(Use -f to force duplicates.)\n", buf);
2340                 ret = -EEXIST;
2341                 goto out;
2342         }
2343
2344         /* Try to add suffix */
2345         for (i = 1; i < MAX_EVENT_INDEX; i++) {
2346                 ret = e_snprintf(buf, len, "%s_%d", nbase, i);
2347                 if (ret < 0) {
2348                         pr_debug("snprintf() failed: %d\n", ret);
2349                         goto out;
2350                 }
2351                 if (!strlist__has_entry(namelist, buf))
2352                         break;
2353         }
2354         if (i == MAX_EVENT_INDEX) {
2355                 pr_warning("Too many events are on the same function.\n");
2356                 ret = -ERANGE;
2357         }
2358
2359 out:
2360         free(nbase);
2361
2362         /* Final validation */
2363         if (ret >= 0 && !is_c_func_name(buf)) {
2364                 pr_warning("Internal error: \"%s\" is an invalid event name.\n",
2365                            buf);
2366                 ret = -EINVAL;
2367         }
2368
2369         return ret;
2370 }
2371
2372 /* Warn if the current kernel's uprobe implementation is old */
2373 static void warn_uprobe_event_compat(struct probe_trace_event *tev)
2374 {
2375         int i;
2376         char *buf = synthesize_probe_trace_command(tev);
2377
2378         /* Old uprobe event doesn't support memory dereference */
2379         if (!tev->uprobes || tev->nargs == 0 || !buf)
2380                 goto out;
2381
2382         for (i = 0; i < tev->nargs; i++)
2383                 if (strglobmatch(tev->args[i].value, "[$@+-]*")) {
2384                         pr_warning("Please upgrade your kernel to at least "
2385                                    "3.14 to have access to feature %s\n",
2386                                    tev->args[i].value);
2387                         break;
2388                 }
2389 out:
2390         free(buf);
2391 }
2392
2393 /* Set new name from original perf_probe_event and namelist */
2394 static int probe_trace_event__set_name(struct probe_trace_event *tev,
2395                                        struct perf_probe_event *pev,
2396                                        struct strlist *namelist,
2397                                        bool allow_suffix)
2398 {
2399         const char *event, *group;
2400         char buf[64];
2401         int ret;
2402
2403         if (pev->event)
2404                 event = pev->event;
2405         else
2406                 if (pev->point.function &&
2407                         (strncmp(pev->point.function, "0x", 2) != 0) &&
2408                         !strisglob(pev->point.function))
2409                         event = pev->point.function;
2410                 else
2411                         event = tev->point.realname;
2412         if (pev->group)
2413                 group = pev->group;
2414         else
2415                 group = PERFPROBE_GROUP;
2416
2417         /* Get an unused new event name */
2418         ret = get_new_event_name(buf, 64, event,
2419                                  namelist, allow_suffix);
2420         if (ret < 0)
2421                 return ret;
2422
2423         event = buf;
2424
2425         tev->event = strdup(event);
2426         tev->group = strdup(group);
2427         if (tev->event == NULL || tev->group == NULL)
2428                 return -ENOMEM;
2429
2430         /* Add added event name to namelist */
2431         strlist__add(namelist, event);
2432         return 0;
2433 }
2434
2435 static int __add_probe_trace_events(struct perf_probe_event *pev,
2436                                      struct probe_trace_event *tevs,
2437                                      int ntevs, bool allow_suffix)
2438 {
2439         int i, fd, ret;
2440         struct probe_trace_event *tev = NULL;
2441         struct strlist *namelist;
2442
2443         fd = probe_file__open(PF_FL_RW | (pev->uprobes ? PF_FL_UPROBE : 0));
2444         if (fd < 0)
2445                 return fd;
2446
2447         /* Get current event names */
2448         namelist = probe_file__get_namelist(fd);
2449         if (!namelist) {
2450                 pr_debug("Failed to get current event list.\n");
2451                 ret = -ENOMEM;
2452                 goto close_out;
2453         }
2454
2455         ret = 0;
2456         for (i = 0; i < ntevs; i++) {
2457                 tev = &tevs[i];
2458                 /* Skip if the symbol is out of .text or blacklisted */
2459                 if (!tev->point.symbol)
2460                         continue;
2461
2462                 /* Set new name for tev (and update namelist) */
2463                 ret = probe_trace_event__set_name(tev, pev, namelist,
2464                                                   allow_suffix);
2465                 if (ret < 0)
2466                         break;
2467
2468                 ret = probe_file__add_event(fd, tev);
2469                 if (ret < 0)
2470                         break;
2471
2472                 /*
2473                  * Probes after the first probe which comes from same
2474                  * user input are always allowed to add suffix, because
2475                  * there might be several addresses corresponding to
2476                  * one code line.
2477                  */
2478                 allow_suffix = true;
2479         }
2480         if (ret == -EINVAL && pev->uprobes)
2481                 warn_uprobe_event_compat(tev);
2482
2483         strlist__delete(namelist);
2484 close_out:
2485         close(fd);
2486         return ret;
2487 }
2488
2489 static int find_probe_functions(struct map *map, char *name,
2490                                 struct symbol **syms)
2491 {
2492         int found = 0;
2493         struct symbol *sym;
2494         struct rb_node *tmp;
2495
2496         if (map__load(map, NULL) < 0)
2497                 return 0;
2498
2499         map__for_each_symbol(map, sym, tmp) {
2500                 if (strglobmatch(sym->name, name)) {
2501                         found++;
2502                         if (syms && found < probe_conf.max_probes)
2503                                 syms[found - 1] = sym;
2504                 }
2505         }
2506
2507         return found;
2508 }
2509
2510 #define strdup_or_goto(str, label)      \
2511         ({ char *__p = strdup(str); if (!__p) goto label; __p; })
2512
2513 void __weak arch__fix_tev_from_maps(struct perf_probe_event *pev __maybe_unused,
2514                                 struct probe_trace_event *tev __maybe_unused,
2515                                 struct map *map __maybe_unused) { }
2516
2517 /*
2518  * Find probe function addresses from map.
2519  * Return an error or the number of found probe_trace_event
2520  */
2521 static int find_probe_trace_events_from_map(struct perf_probe_event *pev,
2522                                             struct probe_trace_event **tevs)
2523 {
2524         struct map *map = NULL;
2525         struct ref_reloc_sym *reloc_sym = NULL;
2526         struct symbol *sym;
2527         struct symbol **syms = NULL;
2528         struct probe_trace_event *tev;
2529         struct perf_probe_point *pp = &pev->point;
2530         struct probe_trace_point *tp;
2531         int num_matched_functions;
2532         int ret, i, j, skipped = 0;
2533
2534         map = get_target_map(pev->target, pev->uprobes);
2535         if (!map) {
2536                 ret = -EINVAL;
2537                 goto out;
2538         }
2539
2540         syms = malloc(sizeof(struct symbol *) * probe_conf.max_probes);
2541         if (!syms) {
2542                 ret = -ENOMEM;
2543                 goto out;
2544         }
2545
2546         /*
2547          * Load matched symbols: Since the different local symbols may have
2548          * same name but different addresses, this lists all the symbols.
2549          */
2550         num_matched_functions = find_probe_functions(map, pp->function, syms);
2551         if (num_matched_functions == 0) {
2552                 pr_err("Failed to find symbol %s in %s\n", pp->function,
2553                         pev->target ? : "kernel");
2554                 ret = -ENOENT;
2555                 goto out;
2556         } else if (num_matched_functions > probe_conf.max_probes) {
2557                 pr_err("Too many functions matched in %s\n",
2558                         pev->target ? : "kernel");
2559                 ret = -E2BIG;
2560                 goto out;
2561         }
2562
2563         /* Note that the symbols in the kmodule are not relocated */
2564         if (!pev->uprobes && !pp->retprobe && !pev->target) {
2565                 reloc_sym = kernel_get_ref_reloc_sym(NULL);
2566                 if (!reloc_sym) {
2567                         pr_warning("Relocated base symbol is not found!\n");
2568                         ret = -EINVAL;
2569                         goto out;
2570                 }
2571         }
2572
2573         /* Setup result trace-probe-events */
2574         *tevs = zalloc(sizeof(*tev) * num_matched_functions);
2575         if (!*tevs) {
2576                 ret = -ENOMEM;
2577                 goto out;
2578         }
2579
2580         ret = 0;
2581
2582         for (j = 0; j < num_matched_functions; j++) {
2583                 sym = syms[j];
2584
2585                 tev = (*tevs) + ret;
2586                 tp = &tev->point;
2587                 if (ret == num_matched_functions) {
2588                         pr_warning("Too many symbols are listed. Skip it.\n");
2589                         break;
2590                 }
2591                 ret++;
2592
2593                 if (pp->offset > sym->end - sym->start) {
2594                         pr_warning("Offset %ld is bigger than the size of %s\n",
2595                                    pp->offset, sym->name);
2596                         ret = -ENOENT;
2597                         goto err_out;
2598                 }
2599                 /* Add one probe point */
2600                 tp->address = map->unmap_ip(map, sym->start) + pp->offset;
2601
2602                 /* Check the kprobe (not in module) is within .text  */
2603                 if (!pev->uprobes && !pev->target &&
2604                     kprobe_warn_out_range(sym->name, tp->address)) {
2605                         tp->symbol = NULL;      /* Skip it */
2606                         skipped++;
2607                 } else if (reloc_sym) {
2608                         tp->symbol = strdup_or_goto(reloc_sym->name, nomem_out);
2609                         tp->offset = tp->address - reloc_sym->addr;
2610                 } else {
2611                         tp->symbol = strdup_or_goto(sym->name, nomem_out);
2612                         tp->offset = pp->offset;
2613                 }
2614                 tp->realname = strdup_or_goto(sym->name, nomem_out);
2615
2616                 tp->retprobe = pp->retprobe;
2617                 if (pev->target)
2618                         tev->point.module = strdup_or_goto(pev->target,
2619                                                            nomem_out);
2620                 tev->uprobes = pev->uprobes;
2621                 tev->nargs = pev->nargs;
2622                 if (tev->nargs) {
2623                         tev->args = zalloc(sizeof(struct probe_trace_arg) *
2624                                            tev->nargs);
2625                         if (tev->args == NULL)
2626                                 goto nomem_out;
2627                 }
2628                 for (i = 0; i < tev->nargs; i++) {
2629                         if (pev->args[i].name)
2630                                 tev->args[i].name =
2631                                         strdup_or_goto(pev->args[i].name,
2632                                                         nomem_out);
2633
2634                         tev->args[i].value = strdup_or_goto(pev->args[i].var,
2635                                                             nomem_out);
2636                         if (pev->args[i].type)
2637                                 tev->args[i].type =
2638                                         strdup_or_goto(pev->args[i].type,
2639                                                         nomem_out);
2640                 }
2641                 arch__fix_tev_from_maps(pev, tev, map);
2642         }
2643         if (ret == skipped) {
2644                 ret = -ENOENT;
2645                 goto err_out;
2646         }
2647
2648 out:
2649         put_target_map(map, pev->uprobes);
2650         free(syms);
2651         return ret;
2652
2653 nomem_out:
2654         ret = -ENOMEM;
2655 err_out:
2656         clear_probe_trace_events(*tevs, num_matched_functions);
2657         zfree(tevs);
2658         goto out;
2659 }
2660
2661 static int try_to_find_absolute_address(struct perf_probe_event *pev,
2662                                         struct probe_trace_event **tevs)
2663 {
2664         struct perf_probe_point *pp = &pev->point;
2665         struct probe_trace_event *tev;
2666         struct probe_trace_point *tp;
2667         int i, err;
2668
2669         if (!(pev->point.function && !strncmp(pev->point.function, "0x", 2)))
2670                 return -EINVAL;
2671         if (perf_probe_event_need_dwarf(pev))
2672                 return -EINVAL;
2673
2674         /*
2675          * This is 'perf probe /lib/libc.so 0xabcd'. Try to probe at
2676          * absolute address.
2677          *
2678          * Only one tev can be generated by this.
2679          */
2680         *tevs = zalloc(sizeof(*tev));
2681         if (!*tevs)
2682                 return -ENOMEM;
2683
2684         tev = *tevs;
2685         tp = &tev->point;
2686
2687         /*
2688          * Don't use tp->offset, use address directly, because
2689          * in synthesize_probe_trace_command() address cannot be
2690          * zero.
2691          */
2692         tp->address = pev->point.abs_address;
2693         tp->retprobe = pp->retprobe;
2694         tev->uprobes = pev->uprobes;
2695
2696         err = -ENOMEM;
2697         /*
2698          * Give it a '0x' leading symbol name.
2699          * In __add_probe_trace_events, a NULL symbol is interpreted as
2700          * invalud.
2701          */
2702         if (asprintf(&tp->symbol, "0x%lx", tp->address) < 0)
2703                 goto errout;
2704
2705         /* For kprobe, check range */
2706         if ((!tev->uprobes) &&
2707             (kprobe_warn_out_range(tev->point.symbol,
2708                                    tev->point.address))) {
2709                 err = -EACCES;
2710                 goto errout;
2711         }
2712
2713         if (asprintf(&tp->realname, "abs_%lx", tp->address) < 0)
2714                 goto errout;
2715
2716         if (pev->target) {
2717                 tp->module = strdup(pev->target);
2718                 if (!tp->module)
2719                         goto errout;
2720         }
2721
2722         if (tev->group) {
2723                 tev->group = strdup(pev->group);
2724                 if (!tev->group)
2725                         goto errout;
2726         }
2727
2728         if (pev->event) {
2729                 tev->event = strdup(pev->event);
2730                 if (!tev->event)
2731                         goto errout;
2732         }
2733
2734         tev->nargs = pev->nargs;
2735         tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
2736         if (!tev->args) {
2737                 err = -ENOMEM;
2738                 goto errout;
2739         }
2740         for (i = 0; i < tev->nargs; i++)
2741                 copy_to_probe_trace_arg(&tev->args[i], &pev->args[i]);
2742
2743         return 1;
2744
2745 errout:
2746         if (*tevs) {
2747                 clear_probe_trace_events(*tevs, 1);
2748                 *tevs = NULL;
2749         }
2750         return err;
2751 }
2752
2753 bool __weak arch__prefers_symtab(void) { return false; }
2754
2755 static int convert_to_probe_trace_events(struct perf_probe_event *pev,
2756                                          struct probe_trace_event **tevs)
2757 {
2758         int ret;
2759
2760         if (pev->uprobes && !pev->group) {
2761                 /* Replace group name if not given */
2762                 ret = convert_exec_to_group(pev->target, &pev->group);
2763                 if (ret != 0) {
2764                         pr_warning("Failed to make a group name.\n");
2765                         return ret;
2766                 }
2767         }
2768
2769         ret = try_to_find_absolute_address(pev, tevs);
2770         if (ret > 0)
2771                 return ret;
2772
2773         if (arch__prefers_symtab() && !perf_probe_event_need_dwarf(pev)) {
2774                 ret = find_probe_trace_events_from_map(pev, tevs);
2775                 if (ret > 0)
2776                         return ret; /* Found in symbol table */
2777         }
2778
2779         /* Convert perf_probe_event with debuginfo */
2780         ret = try_to_find_probe_trace_events(pev, tevs);
2781         if (ret != 0)
2782                 return ret;     /* Found in debuginfo or got an error */
2783
2784         return find_probe_trace_events_from_map(pev, tevs);
2785 }
2786
2787 int convert_perf_probe_events(struct perf_probe_event *pevs, int npevs)
2788 {
2789         int i, ret;
2790
2791         /* Loop 1: convert all events */
2792         for (i = 0; i < npevs; i++) {
2793                 /* Init kprobe blacklist if needed */
2794                 if (!pevs[i].uprobes)
2795                         kprobe_blacklist__init();
2796                 /* Convert with or without debuginfo */
2797                 ret  = convert_to_probe_trace_events(&pevs[i], &pevs[i].tevs);
2798                 if (ret < 0)
2799                         return ret;
2800                 pevs[i].ntevs = ret;
2801         }
2802         /* This just release blacklist only if allocated */
2803         kprobe_blacklist__release();
2804
2805         return 0;
2806 }
2807
2808 int apply_perf_probe_events(struct perf_probe_event *pevs, int npevs)
2809 {
2810         int i, ret = 0;
2811
2812         /* Loop 2: add all events */
2813         for (i = 0; i < npevs; i++) {
2814                 ret = __add_probe_trace_events(&pevs[i], pevs[i].tevs,
2815                                                pevs[i].ntevs,
2816                                                probe_conf.force_add);
2817                 if (ret < 0)
2818                         break;
2819         }
2820         return ret;
2821 }
2822
2823 void cleanup_perf_probe_events(struct perf_probe_event *pevs, int npevs)
2824 {
2825         int i, j;
2826
2827         /* Loop 3: cleanup and free trace events  */
2828         for (i = 0; i < npevs; i++) {
2829                 for (j = 0; j < pevs[i].ntevs; j++)
2830                         clear_probe_trace_event(&pevs[i].tevs[j]);
2831                 zfree(&pevs[i].tevs);
2832                 pevs[i].ntevs = 0;
2833                 clear_perf_probe_event(&pevs[i]);
2834         }
2835 }
2836
2837 int add_perf_probe_events(struct perf_probe_event *pevs, int npevs)
2838 {
2839         int ret;
2840
2841         ret = init_probe_symbol_maps(pevs->uprobes);
2842         if (ret < 0)
2843                 return ret;
2844
2845         ret = convert_perf_probe_events(pevs, npevs);
2846         if (ret == 0)
2847                 ret = apply_perf_probe_events(pevs, npevs);
2848
2849         cleanup_perf_probe_events(pevs, npevs);
2850
2851         exit_probe_symbol_maps();
2852         return ret;
2853 }
2854
2855 int del_perf_probe_events(struct strfilter *filter)
2856 {
2857         int ret, ret2, ufd = -1, kfd = -1;
2858         char *str = strfilter__string(filter);
2859
2860         if (!str)
2861                 return -EINVAL;
2862
2863         /* Get current event names */
2864         ret = probe_file__open_both(&kfd, &ufd, PF_FL_RW);
2865         if (ret < 0)
2866                 goto out;
2867
2868         ret = probe_file__del_events(kfd, filter);
2869         if (ret < 0 && ret != -ENOENT)
2870                 goto error;
2871
2872         ret2 = probe_file__del_events(ufd, filter);
2873         if (ret2 < 0 && ret2 != -ENOENT) {
2874                 ret = ret2;
2875                 goto error;
2876         }
2877         ret = 0;
2878
2879 error:
2880         if (kfd >= 0)
2881                 close(kfd);
2882         if (ufd >= 0)
2883                 close(ufd);
2884 out:
2885         free(str);
2886
2887         return ret;
2888 }
2889
2890 /* TODO: don't use a global variable for filter ... */
2891 static struct strfilter *available_func_filter;
2892
2893 /*
2894  * If a symbol corresponds to a function with global binding and
2895  * matches filter return 0. For all others return 1.
2896  */
2897 static int filter_available_functions(struct map *map __maybe_unused,
2898                                       struct symbol *sym)
2899 {
2900         if (strfilter__compare(available_func_filter, sym->name))
2901                 return 0;
2902         return 1;
2903 }
2904
2905 int show_available_funcs(const char *target, struct strfilter *_filter,
2906                                         bool user)
2907 {
2908         struct map *map;
2909         int ret;
2910
2911         ret = init_probe_symbol_maps(user);
2912         if (ret < 0)
2913                 return ret;
2914
2915         /* Get a symbol map */
2916         if (user)
2917                 map = dso__new_map(target);
2918         else
2919                 map = kernel_get_module_map(target);
2920         if (!map) {
2921                 pr_err("Failed to get a map for %s\n", (target) ? : "kernel");
2922                 return -EINVAL;
2923         }
2924
2925         /* Load symbols with given filter */
2926         available_func_filter = _filter;
2927         if (map__load(map, filter_available_functions)) {
2928                 pr_err("Failed to load symbols in %s\n", (target) ? : "kernel");
2929                 goto end;
2930         }
2931         if (!dso__sorted_by_name(map->dso, map->type))
2932                 dso__sort_by_name(map->dso, map->type);
2933
2934         /* Show all (filtered) symbols */
2935         setup_pager();
2936         dso__fprintf_symbols_by_name(map->dso, map->type, stdout);
2937 end:
2938         if (user) {
2939                 map__put(map);
2940         }
2941         exit_probe_symbol_maps();
2942
2943         return ret;
2944 }
2945
2946 int copy_to_probe_trace_arg(struct probe_trace_arg *tvar,
2947                             struct perf_probe_arg *pvar)
2948 {
2949         tvar->value = strdup(pvar->var);
2950         if (tvar->value == NULL)
2951                 return -ENOMEM;
2952         if (pvar->type) {
2953                 tvar->type = strdup(pvar->type);
2954                 if (tvar->type == NULL)
2955                         return -ENOMEM;
2956         }
2957         if (pvar->name) {
2958                 tvar->name = strdup(pvar->name);
2959                 if (tvar->name == NULL)
2960                         return -ENOMEM;
2961         } else
2962                 tvar->name = NULL;
2963         return 0;
2964 }