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