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