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