perf probe: Remove die() from probe-finder code
[safe/jmp/linux-2.6] / tools / perf / util / probe-event.c
1 /*
2  * probe-event.c : perf-probe definition to kprobe_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 #define _GNU_SOURCE
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
35 #undef _GNU_SOURCE
36 #include "util.h"
37 #include "event.h"
38 #include "string.h"
39 #include "strlist.h"
40 #include "debug.h"
41 #include "cache.h"
42 #include "color.h"
43 #include "symbol.h"
44 #include "thread.h"
45 #include "trace-event.h"        /* For __unused */
46 #include "parse-events.h"       /* For debugfs_path */
47 #include "probe-event.h"
48 #include "probe-finder.h"
49
50 #define MAX_CMDLEN 256
51 #define MAX_PROBE_ARGS 128
52 #define PERFPROBE_GROUP "probe"
53
54 bool probe_event_dry_run;       /* Dry run flag */
55
56 #define semantic_error(msg ...) die("Semantic error :" msg)
57
58 /* If there is no space to write, returns -E2BIG. */
59 static int e_snprintf(char *str, size_t size, const char *format, ...)
60         __attribute__((format(printf, 3, 4)));
61
62 static 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 char *synthesize_perf_probe_point(struct perf_probe_point *pp);
75 static struct map_groups kmap_groups;
76 static struct map *kmaps[MAP__NR_TYPES];
77
78 /* Initialize symbol maps and path of vmlinux */
79 static void init_vmlinux(void)
80 {
81         symbol_conf.sort_by_name = true;
82         if (symbol_conf.vmlinux_name == NULL)
83                 symbol_conf.try_vmlinux_path = true;
84         else
85                 pr_debug("Use vmlinux: %s\n", symbol_conf.vmlinux_name);
86         if (symbol__init() < 0)
87                 die("Failed to init symbol map.");
88
89         map_groups__init(&kmap_groups);
90         if (map_groups__create_kernel_maps(&kmap_groups, kmaps) < 0)
91                 die("Failed to create kernel maps.");
92 }
93
94 #ifdef DWARF_SUPPORT
95 static int open_vmlinux(void)
96 {
97         if (map__load(kmaps[MAP__FUNCTION], NULL) < 0) {
98                 pr_debug("Failed to load kernel map.\n");
99                 return -EINVAL;
100         }
101         pr_debug("Try to open %s\n", kmaps[MAP__FUNCTION]->dso->long_name);
102         return open(kmaps[MAP__FUNCTION]->dso->long_name, O_RDONLY);
103 }
104
105 static void convert_to_perf_probe_point(struct kprobe_trace_point *tp,
106                                         struct perf_probe_point *pp)
107 {
108         struct symbol *sym;
109         int fd, ret = 0;
110
111         sym = map__find_symbol_by_name(kmaps[MAP__FUNCTION],
112                                        tp->symbol, NULL);
113         if (sym) {
114                 fd = open_vmlinux();
115                 ret = find_perf_probe_point(fd, sym->start + tp->offset, pp);
116                 close(fd);
117         }
118         if (ret <= 0) {
119                 pp->function = xstrdup(tp->symbol);
120                 pp->offset = tp->offset;
121         }
122         pp->retprobe = tp->retprobe;
123 }
124
125 /* Try to find perf_probe_event with debuginfo */
126 static int try_to_find_kprobe_trace_events(struct perf_probe_event *pev,
127                                            struct kprobe_trace_event **tevs)
128 {
129         bool need_dwarf = perf_probe_event_need_dwarf(pev);
130         int fd, ntevs;
131
132         fd = open_vmlinux();
133         if (fd < 0) {
134                 if (need_dwarf)
135                         die("Could not open debuginfo file.");
136
137                 pr_debug("Could not open vmlinux. Try to use symbols.\n");
138                 return 0;
139         }
140
141         /* Searching trace events corresponding to probe event */
142         ntevs = find_kprobe_trace_events(fd, pev, tevs);
143         close(fd);
144
145         if (ntevs > 0)  /* Succeeded to find trace events */
146                 return ntevs;
147
148         if (ntevs == 0) /* No error but failed to find probe point. */
149                 die("Probe point '%s' not found. - probe not added.",
150                     synthesize_perf_probe_point(&pev->point));
151
152         /* Error path */
153         if (need_dwarf) {
154                 if (ntevs == -EBADF)
155                         pr_warning("No dwarf info found in the vmlinux - "
156                                 "please rebuild with CONFIG_DEBUG_INFO=y.\n");
157                 die("Failed to analyze debuginfo.");
158         }
159         pr_debug("An error occurred in debuginfo analysis."
160                  " Try to use symbols.\n");
161         return 0;
162
163 }
164
165 #define LINEBUF_SIZE 256
166 #define NR_ADDITIONAL_LINES 2
167
168 static void show_one_line(FILE *fp, unsigned int l, bool skip, bool show_num)
169 {
170         char buf[LINEBUF_SIZE];
171         const char *color = PERF_COLOR_BLUE;
172
173         if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
174                 goto error;
175         if (!skip) {
176                 if (show_num)
177                         fprintf(stdout, "%7u  %s", l, buf);
178                 else
179                         color_fprintf(stdout, color, "         %s", buf);
180         }
181
182         while (strlen(buf) == LINEBUF_SIZE - 1 &&
183                buf[LINEBUF_SIZE - 2] != '\n') {
184                 if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
185                         goto error;
186                 if (!skip) {
187                         if (show_num)
188                                 fprintf(stdout, "%s", buf);
189                         else
190                                 color_fprintf(stdout, color, "%s", buf);
191                 }
192         }
193         return;
194 error:
195         if (feof(fp))
196                 die("Source file is shorter than expected.");
197         else
198                 die("File read error: %s", strerror(errno));
199 }
200
201 /*
202  * Show line-range always requires debuginfo to find source file and
203  * line number.
204  */
205 void show_line_range(struct line_range *lr)
206 {
207         unsigned int l = 1;
208         struct line_node *ln;
209         FILE *fp;
210         int fd, ret;
211
212         /* Search a line range */
213         init_vmlinux();
214         fd = open_vmlinux();
215         if (fd < 0)
216                 die("Could not open debuginfo file.");
217         ret = find_line_range(fd, lr);
218         if (ret <= 0)
219                 die("Source line is not found.\n");
220         close(fd);
221
222         setup_pager();
223
224         if (lr->function)
225                 fprintf(stdout, "<%s:%d>\n", lr->function,
226                         lr->start - lr->offset);
227         else
228                 fprintf(stdout, "<%s:%d>\n", lr->file, lr->start);
229
230         fp = fopen(lr->path, "r");
231         if (fp == NULL)
232                 die("Failed to open %s: %s", lr->path, strerror(errno));
233         /* Skip to starting line number */
234         while (l < lr->start)
235                 show_one_line(fp, l++, true, false);
236
237         list_for_each_entry(ln, &lr->line_list, list) {
238                 while (ln->line > l)
239                         show_one_line(fp, (l++) - lr->offset, false, false);
240                 show_one_line(fp, (l++) - lr->offset, false, true);
241         }
242
243         if (lr->end == INT_MAX)
244                 lr->end = l + NR_ADDITIONAL_LINES;
245         while (l < lr->end && !feof(fp))
246                 show_one_line(fp, (l++) - lr->offset, false, false);
247
248         fclose(fp);
249 }
250
251 #else   /* !DWARF_SUPPORT */
252
253 static void convert_to_perf_probe_point(struct kprobe_trace_point *tp,
254                                         struct perf_probe_point *pp)
255 {
256         pp->function = xstrdup(tp->symbol);
257         pp->offset = tp->offset;
258         pp->retprobe = tp->retprobe;
259 }
260
261 static int try_to_find_kprobe_trace_events(struct perf_probe_event *pev,
262                                 struct kprobe_trace_event **tevs __unused)
263 {
264         if (perf_probe_event_need_dwarf(pev))
265                 die("Debuginfo-analysis is not supported");
266         return 0;
267 }
268
269 void show_line_range(struct line_range *lr __unused)
270 {
271         die("Debuginfo-analysis is not supported");
272 }
273
274 #endif
275
276 void parse_line_range_desc(const char *arg, struct line_range *lr)
277 {
278         const char *ptr;
279         char *tmp;
280         /*
281          * <Syntax>
282          * SRC:SLN[+NUM|-ELN]
283          * FUNC[:SLN[+NUM|-ELN]]
284          */
285         ptr = strchr(arg, ':');
286         if (ptr) {
287                 lr->start = (unsigned int)strtoul(ptr + 1, &tmp, 0);
288                 if (*tmp == '+')
289                         lr->end = lr->start + (unsigned int)strtoul(tmp + 1,
290                                                                     &tmp, 0);
291                 else if (*tmp == '-')
292                         lr->end = (unsigned int)strtoul(tmp + 1, &tmp, 0);
293                 else
294                         lr->end = 0;
295                 pr_debug("Line range is %u to %u\n", lr->start, lr->end);
296                 if (lr->end && lr->start > lr->end)
297                         semantic_error("Start line must be smaller"
298                                        " than end line.");
299                 if (*tmp != '\0')
300                         semantic_error("Tailing with invalid character '%d'.",
301                                        *tmp);
302                 tmp = xstrndup(arg, (ptr - arg));
303         } else
304                 tmp = xstrdup(arg);
305
306         if (strchr(tmp, '.'))
307                 lr->file = tmp;
308         else
309                 lr->function = tmp;
310 }
311
312 /* Check the name is good for event/group */
313 static bool check_event_name(const char *name)
314 {
315         if (!isalpha(*name) && *name != '_')
316                 return false;
317         while (*++name != '\0') {
318                 if (!isalpha(*name) && !isdigit(*name) && *name != '_')
319                         return false;
320         }
321         return true;
322 }
323
324 /* Parse probepoint definition. */
325 static void parse_perf_probe_point(char *arg, struct perf_probe_event *pev)
326 {
327         struct perf_probe_point *pp = &pev->point;
328         char *ptr, *tmp;
329         char c, nc = 0;
330         /*
331          * <Syntax>
332          * perf probe [EVENT=]SRC[:LN|;PTN]
333          * perf probe [EVENT=]FUNC[@SRC][+OFFS|%return|:LN|;PAT]
334          *
335          * TODO:Group name support
336          */
337
338         ptr = strpbrk(arg, ";=@+%");
339         if (ptr && *ptr == '=') {       /* Event name */
340                 *ptr = '\0';
341                 tmp = ptr + 1;
342                 ptr = strchr(arg, ':');
343                 if (ptr)        /* Group name is not supported yet. */
344                         semantic_error("Group name is not supported yet.");
345                 if (!check_event_name(arg))
346                         semantic_error("%s is bad for event name -it must "
347                                        "follow C symbol-naming rule.", arg);
348                 pev->event = xstrdup(arg);
349                 pev->group = NULL;
350                 arg = tmp;
351         }
352
353         ptr = strpbrk(arg, ";:+@%");
354         if (ptr) {
355                 nc = *ptr;
356                 *ptr++ = '\0';
357         }
358
359         /* Check arg is function or file and copy it */
360         if (strchr(arg, '.'))   /* File */
361                 pp->file = xstrdup(arg);
362         else                    /* Function */
363                 pp->function = xstrdup(arg);
364
365         /* Parse other options */
366         while (ptr) {
367                 arg = ptr;
368                 c = nc;
369                 if (c == ';') { /* Lazy pattern must be the last part */
370                         pp->lazy_line = xstrdup(arg);
371                         break;
372                 }
373                 ptr = strpbrk(arg, ";:+@%");
374                 if (ptr) {
375                         nc = *ptr;
376                         *ptr++ = '\0';
377                 }
378                 switch (c) {
379                 case ':':       /* Line number */
380                         pp->line = strtoul(arg, &tmp, 0);
381                         if (*tmp != '\0')
382                                 semantic_error("There is non-digit char"
383                                                " in line number.");
384                         break;
385                 case '+':       /* Byte offset from a symbol */
386                         pp->offset = strtoul(arg, &tmp, 0);
387                         if (*tmp != '\0')
388                                 semantic_error("There is non-digit character"
389                                                 " in offset.");
390                         break;
391                 case '@':       /* File name */
392                         if (pp->file)
393                                 semantic_error("SRC@SRC is not allowed.");
394                         pp->file = xstrdup(arg);
395                         break;
396                 case '%':       /* Probe places */
397                         if (strcmp(arg, "return") == 0) {
398                                 pp->retprobe = 1;
399                         } else  /* Others not supported yet */
400                                 semantic_error("%%%s is not supported.", arg);
401                         break;
402                 default:
403                         DIE_IF("Program has a bug.");
404                         break;
405                 }
406         }
407
408         /* Exclusion check */
409         if (pp->lazy_line && pp->line)
410                 semantic_error("Lazy pattern can't be used with line number.");
411
412         if (pp->lazy_line && pp->offset)
413                 semantic_error("Lazy pattern can't be used with offset.");
414
415         if (pp->line && pp->offset)
416                 semantic_error("Offset can't be used with line number.");
417
418         if (!pp->line && !pp->lazy_line && pp->file && !pp->function)
419                 semantic_error("File always requires line number or "
420                                "lazy pattern.");
421
422         if (pp->offset && !pp->function)
423                 semantic_error("Offset requires an entry function.");
424
425         if (pp->retprobe && !pp->function)
426                 semantic_error("Return probe requires an entry function.");
427
428         if ((pp->offset || pp->line || pp->lazy_line) && pp->retprobe)
429                 semantic_error("Offset/Line/Lazy pattern can't be used with "
430                                "return probe.");
431
432         pr_debug("symbol:%s file:%s line:%d offset:%lu return:%d lazy:%s\n",
433                  pp->function, pp->file, pp->line, pp->offset, pp->retprobe,
434                  pp->lazy_line);
435 }
436
437 /* Parse perf-probe event argument */
438 static void parse_perf_probe_arg(char *str, struct perf_probe_arg *arg)
439 {
440         char *tmp;
441         struct perf_probe_arg_field **fieldp;
442
443         pr_debug("parsing arg: %s into ", str);
444
445         tmp = strchr(str, '=');
446         if (tmp) {
447                 arg->name = xstrndup(str, tmp - str);
448                 pr_debug("name:%s ", arg->name);
449                 str = tmp + 1;
450         }
451
452         tmp = strchr(str, ':');
453         if (tmp) {      /* Type setting */
454                 *tmp = '\0';
455                 arg->type = xstrdup(tmp + 1);
456                 pr_debug("type:%s ", arg->type);
457         }
458
459         tmp = strpbrk(str, "-.");
460         if (!is_c_varname(str) || !tmp) {
461                 /* A variable, register, symbol or special value */
462                 arg->var = xstrdup(str);
463                 pr_debug("%s\n", arg->var);
464                 return;
465         }
466
467         /* Structure fields */
468         arg->var = xstrndup(str, tmp - str);
469         pr_debug("%s, ", arg->var);
470         fieldp = &arg->field;
471
472         do {
473                 *fieldp = xzalloc(sizeof(struct perf_probe_arg_field));
474                 if (*tmp == '.') {
475                         str = tmp + 1;
476                         (*fieldp)->ref = false;
477                 } else if (tmp[1] == '>') {
478                         str = tmp + 2;
479                         (*fieldp)->ref = true;
480                 } else
481                         semantic_error("Argument parse error: %s", str);
482
483                 tmp = strpbrk(str, "-.");
484                 if (tmp) {
485                         (*fieldp)->name = xstrndup(str, tmp - str);
486                         pr_debug("%s(%d), ", (*fieldp)->name, (*fieldp)->ref);
487                         fieldp = &(*fieldp)->next;
488                 }
489         } while (tmp);
490         (*fieldp)->name = xstrdup(str);
491         pr_debug("%s(%d)\n", (*fieldp)->name, (*fieldp)->ref);
492
493         /* If no name is specified, set the last field name */
494         if (!arg->name)
495                 arg->name = xstrdup((*fieldp)->name);
496 }
497
498 /* Parse perf-probe event command */
499 void parse_perf_probe_command(const char *cmd, struct perf_probe_event *pev)
500 {
501         char **argv;
502         int argc, i;
503
504         argv = argv_split(cmd, &argc);
505         if (!argv)
506                 die("argv_split failed.");
507         if (argc > MAX_PROBE_ARGS + 1)
508                 semantic_error("Too many arguments");
509
510         /* Parse probe point */
511         parse_perf_probe_point(argv[0], pev);
512
513         /* Copy arguments and ensure return probe has no C argument */
514         pev->nargs = argc - 1;
515         pev->args = xzalloc(sizeof(struct perf_probe_arg) * pev->nargs);
516         for (i = 0; i < pev->nargs; i++) {
517                 parse_perf_probe_arg(argv[i + 1], &pev->args[i]);
518                 if (is_c_varname(pev->args[i].var) && pev->point.retprobe)
519                         semantic_error("You can't specify local variable for"
520                                        " kretprobe");
521         }
522
523         argv_free(argv);
524 }
525
526 /* Return true if this perf_probe_event requires debuginfo */
527 bool perf_probe_event_need_dwarf(struct perf_probe_event *pev)
528 {
529         int i;
530
531         if (pev->point.file || pev->point.line || pev->point.lazy_line)
532                 return true;
533
534         for (i = 0; i < pev->nargs; i++)
535                 if (is_c_varname(pev->args[i].var))
536                         return true;
537
538         return false;
539 }
540
541 /* Parse kprobe_events event into struct probe_point */
542 void parse_kprobe_trace_command(const char *cmd, struct kprobe_trace_event *tev)
543 {
544         struct kprobe_trace_point *tp = &tev->point;
545         char pr;
546         char *p;
547         int ret, i, argc;
548         char **argv;
549
550         pr_debug("Parsing kprobe_events: %s\n", cmd);
551         argv = argv_split(cmd, &argc);
552         if (!argv)
553                 die("argv_split failed.");
554         if (argc < 2)
555                 semantic_error("Too less arguments.");
556
557         /* Scan event and group name. */
558         ret = sscanf(argv[0], "%c:%a[^/ \t]/%a[^ \t]",
559                      &pr, (float *)(void *)&tev->group,
560                      (float *)(void *)&tev->event);
561         if (ret != 3)
562                 semantic_error("Failed to parse event name: %s", argv[0]);
563         pr_debug("Group:%s Event:%s probe:%c\n", tev->group, tev->event, pr);
564
565         tp->retprobe = (pr == 'r');
566
567         /* Scan function name and offset */
568         ret = sscanf(argv[1], "%a[^+]+%lu", (float *)(void *)&tp->symbol,
569                      &tp->offset);
570         if (ret == 1)
571                 tp->offset = 0;
572
573         tev->nargs = argc - 2;
574         tev->args = xzalloc(sizeof(struct kprobe_trace_arg) * tev->nargs);
575         for (i = 0; i < tev->nargs; i++) {
576                 p = strchr(argv[i + 2], '=');
577                 if (p)  /* We don't need which register is assigned. */
578                         *p++ = '\0';
579                 else
580                         p = argv[i + 2];
581                 tev->args[i].name = xstrdup(argv[i + 2]);
582                 /* TODO: parse regs and offset */
583                 tev->args[i].value = xstrdup(p);
584         }
585
586         argv_free(argv);
587 }
588
589 /* Compose only probe arg */
590 int synthesize_perf_probe_arg(struct perf_probe_arg *pa, char *buf, size_t len)
591 {
592         struct perf_probe_arg_field *field = pa->field;
593         int ret;
594         char *tmp = buf;
595
596         if (pa->name && pa->var)
597                 ret = e_snprintf(tmp, len, "%s=%s", pa->name, pa->var);
598         else
599                 ret = e_snprintf(tmp, len, "%s", pa->name ? pa->name : pa->var);
600         if (ret <= 0)
601                 goto error;
602         tmp += ret;
603         len -= ret;
604
605         while (field) {
606                 ret = e_snprintf(tmp, len, "%s%s", field->ref ? "->" : ".",
607                                  field->name);
608                 if (ret <= 0)
609                         goto error;
610                 tmp += ret;
611                 len -= ret;
612                 field = field->next;
613         }
614
615         if (pa->type) {
616                 ret = e_snprintf(tmp, len, ":%s", pa->type);
617                 if (ret <= 0)
618                         goto error;
619                 tmp += ret;
620                 len -= ret;
621         }
622
623         return tmp - buf;
624 error:
625         die("Failed to synthesize perf probe argument: %s", strerror(-ret));
626 }
627
628 /* Compose only probe point (not argument) */
629 static char *synthesize_perf_probe_point(struct perf_probe_point *pp)
630 {
631         char *buf, *tmp;
632         char offs[32] = "", line[32] = "", file[32] = "";
633         int ret, len;
634
635         buf = xzalloc(MAX_CMDLEN);
636         if (pp->offset) {
637                 ret = e_snprintf(offs, 32, "+%lu", pp->offset);
638                 if (ret <= 0)
639                         goto error;
640         }
641         if (pp->line) {
642                 ret = e_snprintf(line, 32, ":%d", pp->line);
643                 if (ret <= 0)
644                         goto error;
645         }
646         if (pp->file) {
647                 len = strlen(pp->file) - 32;
648                 if (len < 0)
649                         len = 0;
650                 tmp = strchr(pp->file + len, '/');
651                 if (!tmp)
652                         tmp = pp->file + len - 1;
653                 ret = e_snprintf(file, 32, "@%s", tmp + 1);
654                 if (ret <= 0)
655                         goto error;
656         }
657
658         if (pp->function)
659                 ret = e_snprintf(buf, MAX_CMDLEN, "%s%s%s%s%s", pp->function,
660                                  offs, pp->retprobe ? "%return" : "", line,
661                                  file);
662         else
663                 ret = e_snprintf(buf, MAX_CMDLEN, "%s%s", file, line);
664         if (ret <= 0)
665                 goto error;
666
667         return buf;
668 error:
669         die("Failed to synthesize perf probe point: %s", strerror(-ret));
670 }
671
672 #if 0
673 char *synthesize_perf_probe_command(struct perf_probe_event *pev)
674 {
675         char *buf;
676         int i, len, ret;
677
678         buf = synthesize_perf_probe_point(&pev->point);
679         if (!buf)
680                 return NULL;
681
682         len = strlen(buf);
683         for (i = 0; i < pev->nargs; i++) {
684                 ret = e_snprintf(&buf[len], MAX_CMDLEN - len, " %s",
685                                  pev->args[i].name);
686                 if (ret <= 0) {
687                         free(buf);
688                         return NULL;
689                 }
690                 len += ret;
691         }
692
693         return buf;
694 }
695 #endif
696
697 static int __synthesize_kprobe_trace_arg_ref(struct kprobe_trace_arg_ref *ref,
698                                              char **buf, size_t *buflen,
699                                              int depth)
700 {
701         int ret;
702         if (ref->next) {
703                 depth = __synthesize_kprobe_trace_arg_ref(ref->next, buf,
704                                                          buflen, depth + 1);
705                 if (depth < 0)
706                         goto out;
707         }
708
709         ret = e_snprintf(*buf, *buflen, "%+ld(", ref->offset);
710         if (ret < 0)
711                 depth = ret;
712         else {
713                 *buf += ret;
714                 *buflen -= ret;
715         }
716 out:
717         return depth;
718
719 }
720
721 static int synthesize_kprobe_trace_arg(struct kprobe_trace_arg *arg,
722                                        char *buf, size_t buflen)
723 {
724         int ret, depth = 0;
725         char *tmp = buf;
726
727         /* Argument name or separator */
728         if (arg->name)
729                 ret = e_snprintf(buf, buflen, " %s=", arg->name);
730         else
731                 ret = e_snprintf(buf, buflen, " ");
732         if (ret < 0)
733                 return ret;
734         buf += ret;
735         buflen -= ret;
736
737         /* Dereferencing arguments */
738         if (arg->ref) {
739                 depth = __synthesize_kprobe_trace_arg_ref(arg->ref, &buf,
740                                                           &buflen, 1);
741                 if (depth < 0)
742                         return depth;
743         }
744
745         /* Print argument value */
746         ret = e_snprintf(buf, buflen, "%s", arg->value);
747         if (ret < 0)
748                 return ret;
749         buf += ret;
750         buflen -= ret;
751
752         /* Closing */
753         while (depth--) {
754                 ret = e_snprintf(buf, buflen, ")");
755                 if (ret < 0)
756                         return ret;
757                 buf += ret;
758                 buflen -= ret;
759         }
760         /* Print argument type */
761         if (arg->type) {
762                 ret = e_snprintf(buf, buflen, ":%s", arg->type);
763                 if (ret <= 0)
764                         return ret;
765                 buf += ret;
766         }
767
768         return buf - tmp;
769 }
770
771 char *synthesize_kprobe_trace_command(struct kprobe_trace_event *tev)
772 {
773         struct kprobe_trace_point *tp = &tev->point;
774         char *buf;
775         int i, len, ret;
776
777         buf = xzalloc(MAX_CMDLEN);
778         len = e_snprintf(buf, MAX_CMDLEN, "%c:%s/%s %s+%lu",
779                          tp->retprobe ? 'r' : 'p',
780                          tev->group, tev->event,
781                          tp->symbol, tp->offset);
782         if (len <= 0)
783                 goto error;
784
785         for (i = 0; i < tev->nargs; i++) {
786                 ret = synthesize_kprobe_trace_arg(&tev->args[i], buf + len,
787                                                   MAX_CMDLEN - len);
788                 if (ret <= 0)
789                         goto error;
790                 len += ret;
791         }
792
793         return buf;
794 error:
795         free(buf);
796         return NULL;
797 }
798
799 void convert_to_perf_probe_event(struct kprobe_trace_event *tev,
800                                  struct perf_probe_event *pev)
801 {
802         char buf[64];
803         int i;
804
805         /* Convert event/group name */
806         pev->event = xstrdup(tev->event);
807         pev->group = xstrdup(tev->group);
808
809         /* Convert trace_point to probe_point */
810         convert_to_perf_probe_point(&tev->point, &pev->point);
811
812         /* Convert trace_arg to probe_arg */
813         pev->nargs = tev->nargs;
814         pev->args = xzalloc(sizeof(struct perf_probe_arg) * pev->nargs);
815         for (i = 0; i < tev->nargs; i++)
816                 if (tev->args[i].name)
817                         pev->args[i].name = xstrdup(tev->args[i].name);
818                 else {
819                         synthesize_kprobe_trace_arg(&tev->args[i], buf, 64);
820                         pev->args[i].name = xstrdup(buf);
821                 }
822 }
823
824 void clear_perf_probe_event(struct perf_probe_event *pev)
825 {
826         struct perf_probe_point *pp = &pev->point;
827         struct perf_probe_arg_field *field, *next;
828         int i;
829
830         if (pev->event)
831                 free(pev->event);
832         if (pev->group)
833                 free(pev->group);
834         if (pp->file)
835                 free(pp->file);
836         if (pp->function)
837                 free(pp->function);
838         if (pp->lazy_line)
839                 free(pp->lazy_line);
840         for (i = 0; i < pev->nargs; i++) {
841                 if (pev->args[i].name)
842                         free(pev->args[i].name);
843                 if (pev->args[i].var)
844                         free(pev->args[i].var);
845                 if (pev->args[i].type)
846                         free(pev->args[i].type);
847                 field = pev->args[i].field;
848                 while (field) {
849                         next = field->next;
850                         if (field->name)
851                                 free(field->name);
852                         free(field);
853                         field = next;
854                 }
855         }
856         if (pev->args)
857                 free(pev->args);
858         memset(pev, 0, sizeof(*pev));
859 }
860
861 void clear_kprobe_trace_event(struct kprobe_trace_event *tev)
862 {
863         struct kprobe_trace_arg_ref *ref, *next;
864         int i;
865
866         if (tev->event)
867                 free(tev->event);
868         if (tev->group)
869                 free(tev->group);
870         if (tev->point.symbol)
871                 free(tev->point.symbol);
872         for (i = 0; i < tev->nargs; i++) {
873                 if (tev->args[i].name)
874                         free(tev->args[i].name);
875                 if (tev->args[i].value)
876                         free(tev->args[i].value);
877                 if (tev->args[i].type)
878                         free(tev->args[i].type);
879                 ref = tev->args[i].ref;
880                 while (ref) {
881                         next = ref->next;
882                         free(ref);
883                         ref = next;
884                 }
885         }
886         if (tev->args)
887                 free(tev->args);
888         memset(tev, 0, sizeof(*tev));
889 }
890
891 static int open_kprobe_events(bool readwrite)
892 {
893         char buf[PATH_MAX];
894         int ret;
895
896         ret = e_snprintf(buf, PATH_MAX, "%s/../kprobe_events", debugfs_path);
897         if (ret < 0)
898                 die("Failed to make kprobe_events path.");
899
900         if (readwrite && !probe_event_dry_run)
901                 ret = open(buf, O_RDWR, O_APPEND);
902         else
903                 ret = open(buf, O_RDONLY, 0);
904
905         if (ret < 0) {
906                 if (errno == ENOENT)
907                         die("kprobe_events file does not exist -"
908                             " please rebuild with CONFIG_KPROBE_EVENT.");
909                 else
910                         die("Could not open kprobe_events file: %s",
911                             strerror(errno));
912         }
913         return ret;
914 }
915
916 /* Get raw string list of current kprobe_events */
917 static struct strlist *get_kprobe_trace_command_rawlist(int fd)
918 {
919         int ret, idx;
920         FILE *fp;
921         char buf[MAX_CMDLEN];
922         char *p;
923         struct strlist *sl;
924
925         sl = strlist__new(true, NULL);
926
927         fp = fdopen(dup(fd), "r");
928         while (!feof(fp)) {
929                 p = fgets(buf, MAX_CMDLEN, fp);
930                 if (!p)
931                         break;
932
933                 idx = strlen(p) - 1;
934                 if (p[idx] == '\n')
935                         p[idx] = '\0';
936                 ret = strlist__add(sl, buf);
937                 if (ret < 0)
938                         die("strlist__add failed: %s", strerror(-ret));
939         }
940         fclose(fp);
941
942         return sl;
943 }
944
945 /* Show an event */
946 static void show_perf_probe_event(struct perf_probe_event *pev)
947 {
948         int i, ret;
949         char buf[128];
950         char *place;
951
952         /* Synthesize only event probe point */
953         place = synthesize_perf_probe_point(&pev->point);
954
955         ret = e_snprintf(buf, 128, "%s:%s", pev->group, pev->event);
956         if (ret < 0)
957                 die("Failed to copy event: %s", strerror(-ret));
958         printf("  %-20s (on %s", buf, place);
959
960         if (pev->nargs > 0) {
961                 printf(" with");
962                 for (i = 0; i < pev->nargs; i++) {
963                         synthesize_perf_probe_arg(&pev->args[i], buf, 128);
964                         printf(" %s", buf);
965                 }
966         }
967         printf(")\n");
968         free(place);
969 }
970
971 /* List up current perf-probe events */
972 void show_perf_probe_events(void)
973 {
974         int fd;
975         struct kprobe_trace_event tev;
976         struct perf_probe_event pev;
977         struct strlist *rawlist;
978         struct str_node *ent;
979
980         setup_pager();
981         init_vmlinux();
982
983         memset(&tev, 0, sizeof(tev));
984         memset(&pev, 0, sizeof(pev));
985
986         fd = open_kprobe_events(false);
987         rawlist = get_kprobe_trace_command_rawlist(fd);
988         close(fd);
989
990         strlist__for_each(ent, rawlist) {
991                 parse_kprobe_trace_command(ent->s, &tev);
992                 convert_to_perf_probe_event(&tev, &pev);
993                 /* Show an event */
994                 show_perf_probe_event(&pev);
995                 clear_perf_probe_event(&pev);
996                 clear_kprobe_trace_event(&tev);
997         }
998
999         strlist__delete(rawlist);
1000 }
1001
1002 /* Get current perf-probe event names */
1003 static struct strlist *get_kprobe_trace_event_names(int fd, bool include_group)
1004 {
1005         char buf[128];
1006         struct strlist *sl, *rawlist;
1007         struct str_node *ent;
1008         struct kprobe_trace_event tev;
1009
1010         memset(&tev, 0, sizeof(tev));
1011
1012         rawlist = get_kprobe_trace_command_rawlist(fd);
1013         sl = strlist__new(true, NULL);
1014         strlist__for_each(ent, rawlist) {
1015                 parse_kprobe_trace_command(ent->s, &tev);
1016                 if (include_group) {
1017                         if (e_snprintf(buf, 128, "%s:%s", tev.group,
1018                                        tev.event) < 0)
1019                                 die("Failed to copy group:event name.");
1020                         strlist__add(sl, buf);
1021                 } else
1022                         strlist__add(sl, tev.event);
1023                 clear_kprobe_trace_event(&tev);
1024         }
1025
1026         strlist__delete(rawlist);
1027
1028         return sl;
1029 }
1030
1031 static void write_kprobe_trace_event(int fd, struct kprobe_trace_event *tev)
1032 {
1033         int ret;
1034         char *buf = synthesize_kprobe_trace_command(tev);
1035
1036         pr_debug("Writing event: %s\n", buf);
1037         if (!probe_event_dry_run) {
1038                 ret = write(fd, buf, strlen(buf));
1039                 if (ret <= 0)
1040                         die("Failed to write event: %s", strerror(errno));
1041         }
1042         free(buf);
1043 }
1044
1045 static void get_new_event_name(char *buf, size_t len, const char *base,
1046                                struct strlist *namelist, bool allow_suffix)
1047 {
1048         int i, ret;
1049
1050         /* Try no suffix */
1051         ret = e_snprintf(buf, len, "%s", base);
1052         if (ret < 0)
1053                 die("snprintf() failed: %s", strerror(-ret));
1054         if (!strlist__has_entry(namelist, buf))
1055                 return;
1056
1057         if (!allow_suffix) {
1058                 pr_warning("Error: event \"%s\" already exists. "
1059                            "(Use -f to force duplicates.)\n", base);
1060                 die("Can't add new event.");
1061         }
1062
1063         /* Try to add suffix */
1064         for (i = 1; i < MAX_EVENT_INDEX; i++) {
1065                 ret = e_snprintf(buf, len, "%s_%d", base, i);
1066                 if (ret < 0)
1067                         die("snprintf() failed: %s", strerror(-ret));
1068                 if (!strlist__has_entry(namelist, buf))
1069                         break;
1070         }
1071         if (i == MAX_EVENT_INDEX)
1072                 die("Too many events are on the same function.");
1073 }
1074
1075 static void __add_kprobe_trace_events(struct perf_probe_event *pev,
1076                                       struct kprobe_trace_event *tevs,
1077                                       int ntevs, bool allow_suffix)
1078 {
1079         int i, fd;
1080         struct kprobe_trace_event *tev = NULL;
1081         char buf[64];
1082         const char *event, *group;
1083         struct strlist *namelist;
1084
1085         fd = open_kprobe_events(true);
1086         /* Get current event names */
1087         namelist = get_kprobe_trace_event_names(fd, false);
1088
1089         printf("Add new event%s\n", (ntevs > 1) ? "s:" : ":");
1090         for (i = 0; i < ntevs; i++) {
1091                 tev = &tevs[i];
1092                 if (pev->event)
1093                         event = pev->event;
1094                 else
1095                         if (pev->point.function)
1096                                 event = pev->point.function;
1097                         else
1098                                 event = tev->point.symbol;
1099                 if (pev->group)
1100                         group = pev->group;
1101                 else
1102                         group = PERFPROBE_GROUP;
1103
1104                 /* Get an unused new event name */
1105                 get_new_event_name(buf, 64, event, namelist, allow_suffix);
1106                 event = buf;
1107
1108                 tev->event = xstrdup(event);
1109                 tev->group = xstrdup(group);
1110                 write_kprobe_trace_event(fd, tev);
1111                 /* Add added event name to namelist */
1112                 strlist__add(namelist, event);
1113
1114                 /* Trick here - save current event/group */
1115                 event = pev->event;
1116                 group = pev->group;
1117                 pev->event = tev->event;
1118                 pev->group = tev->group;
1119                 show_perf_probe_event(pev);
1120                 /* Trick here - restore current event/group */
1121                 pev->event = (char *)event;
1122                 pev->group = (char *)group;
1123
1124                 /*
1125                  * Probes after the first probe which comes from same
1126                  * user input are always allowed to add suffix, because
1127                  * there might be several addresses corresponding to
1128                  * one code line.
1129                  */
1130                 allow_suffix = true;
1131         }
1132         /* Show how to use the event. */
1133         printf("\nYou can now use it on all perf tools, such as:\n\n");
1134         printf("\tperf record -e %s:%s -a sleep 1\n\n", tev->group, tev->event);
1135
1136         strlist__delete(namelist);
1137         close(fd);
1138 }
1139
1140 static int convert_to_kprobe_trace_events(struct perf_probe_event *pev,
1141                                           struct kprobe_trace_event **tevs)
1142 {
1143         struct symbol *sym;
1144         int ntevs = 0, i;
1145         struct kprobe_trace_event *tev;
1146
1147         /* Convert perf_probe_event with debuginfo */
1148         ntevs = try_to_find_kprobe_trace_events(pev, tevs);
1149         if (ntevs > 0)
1150                 return ntevs;
1151
1152         /* Allocate trace event buffer */
1153         ntevs = 1;
1154         tev = *tevs = xzalloc(sizeof(struct kprobe_trace_event));
1155
1156         /* Copy parameters */
1157         tev->point.symbol = xstrdup(pev->point.function);
1158         tev->point.offset = pev->point.offset;
1159         tev->nargs = pev->nargs;
1160         if (tev->nargs) {
1161                 tev->args = xzalloc(sizeof(struct kprobe_trace_arg)
1162                                     * tev->nargs);
1163                 for (i = 0; i < tev->nargs; i++) {
1164                         if (pev->args[i].name)
1165                                 tev->args[i].name = xstrdup(pev->args[i].name);
1166                         tev->args[i].value = xstrdup(pev->args[i].var);
1167                         if (pev->args[i].type)
1168                                 tev->args[i].type = xstrdup(pev->args[i].type);
1169                 }
1170         }
1171
1172         /* Currently just checking function name from symbol map */
1173         sym = map__find_symbol_by_name(kmaps[MAP__FUNCTION],
1174                                        tev->point.symbol, NULL);
1175         if (!sym)
1176                 die("Kernel symbol \'%s\' not found - probe not added.",
1177                     tev->point.symbol);
1178
1179         return ntevs;
1180 }
1181
1182 struct __event_package {
1183         struct perf_probe_event         *pev;
1184         struct kprobe_trace_event       *tevs;
1185         int                             ntevs;
1186 };
1187
1188 void add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
1189                            bool force_add)
1190 {
1191         int i;
1192         struct __event_package *pkgs;
1193
1194         pkgs = xzalloc(sizeof(struct __event_package) * npevs);
1195
1196         /* Init vmlinux path */
1197         init_vmlinux();
1198
1199         /* Loop 1: convert all events */
1200         for (i = 0; i < npevs; i++) {
1201                 pkgs[i].pev = &pevs[i];
1202                 /* Convert with or without debuginfo */
1203                 pkgs[i].ntevs = convert_to_kprobe_trace_events(pkgs[i].pev,
1204                                                                &pkgs[i].tevs);
1205         }
1206
1207         /* Loop 2: add all events */
1208         for (i = 0; i < npevs; i++)
1209                 __add_kprobe_trace_events(pkgs[i].pev, pkgs[i].tevs,
1210                                           pkgs[i].ntevs, force_add);
1211         /* TODO: cleanup all trace events? */
1212 }
1213
1214 static void __del_trace_kprobe_event(int fd, struct str_node *ent)
1215 {
1216         char *p;
1217         char buf[128];
1218         int ret;
1219
1220         /* Convert from perf-probe event to trace-kprobe event */
1221         if (e_snprintf(buf, 128, "-:%s", ent->s) < 0)
1222                 die("Failed to copy event.");
1223         p = strchr(buf + 2, ':');
1224         if (!p)
1225                 die("Internal error: %s should have ':' but not.", ent->s);
1226         *p = '/';
1227
1228         pr_debug("Writing event: %s\n", buf);
1229         ret = write(fd, buf, strlen(buf));
1230         if (ret <= 0)
1231                 die("Failed to write event: %s", strerror(errno));
1232         printf("Remove event: %s\n", ent->s);
1233 }
1234
1235 static void del_trace_kprobe_event(int fd, const char *group,
1236                                    const char *event, struct strlist *namelist)
1237 {
1238         char buf[128];
1239         struct str_node *ent, *n;
1240         int found = 0;
1241
1242         if (e_snprintf(buf, 128, "%s:%s", group, event) < 0)
1243                 die("Failed to copy event.");
1244
1245         if (strpbrk(buf, "*?")) { /* Glob-exp */
1246                 strlist__for_each_safe(ent, n, namelist)
1247                         if (strglobmatch(ent->s, buf)) {
1248                                 found++;
1249                                 __del_trace_kprobe_event(fd, ent);
1250                                 strlist__remove(namelist, ent);
1251                         }
1252         } else {
1253                 ent = strlist__find(namelist, buf);
1254                 if (ent) {
1255                         found++;
1256                         __del_trace_kprobe_event(fd, ent);
1257                         strlist__remove(namelist, ent);
1258                 }
1259         }
1260         if (found == 0)
1261                 pr_info("Info: event \"%s\" does not exist, could not remove it.\n", buf);
1262 }
1263
1264 void del_perf_probe_events(struct strlist *dellist)
1265 {
1266         int fd;
1267         const char *group, *event;
1268         char *p, *str;
1269         struct str_node *ent;
1270         struct strlist *namelist;
1271
1272         fd = open_kprobe_events(true);
1273         /* Get current event names */
1274         namelist = get_kprobe_trace_event_names(fd, true);
1275
1276         strlist__for_each(ent, dellist) {
1277                 str = xstrdup(ent->s);
1278                 pr_debug("Parsing: %s\n", str);
1279                 p = strchr(str, ':');
1280                 if (p) {
1281                         group = str;
1282                         *p = '\0';
1283                         event = p + 1;
1284                 } else {
1285                         group = "*";
1286                         event = str;
1287                 }
1288                 pr_debug("Group: %s, Event: %s\n", group, event);
1289                 del_trace_kprobe_event(fd, group, event, namelist);
1290                 free(str);
1291         }
1292         strlist__delete(namelist);
1293         close(fd);
1294 }
1295