]> asedeno.scripts.mit.edu Git - linux.git/blob - tools/perf/builtin-script.c
perf script: Add --insn-trace for instruction decoding
[linux.git] / tools / perf / builtin-script.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include "builtin.h"
3
4 #include "perf.h"
5 #include "util/cache.h"
6 #include "util/debug.h"
7 #include <subcmd/exec-cmd.h>
8 #include "util/header.h"
9 #include <subcmd/parse-options.h>
10 #include "util/perf_regs.h"
11 #include "util/session.h"
12 #include "util/tool.h"
13 #include "util/symbol.h"
14 #include "util/thread.h"
15 #include "util/trace-event.h"
16 #include "util/util.h"
17 #include "util/evlist.h"
18 #include "util/evsel.h"
19 #include "util/sort.h"
20 #include "util/data.h"
21 #include "util/auxtrace.h"
22 #include "util/cpumap.h"
23 #include "util/thread_map.h"
24 #include "util/stat.h"
25 #include "util/color.h"
26 #include "util/string2.h"
27 #include "util/thread-stack.h"
28 #include "util/time-utils.h"
29 #include "util/path.h"
30 #include "print_binary.h"
31 #include <linux/bitmap.h>
32 #include <linux/kernel.h>
33 #include <linux/stringify.h>
34 #include <linux/time64.h>
35 #include "asm/bug.h"
36 #include "util/mem-events.h"
37 #include "util/dump-insn.h"
38 #include <dirent.h>
39 #include <errno.h>
40 #include <inttypes.h>
41 #include <signal.h>
42 #include <sys/param.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <fcntl.h>
46 #include <unistd.h>
47 #include <subcmd/pager.h>
48
49 #include "sane_ctype.h"
50
51 static char const               *script_name;
52 static char const               *generate_script_lang;
53 static bool                     debug_mode;
54 static u64                      last_timestamp;
55 static u64                      nr_unordered;
56 static bool                     no_callchain;
57 static bool                     latency_format;
58 static bool                     system_wide;
59 static bool                     print_flags;
60 static bool                     nanosecs;
61 static const char               *cpu_list;
62 static DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
63 static struct perf_stat_config  stat_config;
64 static int                      max_blocks;
65
66 unsigned int scripting_max_stack = PERF_MAX_STACK_DEPTH;
67
68 enum perf_output_field {
69         PERF_OUTPUT_COMM            = 1U << 0,
70         PERF_OUTPUT_TID             = 1U << 1,
71         PERF_OUTPUT_PID             = 1U << 2,
72         PERF_OUTPUT_TIME            = 1U << 3,
73         PERF_OUTPUT_CPU             = 1U << 4,
74         PERF_OUTPUT_EVNAME          = 1U << 5,
75         PERF_OUTPUT_TRACE           = 1U << 6,
76         PERF_OUTPUT_IP              = 1U << 7,
77         PERF_OUTPUT_SYM             = 1U << 8,
78         PERF_OUTPUT_DSO             = 1U << 9,
79         PERF_OUTPUT_ADDR            = 1U << 10,
80         PERF_OUTPUT_SYMOFFSET       = 1U << 11,
81         PERF_OUTPUT_SRCLINE         = 1U << 12,
82         PERF_OUTPUT_PERIOD          = 1U << 13,
83         PERF_OUTPUT_IREGS           = 1U << 14,
84         PERF_OUTPUT_BRSTACK         = 1U << 15,
85         PERF_OUTPUT_BRSTACKSYM      = 1U << 16,
86         PERF_OUTPUT_DATA_SRC        = 1U << 17,
87         PERF_OUTPUT_WEIGHT          = 1U << 18,
88         PERF_OUTPUT_BPF_OUTPUT      = 1U << 19,
89         PERF_OUTPUT_CALLINDENT      = 1U << 20,
90         PERF_OUTPUT_INSN            = 1U << 21,
91         PERF_OUTPUT_INSNLEN         = 1U << 22,
92         PERF_OUTPUT_BRSTACKINSN     = 1U << 23,
93         PERF_OUTPUT_BRSTACKOFF      = 1U << 24,
94         PERF_OUTPUT_SYNTH           = 1U << 25,
95         PERF_OUTPUT_PHYS_ADDR       = 1U << 26,
96         PERF_OUTPUT_UREGS           = 1U << 27,
97         PERF_OUTPUT_METRIC          = 1U << 28,
98         PERF_OUTPUT_MISC            = 1U << 29,
99 };
100
101 struct output_option {
102         const char *str;
103         enum perf_output_field field;
104 } all_output_options[] = {
105         {.str = "comm",  .field = PERF_OUTPUT_COMM},
106         {.str = "tid",   .field = PERF_OUTPUT_TID},
107         {.str = "pid",   .field = PERF_OUTPUT_PID},
108         {.str = "time",  .field = PERF_OUTPUT_TIME},
109         {.str = "cpu",   .field = PERF_OUTPUT_CPU},
110         {.str = "event", .field = PERF_OUTPUT_EVNAME},
111         {.str = "trace", .field = PERF_OUTPUT_TRACE},
112         {.str = "ip",    .field = PERF_OUTPUT_IP},
113         {.str = "sym",   .field = PERF_OUTPUT_SYM},
114         {.str = "dso",   .field = PERF_OUTPUT_DSO},
115         {.str = "addr",  .field = PERF_OUTPUT_ADDR},
116         {.str = "symoff", .field = PERF_OUTPUT_SYMOFFSET},
117         {.str = "srcline", .field = PERF_OUTPUT_SRCLINE},
118         {.str = "period", .field = PERF_OUTPUT_PERIOD},
119         {.str = "iregs", .field = PERF_OUTPUT_IREGS},
120         {.str = "uregs", .field = PERF_OUTPUT_UREGS},
121         {.str = "brstack", .field = PERF_OUTPUT_BRSTACK},
122         {.str = "brstacksym", .field = PERF_OUTPUT_BRSTACKSYM},
123         {.str = "data_src", .field = PERF_OUTPUT_DATA_SRC},
124         {.str = "weight",   .field = PERF_OUTPUT_WEIGHT},
125         {.str = "bpf-output",   .field = PERF_OUTPUT_BPF_OUTPUT},
126         {.str = "callindent", .field = PERF_OUTPUT_CALLINDENT},
127         {.str = "insn", .field = PERF_OUTPUT_INSN},
128         {.str = "insnlen", .field = PERF_OUTPUT_INSNLEN},
129         {.str = "brstackinsn", .field = PERF_OUTPUT_BRSTACKINSN},
130         {.str = "brstackoff", .field = PERF_OUTPUT_BRSTACKOFF},
131         {.str = "synth", .field = PERF_OUTPUT_SYNTH},
132         {.str = "phys_addr", .field = PERF_OUTPUT_PHYS_ADDR},
133         {.str = "metric", .field = PERF_OUTPUT_METRIC},
134         {.str = "misc", .field = PERF_OUTPUT_MISC},
135 };
136
137 enum {
138         OUTPUT_TYPE_SYNTH = PERF_TYPE_MAX,
139         OUTPUT_TYPE_MAX
140 };
141
142 /* default set to maintain compatibility with current format */
143 static struct {
144         bool user_set;
145         bool wildcard_set;
146         unsigned int print_ip_opts;
147         u64 fields;
148         u64 invalid_fields;
149 } output[OUTPUT_TYPE_MAX] = {
150
151         [PERF_TYPE_HARDWARE] = {
152                 .user_set = false,
153
154                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
155                               PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
156                               PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
157                               PERF_OUTPUT_SYM | PERF_OUTPUT_SYMOFFSET |
158                               PERF_OUTPUT_DSO | PERF_OUTPUT_PERIOD,
159
160                 .invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
161         },
162
163         [PERF_TYPE_SOFTWARE] = {
164                 .user_set = false,
165
166                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
167                               PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
168                               PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
169                               PERF_OUTPUT_SYM | PERF_OUTPUT_SYMOFFSET |
170                               PERF_OUTPUT_DSO | PERF_OUTPUT_PERIOD |
171                               PERF_OUTPUT_BPF_OUTPUT,
172
173                 .invalid_fields = PERF_OUTPUT_TRACE,
174         },
175
176         [PERF_TYPE_TRACEPOINT] = {
177                 .user_set = false,
178
179                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
180                                   PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
181                                   PERF_OUTPUT_EVNAME | PERF_OUTPUT_TRACE
182         },
183
184         [PERF_TYPE_HW_CACHE] = {
185                 .user_set = false,
186
187                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
188                               PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
189                               PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
190                               PERF_OUTPUT_SYM | PERF_OUTPUT_SYMOFFSET |
191                               PERF_OUTPUT_DSO | PERF_OUTPUT_PERIOD,
192
193                 .invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
194         },
195
196         [PERF_TYPE_RAW] = {
197                 .user_set = false,
198
199                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
200                               PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
201                               PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
202                               PERF_OUTPUT_SYM | PERF_OUTPUT_SYMOFFSET |
203                               PERF_OUTPUT_DSO | PERF_OUTPUT_PERIOD |
204                               PERF_OUTPUT_ADDR | PERF_OUTPUT_DATA_SRC |
205                               PERF_OUTPUT_WEIGHT | PERF_OUTPUT_PHYS_ADDR,
206
207                 .invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
208         },
209
210         [PERF_TYPE_BREAKPOINT] = {
211                 .user_set = false,
212
213                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
214                               PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
215                               PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
216                               PERF_OUTPUT_SYM | PERF_OUTPUT_SYMOFFSET |
217                               PERF_OUTPUT_DSO | PERF_OUTPUT_PERIOD,
218
219                 .invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
220         },
221
222         [OUTPUT_TYPE_SYNTH] = {
223                 .user_set = false,
224
225                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
226                               PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
227                               PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
228                               PERF_OUTPUT_SYM | PERF_OUTPUT_SYMOFFSET |
229                               PERF_OUTPUT_DSO | PERF_OUTPUT_SYNTH,
230
231                 .invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
232         },
233 };
234
235 struct perf_evsel_script {
236        char *filename;
237        FILE *fp;
238        u64  samples;
239        /* For metric output */
240        u64  val;
241        int  gnum;
242 };
243
244 static inline struct perf_evsel_script *evsel_script(struct perf_evsel *evsel)
245 {
246         return (struct perf_evsel_script *)evsel->priv;
247 }
248
249 static struct perf_evsel_script *perf_evsel_script__new(struct perf_evsel *evsel,
250                                                         struct perf_data *data)
251 {
252         struct perf_evsel_script *es = zalloc(sizeof(*es));
253
254         if (es != NULL) {
255                 if (asprintf(&es->filename, "%s.%s.dump", data->file.path, perf_evsel__name(evsel)) < 0)
256                         goto out_free;
257                 es->fp = fopen(es->filename, "w");
258                 if (es->fp == NULL)
259                         goto out_free_filename;
260         }
261
262         return es;
263 out_free_filename:
264         zfree(&es->filename);
265 out_free:
266         free(es);
267         return NULL;
268 }
269
270 static void perf_evsel_script__delete(struct perf_evsel_script *es)
271 {
272         zfree(&es->filename);
273         fclose(es->fp);
274         es->fp = NULL;
275         free(es);
276 }
277
278 static int perf_evsel_script__fprintf(struct perf_evsel_script *es, FILE *fp)
279 {
280         struct stat st;
281
282         fstat(fileno(es->fp), &st);
283         return fprintf(fp, "[ perf script: Wrote %.3f MB %s (%" PRIu64 " samples) ]\n",
284                        st.st_size / 1024.0 / 1024.0, es->filename, es->samples);
285 }
286
287 static inline int output_type(unsigned int type)
288 {
289         switch (type) {
290         case PERF_TYPE_SYNTH:
291                 return OUTPUT_TYPE_SYNTH;
292         default:
293                 return type;
294         }
295 }
296
297 static inline unsigned int attr_type(unsigned int type)
298 {
299         switch (type) {
300         case OUTPUT_TYPE_SYNTH:
301                 return PERF_TYPE_SYNTH;
302         default:
303                 return type;
304         }
305 }
306
307 static bool output_set_by_user(void)
308 {
309         int j;
310         for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
311                 if (output[j].user_set)
312                         return true;
313         }
314         return false;
315 }
316
317 static const char *output_field2str(enum perf_output_field field)
318 {
319         int i, imax = ARRAY_SIZE(all_output_options);
320         const char *str = "";
321
322         for (i = 0; i < imax; ++i) {
323                 if (all_output_options[i].field == field) {
324                         str = all_output_options[i].str;
325                         break;
326                 }
327         }
328         return str;
329 }
330
331 #define PRINT_FIELD(x)  (output[output_type(attr->type)].fields & PERF_OUTPUT_##x)
332
333 static int perf_evsel__do_check_stype(struct perf_evsel *evsel,
334                                       u64 sample_type, const char *sample_msg,
335                                       enum perf_output_field field,
336                                       bool allow_user_set)
337 {
338         struct perf_event_attr *attr = &evsel->attr;
339         int type = output_type(attr->type);
340         const char *evname;
341
342         if (attr->sample_type & sample_type)
343                 return 0;
344
345         if (output[type].user_set) {
346                 if (allow_user_set)
347                         return 0;
348                 evname = perf_evsel__name(evsel);
349                 pr_err("Samples for '%s' event do not have %s attribute set. "
350                        "Cannot print '%s' field.\n",
351                        evname, sample_msg, output_field2str(field));
352                 return -1;
353         }
354
355         /* user did not ask for it explicitly so remove from the default list */
356         output[type].fields &= ~field;
357         evname = perf_evsel__name(evsel);
358         pr_debug("Samples for '%s' event do not have %s attribute set. "
359                  "Skipping '%s' field.\n",
360                  evname, sample_msg, output_field2str(field));
361
362         return 0;
363 }
364
365 static int perf_evsel__check_stype(struct perf_evsel *evsel,
366                                    u64 sample_type, const char *sample_msg,
367                                    enum perf_output_field field)
368 {
369         return perf_evsel__do_check_stype(evsel, sample_type, sample_msg, field,
370                                           false);
371 }
372
373 static int perf_evsel__check_attr(struct perf_evsel *evsel,
374                                   struct perf_session *session)
375 {
376         struct perf_event_attr *attr = &evsel->attr;
377         bool allow_user_set;
378
379         if (perf_header__has_feat(&session->header, HEADER_STAT))
380                 return 0;
381
382         allow_user_set = perf_header__has_feat(&session->header,
383                                                HEADER_AUXTRACE);
384
385         if (PRINT_FIELD(TRACE) &&
386                 !perf_session__has_traces(session, "record -R"))
387                 return -EINVAL;
388
389         if (PRINT_FIELD(IP)) {
390                 if (perf_evsel__check_stype(evsel, PERF_SAMPLE_IP, "IP",
391                                             PERF_OUTPUT_IP))
392                         return -EINVAL;
393         }
394
395         if (PRINT_FIELD(ADDR) &&
396                 perf_evsel__do_check_stype(evsel, PERF_SAMPLE_ADDR, "ADDR",
397                                            PERF_OUTPUT_ADDR, allow_user_set))
398                 return -EINVAL;
399
400         if (PRINT_FIELD(DATA_SRC) &&
401                 perf_evsel__check_stype(evsel, PERF_SAMPLE_DATA_SRC, "DATA_SRC",
402                                         PERF_OUTPUT_DATA_SRC))
403                 return -EINVAL;
404
405         if (PRINT_FIELD(WEIGHT) &&
406                 perf_evsel__check_stype(evsel, PERF_SAMPLE_WEIGHT, "WEIGHT",
407                                         PERF_OUTPUT_WEIGHT))
408                 return -EINVAL;
409
410         if (PRINT_FIELD(SYM) &&
411                 !(evsel->attr.sample_type & (PERF_SAMPLE_IP|PERF_SAMPLE_ADDR))) {
412                 pr_err("Display of symbols requested but neither sample IP nor "
413                            "sample address\navailable. Hence, no addresses to convert "
414                        "to symbols.\n");
415                 return -EINVAL;
416         }
417         if (PRINT_FIELD(SYMOFFSET) && !PRINT_FIELD(SYM)) {
418                 pr_err("Display of offsets requested but symbol is not"
419                        "selected.\n");
420                 return -EINVAL;
421         }
422         if (PRINT_FIELD(DSO) &&
423                 !(evsel->attr.sample_type & (PERF_SAMPLE_IP|PERF_SAMPLE_ADDR))) {
424                 pr_err("Display of DSO requested but no address to convert.\n");
425                 return -EINVAL;
426         }
427         if (PRINT_FIELD(SRCLINE) && !PRINT_FIELD(IP)) {
428                 pr_err("Display of source line number requested but sample IP is not\n"
429                        "selected. Hence, no address to lookup the source line number.\n");
430                 return -EINVAL;
431         }
432         if (PRINT_FIELD(BRSTACKINSN) &&
433             !(perf_evlist__combined_branch_type(session->evlist) &
434               PERF_SAMPLE_BRANCH_ANY)) {
435                 pr_err("Display of branch stack assembler requested, but non all-branch filter set\n"
436                        "Hint: run 'perf record -b ...'\n");
437                 return -EINVAL;
438         }
439         if ((PRINT_FIELD(PID) || PRINT_FIELD(TID)) &&
440                 perf_evsel__check_stype(evsel, PERF_SAMPLE_TID, "TID",
441                                         PERF_OUTPUT_TID|PERF_OUTPUT_PID))
442                 return -EINVAL;
443
444         if (PRINT_FIELD(TIME) &&
445                 perf_evsel__check_stype(evsel, PERF_SAMPLE_TIME, "TIME",
446                                         PERF_OUTPUT_TIME))
447                 return -EINVAL;
448
449         if (PRINT_FIELD(CPU) &&
450                 perf_evsel__do_check_stype(evsel, PERF_SAMPLE_CPU, "CPU",
451                                            PERF_OUTPUT_CPU, allow_user_set))
452                 return -EINVAL;
453
454         if (PRINT_FIELD(IREGS) &&
455                 perf_evsel__check_stype(evsel, PERF_SAMPLE_REGS_INTR, "IREGS",
456                                         PERF_OUTPUT_IREGS))
457                 return -EINVAL;
458
459         if (PRINT_FIELD(UREGS) &&
460                 perf_evsel__check_stype(evsel, PERF_SAMPLE_REGS_USER, "UREGS",
461                                         PERF_OUTPUT_UREGS))
462                 return -EINVAL;
463
464         if (PRINT_FIELD(PHYS_ADDR) &&
465                 perf_evsel__check_stype(evsel, PERF_SAMPLE_PHYS_ADDR, "PHYS_ADDR",
466                                         PERF_OUTPUT_PHYS_ADDR))
467                 return -EINVAL;
468
469         return 0;
470 }
471
472 static void set_print_ip_opts(struct perf_event_attr *attr)
473 {
474         unsigned int type = output_type(attr->type);
475
476         output[type].print_ip_opts = 0;
477         if (PRINT_FIELD(IP))
478                 output[type].print_ip_opts |= EVSEL__PRINT_IP;
479
480         if (PRINT_FIELD(SYM))
481                 output[type].print_ip_opts |= EVSEL__PRINT_SYM;
482
483         if (PRINT_FIELD(DSO))
484                 output[type].print_ip_opts |= EVSEL__PRINT_DSO;
485
486         if (PRINT_FIELD(SYMOFFSET))
487                 output[type].print_ip_opts |= EVSEL__PRINT_SYMOFFSET;
488
489         if (PRINT_FIELD(SRCLINE))
490                 output[type].print_ip_opts |= EVSEL__PRINT_SRCLINE;
491 }
492
493 /*
494  * verify all user requested events exist and the samples
495  * have the expected data
496  */
497 static int perf_session__check_output_opt(struct perf_session *session)
498 {
499         unsigned int j;
500         struct perf_evsel *evsel;
501
502         for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
503                 evsel = perf_session__find_first_evtype(session, attr_type(j));
504
505                 /*
506                  * even if fields is set to 0 (ie., show nothing) event must
507                  * exist if user explicitly includes it on the command line
508                  */
509                 if (!evsel && output[j].user_set && !output[j].wildcard_set &&
510                     j != OUTPUT_TYPE_SYNTH) {
511                         pr_err("%s events do not exist. "
512                                "Remove corresponding -F option to proceed.\n",
513                                event_type(j));
514                         return -1;
515                 }
516
517                 if (evsel && output[j].fields &&
518                         perf_evsel__check_attr(evsel, session))
519                         return -1;
520
521                 if (evsel == NULL)
522                         continue;
523
524                 set_print_ip_opts(&evsel->attr);
525         }
526
527         if (!no_callchain) {
528                 bool use_callchain = false;
529                 bool not_pipe = false;
530
531                 evlist__for_each_entry(session->evlist, evsel) {
532                         not_pipe = true;
533                         if (evsel__has_callchain(evsel)) {
534                                 use_callchain = true;
535                                 break;
536                         }
537                 }
538                 if (not_pipe && !use_callchain)
539                         symbol_conf.use_callchain = false;
540         }
541
542         /*
543          * set default for tracepoints to print symbols only
544          * if callchains are present
545          */
546         if (symbol_conf.use_callchain &&
547             !output[PERF_TYPE_TRACEPOINT].user_set) {
548                 j = PERF_TYPE_TRACEPOINT;
549
550                 evlist__for_each_entry(session->evlist, evsel) {
551                         if (evsel->attr.type != j)
552                                 continue;
553
554                         if (evsel__has_callchain(evsel)) {
555                                 output[j].fields |= PERF_OUTPUT_IP;
556                                 output[j].fields |= PERF_OUTPUT_SYM;
557                                 output[j].fields |= PERF_OUTPUT_SYMOFFSET;
558                                 output[j].fields |= PERF_OUTPUT_DSO;
559                                 set_print_ip_opts(&evsel->attr);
560                                 goto out;
561                         }
562                 }
563         }
564
565 out:
566         return 0;
567 }
568
569 static int perf_sample__fprintf_iregs(struct perf_sample *sample,
570                                       struct perf_event_attr *attr, FILE *fp)
571 {
572         struct regs_dump *regs = &sample->intr_regs;
573         uint64_t mask = attr->sample_regs_intr;
574         unsigned i = 0, r;
575         int printed = 0;
576
577         if (!regs)
578                 return 0;
579
580         for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
581                 u64 val = regs->regs[i++];
582                 printed += fprintf(fp, "%5s:0x%"PRIx64" ", perf_reg_name(r), val);
583         }
584
585         return printed;
586 }
587
588 static int perf_sample__fprintf_uregs(struct perf_sample *sample,
589                                       struct perf_event_attr *attr, FILE *fp)
590 {
591         struct regs_dump *regs = &sample->user_regs;
592         uint64_t mask = attr->sample_regs_user;
593         unsigned i = 0, r;
594         int printed = 0;
595
596         if (!regs || !regs->regs)
597                 return 0;
598
599         printed += fprintf(fp, " ABI:%" PRIu64 " ", regs->abi);
600
601         for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
602                 u64 val = regs->regs[i++];
603                 printed += fprintf(fp, "%5s:0x%"PRIx64" ", perf_reg_name(r), val);
604         }
605
606         return printed;
607 }
608
609 static int perf_sample__fprintf_start(struct perf_sample *sample,
610                                       struct thread *thread,
611                                       struct perf_evsel *evsel,
612                                       u32 type, FILE *fp)
613 {
614         struct perf_event_attr *attr = &evsel->attr;
615         unsigned long secs;
616         unsigned long long nsecs;
617         int printed = 0;
618
619         if (PRINT_FIELD(COMM)) {
620                 if (latency_format)
621                         printed += fprintf(fp, "%8.8s ", thread__comm_str(thread));
622                 else if (PRINT_FIELD(IP) && evsel__has_callchain(evsel) && symbol_conf.use_callchain)
623                         printed += fprintf(fp, "%s ", thread__comm_str(thread));
624                 else
625                         printed += fprintf(fp, "%16s ", thread__comm_str(thread));
626         }
627
628         if (PRINT_FIELD(PID) && PRINT_FIELD(TID))
629                 printed += fprintf(fp, "%5d/%-5d ", sample->pid, sample->tid);
630         else if (PRINT_FIELD(PID))
631                 printed += fprintf(fp, "%5d ", sample->pid);
632         else if (PRINT_FIELD(TID))
633                 printed += fprintf(fp, "%5d ", sample->tid);
634
635         if (PRINT_FIELD(CPU)) {
636                 if (latency_format)
637                         printed += fprintf(fp, "%3d ", sample->cpu);
638                 else
639                         printed += fprintf(fp, "[%03d] ", sample->cpu);
640         }
641
642         if (PRINT_FIELD(MISC)) {
643                 int ret = 0;
644
645                 #define has(m) \
646                         (sample->misc & PERF_RECORD_MISC_##m) == PERF_RECORD_MISC_##m
647
648                 if (has(KERNEL))
649                         ret += fprintf(fp, "K");
650                 if (has(USER))
651                         ret += fprintf(fp, "U");
652                 if (has(HYPERVISOR))
653                         ret += fprintf(fp, "H");
654                 if (has(GUEST_KERNEL))
655                         ret += fprintf(fp, "G");
656                 if (has(GUEST_USER))
657                         ret += fprintf(fp, "g");
658
659                 switch (type) {
660                 case PERF_RECORD_MMAP:
661                 case PERF_RECORD_MMAP2:
662                         if (has(MMAP_DATA))
663                                 ret += fprintf(fp, "M");
664                         break;
665                 case PERF_RECORD_COMM:
666                         if (has(COMM_EXEC))
667                                 ret += fprintf(fp, "E");
668                         break;
669                 case PERF_RECORD_SWITCH:
670                 case PERF_RECORD_SWITCH_CPU_WIDE:
671                         if (has(SWITCH_OUT)) {
672                                 ret += fprintf(fp, "S");
673                                 if (sample->misc & PERF_RECORD_MISC_SWITCH_OUT_PREEMPT)
674                                         ret += fprintf(fp, "p");
675                         }
676                 default:
677                         break;
678                 }
679
680                 #undef has
681
682                 ret += fprintf(fp, "%*s", 6 - ret, " ");
683                 printed += ret;
684         }
685
686         if (PRINT_FIELD(TIME)) {
687                 nsecs = sample->time;
688                 secs = nsecs / NSEC_PER_SEC;
689                 nsecs -= secs * NSEC_PER_SEC;
690
691                 if (nanosecs)
692                         printed += fprintf(fp, "%5lu.%09llu: ", secs, nsecs);
693                 else {
694                         char sample_time[32];
695                         timestamp__scnprintf_usec(sample->time, sample_time, sizeof(sample_time));
696                         printed += fprintf(fp, "%12s: ", sample_time);
697                 }
698         }
699
700         return printed;
701 }
702
703 static inline char
704 mispred_str(struct branch_entry *br)
705 {
706         if (!(br->flags.mispred  || br->flags.predicted))
707                 return '-';
708
709         return br->flags.predicted ? 'P' : 'M';
710 }
711
712 static int perf_sample__fprintf_brstack(struct perf_sample *sample,
713                                         struct thread *thread,
714                                         struct perf_event_attr *attr, FILE *fp)
715 {
716         struct branch_stack *br = sample->branch_stack;
717         struct addr_location alf, alt;
718         u64 i, from, to;
719         int printed = 0;
720
721         if (!(br && br->nr))
722                 return 0;
723
724         for (i = 0; i < br->nr; i++) {
725                 from = br->entries[i].from;
726                 to   = br->entries[i].to;
727
728                 if (PRINT_FIELD(DSO)) {
729                         memset(&alf, 0, sizeof(alf));
730                         memset(&alt, 0, sizeof(alt));
731                         thread__find_map(thread, sample->cpumode, from, &alf);
732                         thread__find_map(thread, sample->cpumode, to, &alt);
733                 }
734
735                 printed += fprintf(fp, " 0x%"PRIx64, from);
736                 if (PRINT_FIELD(DSO)) {
737                         printed += fprintf(fp, "(");
738                         printed += map__fprintf_dsoname(alf.map, fp);
739                         printed += fprintf(fp, ")");
740                 }
741
742                 printed += fprintf(fp, "/0x%"PRIx64, to);
743                 if (PRINT_FIELD(DSO)) {
744                         printed += fprintf(fp, "(");
745                         printed += map__fprintf_dsoname(alt.map, fp);
746                         printed += fprintf(fp, ")");
747                 }
748
749                 printed += fprintf(fp, "/%c/%c/%c/%d ",
750                         mispred_str( br->entries + i),
751                         br->entries[i].flags.in_tx? 'X' : '-',
752                         br->entries[i].flags.abort? 'A' : '-',
753                         br->entries[i].flags.cycles);
754         }
755
756         return printed;
757 }
758
759 static int perf_sample__fprintf_brstacksym(struct perf_sample *sample,
760                                            struct thread *thread,
761                                            struct perf_event_attr *attr, FILE *fp)
762 {
763         struct branch_stack *br = sample->branch_stack;
764         struct addr_location alf, alt;
765         u64 i, from, to;
766         int printed = 0;
767
768         if (!(br && br->nr))
769                 return 0;
770
771         for (i = 0; i < br->nr; i++) {
772
773                 memset(&alf, 0, sizeof(alf));
774                 memset(&alt, 0, sizeof(alt));
775                 from = br->entries[i].from;
776                 to   = br->entries[i].to;
777
778                 thread__find_symbol(thread, sample->cpumode, from, &alf);
779                 thread__find_symbol(thread, sample->cpumode, to, &alt);
780
781                 printed += symbol__fprintf_symname_offs(alf.sym, &alf, fp);
782                 if (PRINT_FIELD(DSO)) {
783                         printed += fprintf(fp, "(");
784                         printed += map__fprintf_dsoname(alf.map, fp);
785                         printed += fprintf(fp, ")");
786                 }
787                 printed += fprintf(fp, "%c", '/');
788                 printed += symbol__fprintf_symname_offs(alt.sym, &alt, fp);
789                 if (PRINT_FIELD(DSO)) {
790                         printed += fprintf(fp, "(");
791                         printed += map__fprintf_dsoname(alt.map, fp);
792                         printed += fprintf(fp, ")");
793                 }
794                 printed += fprintf(fp, "/%c/%c/%c/%d ",
795                         mispred_str( br->entries + i),
796                         br->entries[i].flags.in_tx? 'X' : '-',
797                         br->entries[i].flags.abort? 'A' : '-',
798                         br->entries[i].flags.cycles);
799         }
800
801         return printed;
802 }
803
804 static int perf_sample__fprintf_brstackoff(struct perf_sample *sample,
805                                            struct thread *thread,
806                                            struct perf_event_attr *attr, FILE *fp)
807 {
808         struct branch_stack *br = sample->branch_stack;
809         struct addr_location alf, alt;
810         u64 i, from, to;
811         int printed = 0;
812
813         if (!(br && br->nr))
814                 return 0;
815
816         for (i = 0; i < br->nr; i++) {
817
818                 memset(&alf, 0, sizeof(alf));
819                 memset(&alt, 0, sizeof(alt));
820                 from = br->entries[i].from;
821                 to   = br->entries[i].to;
822
823                 if (thread__find_map(thread, sample->cpumode, from, &alf) &&
824                     !alf.map->dso->adjust_symbols)
825                         from = map__map_ip(alf.map, from);
826
827                 if (thread__find_map(thread, sample->cpumode, to, &alt) &&
828                     !alt.map->dso->adjust_symbols)
829                         to = map__map_ip(alt.map, to);
830
831                 printed += fprintf(fp, " 0x%"PRIx64, from);
832                 if (PRINT_FIELD(DSO)) {
833                         printed += fprintf(fp, "(");
834                         printed += map__fprintf_dsoname(alf.map, fp);
835                         printed += fprintf(fp, ")");
836                 }
837                 printed += fprintf(fp, "/0x%"PRIx64, to);
838                 if (PRINT_FIELD(DSO)) {
839                         printed += fprintf(fp, "(");
840                         printed += map__fprintf_dsoname(alt.map, fp);
841                         printed += fprintf(fp, ")");
842                 }
843                 printed += fprintf(fp, "/%c/%c/%c/%d ",
844                         mispred_str(br->entries + i),
845                         br->entries[i].flags.in_tx ? 'X' : '-',
846                         br->entries[i].flags.abort ? 'A' : '-',
847                         br->entries[i].flags.cycles);
848         }
849
850         return printed;
851 }
852 #define MAXBB 16384UL
853
854 static int grab_bb(u8 *buffer, u64 start, u64 end,
855                     struct machine *machine, struct thread *thread,
856                     bool *is64bit, u8 *cpumode, bool last)
857 {
858         long offset, len;
859         struct addr_location al;
860         bool kernel;
861
862         if (!start || !end)
863                 return 0;
864
865         kernel = machine__kernel_ip(machine, start);
866         if (kernel)
867                 *cpumode = PERF_RECORD_MISC_KERNEL;
868         else
869                 *cpumode = PERF_RECORD_MISC_USER;
870
871         /*
872          * Block overlaps between kernel and user.
873          * This can happen due to ring filtering
874          * On Intel CPUs the entry into the kernel is filtered,
875          * but the exit is not. Let the caller patch it up.
876          */
877         if (kernel != machine__kernel_ip(machine, end)) {
878                 pr_debug("\tblock %" PRIx64 "-%" PRIx64 " transfers between kernel and user\n", start, end);
879                 return -ENXIO;
880         }
881
882         memset(&al, 0, sizeof(al));
883         if (end - start > MAXBB - MAXINSN) {
884                 if (last)
885                         pr_debug("\tbrstack does not reach to final jump (%" PRIx64 "-%" PRIx64 ")\n", start, end);
886                 else
887                         pr_debug("\tblock %" PRIx64 "-%" PRIx64 " (%" PRIu64 ") too long to dump\n", start, end, end - start);
888                 return 0;
889         }
890
891         if (!thread__find_map(thread, *cpumode, start, &al) || !al.map->dso) {
892                 pr_debug("\tcannot resolve %" PRIx64 "-%" PRIx64 "\n", start, end);
893                 return 0;
894         }
895         if (al.map->dso->data.status == DSO_DATA_STATUS_ERROR) {
896                 pr_debug("\tcannot resolve %" PRIx64 "-%" PRIx64 "\n", start, end);
897                 return 0;
898         }
899
900         /* Load maps to ensure dso->is_64_bit has been updated */
901         map__load(al.map);
902
903         offset = al.map->map_ip(al.map, start);
904         len = dso__data_read_offset(al.map->dso, machine, offset, (u8 *)buffer,
905                                     end - start + MAXINSN);
906
907         *is64bit = al.map->dso->is_64_bit;
908         if (len <= 0)
909                 pr_debug("\tcannot fetch code for block at %" PRIx64 "-%" PRIx64 "\n",
910                         start, end);
911         return len;
912 }
913
914 static int ip__fprintf_jump(uint64_t ip, struct branch_entry *en,
915                             struct perf_insn *x, u8 *inbuf, int len,
916                             int insn, FILE *fp)
917 {
918         int printed = fprintf(fp, "\t%016" PRIx64 "\t%-30s\t#%s%s%s%s", ip,
919                               dump_insn(x, ip, inbuf, len, NULL),
920                               en->flags.predicted ? " PRED" : "",
921                               en->flags.mispred ? " MISPRED" : "",
922                               en->flags.in_tx ? " INTX" : "",
923                               en->flags.abort ? " ABORT" : "");
924         if (en->flags.cycles) {
925                 printed += fprintf(fp, " %d cycles", en->flags.cycles);
926                 if (insn)
927                         printed += fprintf(fp, " %.2f IPC", (float)insn / en->flags.cycles);
928         }
929         return printed + fprintf(fp, "\n");
930 }
931
932 static int ip__fprintf_sym(uint64_t addr, struct thread *thread,
933                            u8 cpumode, int cpu, struct symbol **lastsym,
934                            struct perf_event_attr *attr, FILE *fp)
935 {
936         struct addr_location al;
937         int off, printed = 0;
938
939         memset(&al, 0, sizeof(al));
940
941         thread__find_map(thread, cpumode, addr, &al);
942
943         if ((*lastsym) && al.addr >= (*lastsym)->start && al.addr < (*lastsym)->end)
944                 return 0;
945
946         al.cpu = cpu;
947         al.sym = NULL;
948         if (al.map)
949                 al.sym = map__find_symbol(al.map, al.addr);
950
951         if (!al.sym)
952                 return 0;
953
954         if (al.addr < al.sym->end)
955                 off = al.addr - al.sym->start;
956         else
957                 off = al.addr - al.map->start - al.sym->start;
958         printed += fprintf(fp, "\t%s", al.sym->name);
959         if (off)
960                 printed += fprintf(fp, "%+d", off);
961         printed += fprintf(fp, ":");
962         if (PRINT_FIELD(SRCLINE))
963                 printed += map__fprintf_srcline(al.map, al.addr, "\t", fp);
964         printed += fprintf(fp, "\n");
965         *lastsym = al.sym;
966
967         return printed;
968 }
969
970 static int perf_sample__fprintf_brstackinsn(struct perf_sample *sample,
971                                             struct thread *thread,
972                                             struct perf_event_attr *attr,
973                                             struct machine *machine, FILE *fp)
974 {
975         struct branch_stack *br = sample->branch_stack;
976         u64 start, end;
977         int i, insn, len, nr, ilen, printed = 0;
978         struct perf_insn x;
979         u8 buffer[MAXBB];
980         unsigned off;
981         struct symbol *lastsym = NULL;
982
983         if (!(br && br->nr))
984                 return 0;
985         nr = br->nr;
986         if (max_blocks && nr > max_blocks + 1)
987                 nr = max_blocks + 1;
988
989         x.thread = thread;
990         x.cpu = sample->cpu;
991
992         printed += fprintf(fp, "%c", '\n');
993
994         /* Handle first from jump, of which we don't know the entry. */
995         len = grab_bb(buffer, br->entries[nr-1].from,
996                         br->entries[nr-1].from,
997                         machine, thread, &x.is64bit, &x.cpumode, false);
998         if (len > 0) {
999                 printed += ip__fprintf_sym(br->entries[nr - 1].from, thread,
1000                                            x.cpumode, x.cpu, &lastsym, attr, fp);
1001                 printed += ip__fprintf_jump(br->entries[nr - 1].from, &br->entries[nr - 1],
1002                                             &x, buffer, len, 0, fp);
1003         }
1004
1005         /* Print all blocks */
1006         for (i = nr - 2; i >= 0; i--) {
1007                 if (br->entries[i].from || br->entries[i].to)
1008                         pr_debug("%d: %" PRIx64 "-%" PRIx64 "\n", i,
1009                                  br->entries[i].from,
1010                                  br->entries[i].to);
1011                 start = br->entries[i + 1].to;
1012                 end   = br->entries[i].from;
1013
1014                 len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, false);
1015                 /* Patch up missing kernel transfers due to ring filters */
1016                 if (len == -ENXIO && i > 0) {
1017                         end = br->entries[--i].from;
1018                         pr_debug("\tpatching up to %" PRIx64 "-%" PRIx64 "\n", start, end);
1019                         len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, false);
1020                 }
1021                 if (len <= 0)
1022                         continue;
1023
1024                 insn = 0;
1025                 for (off = 0;; off += ilen) {
1026                         uint64_t ip = start + off;
1027
1028                         printed += ip__fprintf_sym(ip, thread, x.cpumode, x.cpu, &lastsym, attr, fp);
1029                         if (ip == end) {
1030                                 printed += ip__fprintf_jump(ip, &br->entries[i], &x, buffer + off, len - off, insn, fp);
1031                                 break;
1032                         } else {
1033                                 printed += fprintf(fp, "\t%016" PRIx64 "\t%s\n", ip,
1034                                                    dump_insn(&x, ip, buffer + off, len - off, &ilen));
1035                                 if (ilen == 0)
1036                                         break;
1037                                 insn++;
1038                         }
1039                 }
1040         }
1041
1042         /*
1043          * Hit the branch? In this case we are already done, and the target
1044          * has not been executed yet.
1045          */
1046         if (br->entries[0].from == sample->ip)
1047                 goto out;
1048         if (br->entries[0].flags.abort)
1049                 goto out;
1050
1051         /*
1052          * Print final block upto sample
1053          */
1054         start = br->entries[0].to;
1055         end = sample->ip;
1056         len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, true);
1057         printed += ip__fprintf_sym(start, thread, x.cpumode, x.cpu, &lastsym, attr, fp);
1058         if (len <= 0) {
1059                 /* Print at least last IP if basic block did not work */
1060                 len = grab_bb(buffer, sample->ip, sample->ip,
1061                               machine, thread, &x.is64bit, &x.cpumode, false);
1062                 if (len <= 0)
1063                         goto out;
1064
1065                 printed += fprintf(fp, "\t%016" PRIx64 "\t%s\n", sample->ip,
1066                         dump_insn(&x, sample->ip, buffer, len, NULL));
1067                 goto out;
1068         }
1069         for (off = 0; off <= end - start; off += ilen) {
1070                 printed += fprintf(fp, "\t%016" PRIx64 "\t%s\n", start + off,
1071                                    dump_insn(&x, start + off, buffer + off, len - off, &ilen));
1072                 if (ilen == 0)
1073                         break;
1074         }
1075 out:
1076         return printed;
1077 }
1078
1079 static int perf_sample__fprintf_addr(struct perf_sample *sample,
1080                                      struct thread *thread,
1081                                      struct perf_event_attr *attr, FILE *fp)
1082 {
1083         struct addr_location al;
1084         int printed = fprintf(fp, "%16" PRIx64, sample->addr);
1085
1086         if (!sample_addr_correlates_sym(attr))
1087                 goto out;
1088
1089         thread__resolve(thread, &al, sample);
1090
1091         if (PRINT_FIELD(SYM)) {
1092                 printed += fprintf(fp, " ");
1093                 if (PRINT_FIELD(SYMOFFSET))
1094                         printed += symbol__fprintf_symname_offs(al.sym, &al, fp);
1095                 else
1096                         printed += symbol__fprintf_symname(al.sym, fp);
1097         }
1098
1099         if (PRINT_FIELD(DSO)) {
1100                 printed += fprintf(fp, " (");
1101                 printed += map__fprintf_dsoname(al.map, fp);
1102                 printed += fprintf(fp, ")");
1103         }
1104 out:
1105         return printed;
1106 }
1107
1108 static int perf_sample__fprintf_callindent(struct perf_sample *sample,
1109                                            struct perf_evsel *evsel,
1110                                            struct thread *thread,
1111                                            struct addr_location *al, FILE *fp)
1112 {
1113         struct perf_event_attr *attr = &evsel->attr;
1114         size_t depth = thread_stack__depth(thread);
1115         struct addr_location addr_al;
1116         const char *name = NULL;
1117         static int spacing;
1118         int len = 0;
1119         int dlen = 0;
1120         u64 ip = 0;
1121
1122         /*
1123          * The 'return' has already been popped off the stack so the depth has
1124          * to be adjusted to match the 'call'.
1125          */
1126         if (thread->ts && sample->flags & PERF_IP_FLAG_RETURN)
1127                 depth += 1;
1128
1129         if (sample->flags & (PERF_IP_FLAG_CALL | PERF_IP_FLAG_TRACE_BEGIN)) {
1130                 if (sample_addr_correlates_sym(attr)) {
1131                         thread__resolve(thread, &addr_al, sample);
1132                         if (addr_al.sym)
1133                                 name = addr_al.sym->name;
1134                         else
1135                                 ip = sample->addr;
1136                 } else {
1137                         ip = sample->addr;
1138                 }
1139         } else if (sample->flags & (PERF_IP_FLAG_RETURN | PERF_IP_FLAG_TRACE_END)) {
1140                 if (al->sym)
1141                         name = al->sym->name;
1142                 else
1143                         ip = sample->ip;
1144         }
1145
1146         if (PRINT_FIELD(DSO) && !(PRINT_FIELD(IP) || PRINT_FIELD(ADDR))) {
1147                 dlen += fprintf(fp, "(");
1148                 dlen += map__fprintf_dsoname(al->map, fp);
1149                 dlen += fprintf(fp, ")\t");
1150         }
1151
1152         if (name)
1153                 len = fprintf(fp, "%*s%s", (int)depth * 4, "", name);
1154         else if (ip)
1155                 len = fprintf(fp, "%*s%16" PRIx64, (int)depth * 4, "", ip);
1156
1157         if (len < 0)
1158                 return len;
1159
1160         /*
1161          * Try to keep the output length from changing frequently so that the
1162          * output lines up more nicely.
1163          */
1164         if (len > spacing || (len && len < spacing - 52))
1165                 spacing = round_up(len + 4, 32);
1166
1167         if (len < spacing)
1168                 len += fprintf(fp, "%*s", spacing - len, "");
1169
1170         return len + dlen;
1171 }
1172
1173 static int perf_sample__fprintf_insn(struct perf_sample *sample,
1174                                      struct perf_event_attr *attr,
1175                                      struct thread *thread,
1176                                      struct machine *machine, FILE *fp)
1177 {
1178         int printed = 0;
1179
1180         if (PRINT_FIELD(INSNLEN))
1181                 printed += fprintf(fp, " ilen: %d", sample->insn_len);
1182         if (PRINT_FIELD(INSN)) {
1183                 int i;
1184
1185                 printed += fprintf(fp, " insn:");
1186                 for (i = 0; i < sample->insn_len; i++)
1187                         printed += fprintf(fp, " %02x", (unsigned char)sample->insn[i]);
1188         }
1189         if (PRINT_FIELD(BRSTACKINSN))
1190                 printed += perf_sample__fprintf_brstackinsn(sample, thread, attr, machine, fp);
1191
1192         return printed;
1193 }
1194
1195 static int perf_sample__fprintf_bts(struct perf_sample *sample,
1196                                     struct perf_evsel *evsel,
1197                                     struct thread *thread,
1198                                     struct addr_location *al,
1199                                     struct machine *machine, FILE *fp)
1200 {
1201         struct perf_event_attr *attr = &evsel->attr;
1202         unsigned int type = output_type(attr->type);
1203         bool print_srcline_last = false;
1204         int printed = 0;
1205
1206         if (PRINT_FIELD(CALLINDENT))
1207                 printed += perf_sample__fprintf_callindent(sample, evsel, thread, al, fp);
1208
1209         /* print branch_from information */
1210         if (PRINT_FIELD(IP)) {
1211                 unsigned int print_opts = output[type].print_ip_opts;
1212                 struct callchain_cursor *cursor = NULL;
1213
1214                 if (symbol_conf.use_callchain && sample->callchain &&
1215                     thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
1216                                               sample, NULL, NULL, scripting_max_stack) == 0)
1217                         cursor = &callchain_cursor;
1218
1219                 if (cursor == NULL) {
1220                         printed += fprintf(fp, " ");
1221                         if (print_opts & EVSEL__PRINT_SRCLINE) {
1222                                 print_srcline_last = true;
1223                                 print_opts &= ~EVSEL__PRINT_SRCLINE;
1224                         }
1225                 } else
1226                         printed += fprintf(fp, "\n");
1227
1228                 printed += sample__fprintf_sym(sample, al, 0, print_opts, cursor, fp);
1229         }
1230
1231         /* print branch_to information */
1232         if (PRINT_FIELD(ADDR) ||
1233             ((evsel->attr.sample_type & PERF_SAMPLE_ADDR) &&
1234              !output[type].user_set)) {
1235                 printed += fprintf(fp, " => ");
1236                 printed += perf_sample__fprintf_addr(sample, thread, attr, fp);
1237         }
1238
1239         if (print_srcline_last)
1240                 printed += map__fprintf_srcline(al->map, al->addr, "\n  ", fp);
1241
1242         printed += perf_sample__fprintf_insn(sample, attr, thread, machine, fp);
1243         return printed + fprintf(fp, "\n");
1244 }
1245
1246 static struct {
1247         u32 flags;
1248         const char *name;
1249 } sample_flags[] = {
1250         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL, "call"},
1251         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN, "return"},
1252         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CONDITIONAL, "jcc"},
1253         {PERF_IP_FLAG_BRANCH, "jmp"},
1254         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_INTERRUPT, "int"},
1255         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN | PERF_IP_FLAG_INTERRUPT, "iret"},
1256         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_SYSCALLRET, "syscall"},
1257         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN | PERF_IP_FLAG_SYSCALLRET, "sysret"},
1258         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_ASYNC, "async"},
1259         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_ASYNC | PERF_IP_FLAG_INTERRUPT, "hw int"},
1260         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TX_ABORT, "tx abrt"},
1261         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TRACE_BEGIN, "tr strt"},
1262         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TRACE_END, "tr end"},
1263         {0, NULL}
1264 };
1265
1266 static const char *sample_flags_to_name(u32 flags)
1267 {
1268         int i;
1269
1270         for (i = 0; sample_flags[i].name ; i++) {
1271                 if (sample_flags[i].flags == flags)
1272                         return sample_flags[i].name;
1273         }
1274
1275         return NULL;
1276 }
1277
1278 static int perf_sample__fprintf_flags(u32 flags, FILE *fp)
1279 {
1280         const char *chars = PERF_IP_FLAG_CHARS;
1281         const int n = strlen(PERF_IP_FLAG_CHARS);
1282         bool in_tx = flags & PERF_IP_FLAG_IN_TX;
1283         const char *name = NULL;
1284         char str[33];
1285         int i, pos = 0;
1286
1287         name = sample_flags_to_name(flags & ~PERF_IP_FLAG_IN_TX);
1288         if (name)
1289                 return fprintf(fp, "  %-15s%4s ", name, in_tx ? "(x)" : "");
1290
1291         if (flags & PERF_IP_FLAG_TRACE_BEGIN) {
1292                 name = sample_flags_to_name(flags & ~(PERF_IP_FLAG_IN_TX | PERF_IP_FLAG_TRACE_BEGIN));
1293                 if (name)
1294                         return fprintf(fp, "  tr strt %-7s%4s ", name, in_tx ? "(x)" : "");
1295         }
1296
1297         if (flags & PERF_IP_FLAG_TRACE_END) {
1298                 name = sample_flags_to_name(flags & ~(PERF_IP_FLAG_IN_TX | PERF_IP_FLAG_TRACE_END));
1299                 if (name)
1300                         return fprintf(fp, "  tr end  %-7s%4s ", name, in_tx ? "(x)" : "");
1301         }
1302
1303         for (i = 0; i < n; i++, flags >>= 1) {
1304                 if (flags & 1)
1305                         str[pos++] = chars[i];
1306         }
1307         for (; i < 32; i++, flags >>= 1) {
1308                 if (flags & 1)
1309                         str[pos++] = '?';
1310         }
1311         str[pos] = 0;
1312
1313         return fprintf(fp, "  %-19s ", str);
1314 }
1315
1316 struct printer_data {
1317         int line_no;
1318         bool hit_nul;
1319         bool is_printable;
1320 };
1321
1322 static int sample__fprintf_bpf_output(enum binary_printer_ops op,
1323                                       unsigned int val,
1324                                       void *extra, FILE *fp)
1325 {
1326         unsigned char ch = (unsigned char)val;
1327         struct printer_data *printer_data = extra;
1328         int printed = 0;
1329
1330         switch (op) {
1331         case BINARY_PRINT_DATA_BEGIN:
1332                 printed += fprintf(fp, "\n");
1333                 break;
1334         case BINARY_PRINT_LINE_BEGIN:
1335                 printed += fprintf(fp, "%17s", !printer_data->line_no ? "BPF output:" :
1336                                                         "           ");
1337                 break;
1338         case BINARY_PRINT_ADDR:
1339                 printed += fprintf(fp, " %04x:", val);
1340                 break;
1341         case BINARY_PRINT_NUM_DATA:
1342                 printed += fprintf(fp, " %02x", val);
1343                 break;
1344         case BINARY_PRINT_NUM_PAD:
1345                 printed += fprintf(fp, "   ");
1346                 break;
1347         case BINARY_PRINT_SEP:
1348                 printed += fprintf(fp, "  ");
1349                 break;
1350         case BINARY_PRINT_CHAR_DATA:
1351                 if (printer_data->hit_nul && ch)
1352                         printer_data->is_printable = false;
1353
1354                 if (!isprint(ch)) {
1355                         printed += fprintf(fp, "%c", '.');
1356
1357                         if (!printer_data->is_printable)
1358                                 break;
1359
1360                         if (ch == '\0')
1361                                 printer_data->hit_nul = true;
1362                         else
1363                                 printer_data->is_printable = false;
1364                 } else {
1365                         printed += fprintf(fp, "%c", ch);
1366                 }
1367                 break;
1368         case BINARY_PRINT_CHAR_PAD:
1369                 printed += fprintf(fp, " ");
1370                 break;
1371         case BINARY_PRINT_LINE_END:
1372                 printed += fprintf(fp, "\n");
1373                 printer_data->line_no++;
1374                 break;
1375         case BINARY_PRINT_DATA_END:
1376         default:
1377                 break;
1378         }
1379
1380         return printed;
1381 }
1382
1383 static int perf_sample__fprintf_bpf_output(struct perf_sample *sample, FILE *fp)
1384 {
1385         unsigned int nr_bytes = sample->raw_size;
1386         struct printer_data printer_data = {0, false, true};
1387         int printed = binary__fprintf(sample->raw_data, nr_bytes, 8,
1388                                       sample__fprintf_bpf_output, &printer_data, fp);
1389
1390         if (printer_data.is_printable && printer_data.hit_nul)
1391                 printed += fprintf(fp, "%17s \"%s\"\n", "BPF string:", (char *)(sample->raw_data));
1392
1393         return printed;
1394 }
1395
1396 static int perf_sample__fprintf_spacing(int len, int spacing, FILE *fp)
1397 {
1398         if (len > 0 && len < spacing)
1399                 return fprintf(fp, "%*s", spacing - len, "");
1400
1401         return 0;
1402 }
1403
1404 static int perf_sample__fprintf_pt_spacing(int len, FILE *fp)
1405 {
1406         return perf_sample__fprintf_spacing(len, 34, fp);
1407 }
1408
1409 static int perf_sample__fprintf_synth_ptwrite(struct perf_sample *sample, FILE *fp)
1410 {
1411         struct perf_synth_intel_ptwrite *data = perf_sample__synth_ptr(sample);
1412         int len;
1413
1414         if (perf_sample__bad_synth_size(sample, *data))
1415                 return 0;
1416
1417         len = fprintf(fp, " IP: %u payload: %#" PRIx64 " ",
1418                      data->ip, le64_to_cpu(data->payload));
1419         return len + perf_sample__fprintf_pt_spacing(len, fp);
1420 }
1421
1422 static int perf_sample__fprintf_synth_mwait(struct perf_sample *sample, FILE *fp)
1423 {
1424         struct perf_synth_intel_mwait *data = perf_sample__synth_ptr(sample);
1425         int len;
1426
1427         if (perf_sample__bad_synth_size(sample, *data))
1428                 return 0;
1429
1430         len = fprintf(fp, " hints: %#x extensions: %#x ",
1431                       data->hints, data->extensions);
1432         return len + perf_sample__fprintf_pt_spacing(len, fp);
1433 }
1434
1435 static int perf_sample__fprintf_synth_pwre(struct perf_sample *sample, FILE *fp)
1436 {
1437         struct perf_synth_intel_pwre *data = perf_sample__synth_ptr(sample);
1438         int len;
1439
1440         if (perf_sample__bad_synth_size(sample, *data))
1441                 return 0;
1442
1443         len = fprintf(fp, " hw: %u cstate: %u sub-cstate: %u ",
1444                       data->hw, data->cstate, data->subcstate);
1445         return len + perf_sample__fprintf_pt_spacing(len, fp);
1446 }
1447
1448 static int perf_sample__fprintf_synth_exstop(struct perf_sample *sample, FILE *fp)
1449 {
1450         struct perf_synth_intel_exstop *data = perf_sample__synth_ptr(sample);
1451         int len;
1452
1453         if (perf_sample__bad_synth_size(sample, *data))
1454                 return 0;
1455
1456         len = fprintf(fp, " IP: %u ", data->ip);
1457         return len + perf_sample__fprintf_pt_spacing(len, fp);
1458 }
1459
1460 static int perf_sample__fprintf_synth_pwrx(struct perf_sample *sample, FILE *fp)
1461 {
1462         struct perf_synth_intel_pwrx *data = perf_sample__synth_ptr(sample);
1463         int len;
1464
1465         if (perf_sample__bad_synth_size(sample, *data))
1466                 return 0;
1467
1468         len = fprintf(fp, " deepest cstate: %u last cstate: %u wake reason: %#x ",
1469                      data->deepest_cstate, data->last_cstate,
1470                      data->wake_reason);
1471         return len + perf_sample__fprintf_pt_spacing(len, fp);
1472 }
1473
1474 static int perf_sample__fprintf_synth_cbr(struct perf_sample *sample, FILE *fp)
1475 {
1476         struct perf_synth_intel_cbr *data = perf_sample__synth_ptr(sample);
1477         unsigned int percent, freq;
1478         int len;
1479
1480         if (perf_sample__bad_synth_size(sample, *data))
1481                 return 0;
1482
1483         freq = (le32_to_cpu(data->freq) + 500) / 1000;
1484         len = fprintf(fp, " cbr: %2u freq: %4u MHz ", data->cbr, freq);
1485         if (data->max_nonturbo) {
1486                 percent = (5 + (1000 * data->cbr) / data->max_nonturbo) / 10;
1487                 len += fprintf(fp, "(%3u%%) ", percent);
1488         }
1489         return len + perf_sample__fprintf_pt_spacing(len, fp);
1490 }
1491
1492 static int perf_sample__fprintf_synth(struct perf_sample *sample,
1493                                       struct perf_evsel *evsel, FILE *fp)
1494 {
1495         switch (evsel->attr.config) {
1496         case PERF_SYNTH_INTEL_PTWRITE:
1497                 return perf_sample__fprintf_synth_ptwrite(sample, fp);
1498         case PERF_SYNTH_INTEL_MWAIT:
1499                 return perf_sample__fprintf_synth_mwait(sample, fp);
1500         case PERF_SYNTH_INTEL_PWRE:
1501                 return perf_sample__fprintf_synth_pwre(sample, fp);
1502         case PERF_SYNTH_INTEL_EXSTOP:
1503                 return perf_sample__fprintf_synth_exstop(sample, fp);
1504         case PERF_SYNTH_INTEL_PWRX:
1505                 return perf_sample__fprintf_synth_pwrx(sample, fp);
1506         case PERF_SYNTH_INTEL_CBR:
1507                 return perf_sample__fprintf_synth_cbr(sample, fp);
1508         default:
1509                 break;
1510         }
1511
1512         return 0;
1513 }
1514
1515 struct perf_script {
1516         struct perf_tool        tool;
1517         struct perf_session     *session;
1518         bool                    show_task_events;
1519         bool                    show_mmap_events;
1520         bool                    show_switch_events;
1521         bool                    show_namespace_events;
1522         bool                    show_lost_events;
1523         bool                    show_round_events;
1524         bool                    allocated;
1525         bool                    per_event_dump;
1526         struct cpu_map          *cpus;
1527         struct thread_map       *threads;
1528         int                     name_width;
1529         const char              *time_str;
1530         struct perf_time_interval *ptime_range;
1531         int                     range_size;
1532         int                     range_num;
1533 };
1534
1535 static int perf_evlist__max_name_len(struct perf_evlist *evlist)
1536 {
1537         struct perf_evsel *evsel;
1538         int max = 0;
1539
1540         evlist__for_each_entry(evlist, evsel) {
1541                 int len = strlen(perf_evsel__name(evsel));
1542
1543                 max = MAX(len, max);
1544         }
1545
1546         return max;
1547 }
1548
1549 static int data_src__fprintf(u64 data_src, FILE *fp)
1550 {
1551         struct mem_info mi = { .data_src.val = data_src };
1552         char decode[100];
1553         char out[100];
1554         static int maxlen;
1555         int len;
1556
1557         perf_script__meminfo_scnprintf(decode, 100, &mi);
1558
1559         len = scnprintf(out, 100, "%16" PRIx64 " %s", data_src, decode);
1560         if (maxlen < len)
1561                 maxlen = len;
1562
1563         return fprintf(fp, "%-*s", maxlen, out);
1564 }
1565
1566 struct metric_ctx {
1567         struct perf_sample      *sample;
1568         struct thread           *thread;
1569         struct perf_evsel       *evsel;
1570         FILE                    *fp;
1571 };
1572
1573 static void script_print_metric(struct perf_stat_config *config __maybe_unused,
1574                                 void *ctx, const char *color,
1575                                 const char *fmt,
1576                                 const char *unit, double val)
1577 {
1578         struct metric_ctx *mctx = ctx;
1579
1580         if (!fmt)
1581                 return;
1582         perf_sample__fprintf_start(mctx->sample, mctx->thread, mctx->evsel,
1583                                    PERF_RECORD_SAMPLE, mctx->fp);
1584         fputs("\tmetric: ", mctx->fp);
1585         if (color)
1586                 color_fprintf(mctx->fp, color, fmt, val);
1587         else
1588                 printf(fmt, val);
1589         fprintf(mctx->fp, " %s\n", unit);
1590 }
1591
1592 static void script_new_line(struct perf_stat_config *config __maybe_unused,
1593                             void *ctx)
1594 {
1595         struct metric_ctx *mctx = ctx;
1596
1597         perf_sample__fprintf_start(mctx->sample, mctx->thread, mctx->evsel,
1598                                    PERF_RECORD_SAMPLE, mctx->fp);
1599         fputs("\tmetric: ", mctx->fp);
1600 }
1601
1602 static void perf_sample__fprint_metric(struct perf_script *script,
1603                                        struct thread *thread,
1604                                        struct perf_evsel *evsel,
1605                                        struct perf_sample *sample,
1606                                        FILE *fp)
1607 {
1608         struct perf_stat_output_ctx ctx = {
1609                 .print_metric = script_print_metric,
1610                 .new_line = script_new_line,
1611                 .ctx = &(struct metric_ctx) {
1612                                 .sample = sample,
1613                                 .thread = thread,
1614                                 .evsel  = evsel,
1615                                 .fp     = fp,
1616                          },
1617                 .force_header = false,
1618         };
1619         struct perf_evsel *ev2;
1620         static bool init;
1621         u64 val;
1622
1623         if (!init) {
1624                 perf_stat__init_shadow_stats();
1625                 init = true;
1626         }
1627         if (!evsel->stats)
1628                 perf_evlist__alloc_stats(script->session->evlist, false);
1629         if (evsel_script(evsel->leader)->gnum++ == 0)
1630                 perf_stat__reset_shadow_stats();
1631         val = sample->period * evsel->scale;
1632         perf_stat__update_shadow_stats(evsel,
1633                                        val,
1634                                        sample->cpu,
1635                                        &rt_stat);
1636         evsel_script(evsel)->val = val;
1637         if (evsel_script(evsel->leader)->gnum == evsel->leader->nr_members) {
1638                 for_each_group_member (ev2, evsel->leader) {
1639                         perf_stat__print_shadow_stats(&stat_config, ev2,
1640                                                       evsel_script(ev2)->val,
1641                                                       sample->cpu,
1642                                                       &ctx,
1643                                                       NULL,
1644                                                       &rt_stat);
1645                 }
1646                 evsel_script(evsel->leader)->gnum = 0;
1647         }
1648 }
1649
1650 static void process_event(struct perf_script *script,
1651                           struct perf_sample *sample, struct perf_evsel *evsel,
1652                           struct addr_location *al,
1653                           struct machine *machine)
1654 {
1655         struct thread *thread = al->thread;
1656         struct perf_event_attr *attr = &evsel->attr;
1657         unsigned int type = output_type(attr->type);
1658         struct perf_evsel_script *es = evsel->priv;
1659         FILE *fp = es->fp;
1660
1661         if (output[type].fields == 0)
1662                 return;
1663
1664         ++es->samples;
1665
1666         perf_sample__fprintf_start(sample, thread, evsel,
1667                                    PERF_RECORD_SAMPLE, fp);
1668
1669         if (PRINT_FIELD(PERIOD))
1670                 fprintf(fp, "%10" PRIu64 " ", sample->period);
1671
1672         if (PRINT_FIELD(EVNAME)) {
1673                 const char *evname = perf_evsel__name(evsel);
1674
1675                 if (!script->name_width)
1676                         script->name_width = perf_evlist__max_name_len(script->session->evlist);
1677
1678                 fprintf(fp, "%*s: ", script->name_width, evname ?: "[unknown]");
1679         }
1680
1681         if (print_flags)
1682                 perf_sample__fprintf_flags(sample->flags, fp);
1683
1684         if (is_bts_event(attr)) {
1685                 perf_sample__fprintf_bts(sample, evsel, thread, al, machine, fp);
1686                 return;
1687         }
1688
1689         if (PRINT_FIELD(TRACE)) {
1690                 event_format__fprintf(evsel->tp_format, sample->cpu,
1691                                       sample->raw_data, sample->raw_size, fp);
1692         }
1693
1694         if (attr->type == PERF_TYPE_SYNTH && PRINT_FIELD(SYNTH))
1695                 perf_sample__fprintf_synth(sample, evsel, fp);
1696
1697         if (PRINT_FIELD(ADDR))
1698                 perf_sample__fprintf_addr(sample, thread, attr, fp);
1699
1700         if (PRINT_FIELD(DATA_SRC))
1701                 data_src__fprintf(sample->data_src, fp);
1702
1703         if (PRINT_FIELD(WEIGHT))
1704                 fprintf(fp, "%16" PRIu64, sample->weight);
1705
1706         if (PRINT_FIELD(IP)) {
1707                 struct callchain_cursor *cursor = NULL;
1708
1709                 if (symbol_conf.use_callchain && sample->callchain &&
1710                     thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
1711                                               sample, NULL, NULL, scripting_max_stack) == 0)
1712                         cursor = &callchain_cursor;
1713
1714                 fputc(cursor ? '\n' : ' ', fp);
1715                 sample__fprintf_sym(sample, al, 0, output[type].print_ip_opts, cursor, fp);
1716         }
1717
1718         if (PRINT_FIELD(IREGS))
1719                 perf_sample__fprintf_iregs(sample, attr, fp);
1720
1721         if (PRINT_FIELD(UREGS))
1722                 perf_sample__fprintf_uregs(sample, attr, fp);
1723
1724         if (PRINT_FIELD(BRSTACK))
1725                 perf_sample__fprintf_brstack(sample, thread, attr, fp);
1726         else if (PRINT_FIELD(BRSTACKSYM))
1727                 perf_sample__fprintf_brstacksym(sample, thread, attr, fp);
1728         else if (PRINT_FIELD(BRSTACKOFF))
1729                 perf_sample__fprintf_brstackoff(sample, thread, attr, fp);
1730
1731         if (perf_evsel__is_bpf_output(evsel) && PRINT_FIELD(BPF_OUTPUT))
1732                 perf_sample__fprintf_bpf_output(sample, fp);
1733         perf_sample__fprintf_insn(sample, attr, thread, machine, fp);
1734
1735         if (PRINT_FIELD(PHYS_ADDR))
1736                 fprintf(fp, "%16" PRIx64, sample->phys_addr);
1737         fprintf(fp, "\n");
1738
1739         if (PRINT_FIELD(METRIC))
1740                 perf_sample__fprint_metric(script, thread, evsel, sample, fp);
1741
1742         if (verbose)
1743                 fflush(fp);
1744 }
1745
1746 static struct scripting_ops     *scripting_ops;
1747
1748 static void __process_stat(struct perf_evsel *counter, u64 tstamp)
1749 {
1750         int nthreads = thread_map__nr(counter->threads);
1751         int ncpus = perf_evsel__nr_cpus(counter);
1752         int cpu, thread;
1753         static int header_printed;
1754
1755         if (counter->system_wide)
1756                 nthreads = 1;
1757
1758         if (!header_printed) {
1759                 printf("%3s %8s %15s %15s %15s %15s %s\n",
1760                        "CPU", "THREAD", "VAL", "ENA", "RUN", "TIME", "EVENT");
1761                 header_printed = 1;
1762         }
1763
1764         for (thread = 0; thread < nthreads; thread++) {
1765                 for (cpu = 0; cpu < ncpus; cpu++) {
1766                         struct perf_counts_values *counts;
1767
1768                         counts = perf_counts(counter->counts, cpu, thread);
1769
1770                         printf("%3d %8d %15" PRIu64 " %15" PRIu64 " %15" PRIu64 " %15" PRIu64 " %s\n",
1771                                 counter->cpus->map[cpu],
1772                                 thread_map__pid(counter->threads, thread),
1773                                 counts->val,
1774                                 counts->ena,
1775                                 counts->run,
1776                                 tstamp,
1777                                 perf_evsel__name(counter));
1778                 }
1779         }
1780 }
1781
1782 static void process_stat(struct perf_evsel *counter, u64 tstamp)
1783 {
1784         if (scripting_ops && scripting_ops->process_stat)
1785                 scripting_ops->process_stat(&stat_config, counter, tstamp);
1786         else
1787                 __process_stat(counter, tstamp);
1788 }
1789
1790 static void process_stat_interval(u64 tstamp)
1791 {
1792         if (scripting_ops && scripting_ops->process_stat_interval)
1793                 scripting_ops->process_stat_interval(tstamp);
1794 }
1795
1796 static void setup_scripting(void)
1797 {
1798         setup_perl_scripting();
1799         setup_python_scripting();
1800 }
1801
1802 static int flush_scripting(void)
1803 {
1804         return scripting_ops ? scripting_ops->flush_script() : 0;
1805 }
1806
1807 static int cleanup_scripting(void)
1808 {
1809         pr_debug("\nperf script stopped\n");
1810
1811         return scripting_ops ? scripting_ops->stop_script() : 0;
1812 }
1813
1814 static int process_sample_event(struct perf_tool *tool,
1815                                 union perf_event *event,
1816                                 struct perf_sample *sample,
1817                                 struct perf_evsel *evsel,
1818                                 struct machine *machine)
1819 {
1820         struct perf_script *scr = container_of(tool, struct perf_script, tool);
1821         struct addr_location al;
1822
1823         if (perf_time__ranges_skip_sample(scr->ptime_range, scr->range_num,
1824                                           sample->time)) {
1825                 return 0;
1826         }
1827
1828         if (debug_mode) {
1829                 if (sample->time < last_timestamp) {
1830                         pr_err("Samples misordered, previous: %" PRIu64
1831                                 " this: %" PRIu64 "\n", last_timestamp,
1832                                 sample->time);
1833                         nr_unordered++;
1834                 }
1835                 last_timestamp = sample->time;
1836                 return 0;
1837         }
1838
1839         if (machine__resolve(machine, &al, sample) < 0) {
1840                 pr_err("problem processing %d event, skipping it.\n",
1841                        event->header.type);
1842                 return -1;
1843         }
1844
1845         if (al.filtered)
1846                 goto out_put;
1847
1848         if (cpu_list && !test_bit(sample->cpu, cpu_bitmap))
1849                 goto out_put;
1850
1851         if (scripting_ops)
1852                 scripting_ops->process_event(event, sample, evsel, &al);
1853         else
1854                 process_event(scr, sample, evsel, &al, machine);
1855
1856 out_put:
1857         addr_location__put(&al);
1858         return 0;
1859 }
1860
1861 static int process_attr(struct perf_tool *tool, union perf_event *event,
1862                         struct perf_evlist **pevlist)
1863 {
1864         struct perf_script *scr = container_of(tool, struct perf_script, tool);
1865         struct perf_evlist *evlist;
1866         struct perf_evsel *evsel, *pos;
1867         int err;
1868         static struct perf_evsel_script *es;
1869
1870         err = perf_event__process_attr(tool, event, pevlist);
1871         if (err)
1872                 return err;
1873
1874         evlist = *pevlist;
1875         evsel = perf_evlist__last(*pevlist);
1876
1877         if (!evsel->priv) {
1878                 if (scr->per_event_dump) {
1879                         evsel->priv = perf_evsel_script__new(evsel,
1880                                                 scr->session->data);
1881                 } else {
1882                         es = zalloc(sizeof(*es));
1883                         if (!es)
1884                                 return -ENOMEM;
1885                         es->fp = stdout;
1886                         evsel->priv = es;
1887                 }
1888         }
1889
1890         if (evsel->attr.type >= PERF_TYPE_MAX &&
1891             evsel->attr.type != PERF_TYPE_SYNTH)
1892                 return 0;
1893
1894         evlist__for_each_entry(evlist, pos) {
1895                 if (pos->attr.type == evsel->attr.type && pos != evsel)
1896                         return 0;
1897         }
1898
1899         set_print_ip_opts(&evsel->attr);
1900
1901         if (evsel->attr.sample_type)
1902                 err = perf_evsel__check_attr(evsel, scr->session);
1903
1904         return err;
1905 }
1906
1907 static int process_comm_event(struct perf_tool *tool,
1908                               union perf_event *event,
1909                               struct perf_sample *sample,
1910                               struct machine *machine)
1911 {
1912         struct thread *thread;
1913         struct perf_script *script = container_of(tool, struct perf_script, tool);
1914         struct perf_session *session = script->session;
1915         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1916         int ret = -1;
1917
1918         thread = machine__findnew_thread(machine, event->comm.pid, event->comm.tid);
1919         if (thread == NULL) {
1920                 pr_debug("problem processing COMM event, skipping it.\n");
1921                 return -1;
1922         }
1923
1924         if (perf_event__process_comm(tool, event, sample, machine) < 0)
1925                 goto out;
1926
1927         if (!evsel->attr.sample_id_all) {
1928                 sample->cpu = 0;
1929                 sample->time = 0;
1930                 sample->tid = event->comm.tid;
1931                 sample->pid = event->comm.pid;
1932         }
1933         perf_sample__fprintf_start(sample, thread, evsel,
1934                                    PERF_RECORD_COMM, stdout);
1935         perf_event__fprintf(event, stdout);
1936         ret = 0;
1937 out:
1938         thread__put(thread);
1939         return ret;
1940 }
1941
1942 static int process_namespaces_event(struct perf_tool *tool,
1943                                     union perf_event *event,
1944                                     struct perf_sample *sample,
1945                                     struct machine *machine)
1946 {
1947         struct thread *thread;
1948         struct perf_script *script = container_of(tool, struct perf_script, tool);
1949         struct perf_session *session = script->session;
1950         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1951         int ret = -1;
1952
1953         thread = machine__findnew_thread(machine, event->namespaces.pid,
1954                                          event->namespaces.tid);
1955         if (thread == NULL) {
1956                 pr_debug("problem processing NAMESPACES event, skipping it.\n");
1957                 return -1;
1958         }
1959
1960         if (perf_event__process_namespaces(tool, event, sample, machine) < 0)
1961                 goto out;
1962
1963         if (!evsel->attr.sample_id_all) {
1964                 sample->cpu = 0;
1965                 sample->time = 0;
1966                 sample->tid = event->namespaces.tid;
1967                 sample->pid = event->namespaces.pid;
1968         }
1969         perf_sample__fprintf_start(sample, thread, evsel,
1970                                    PERF_RECORD_NAMESPACES, stdout);
1971         perf_event__fprintf(event, stdout);
1972         ret = 0;
1973 out:
1974         thread__put(thread);
1975         return ret;
1976 }
1977
1978 static int process_fork_event(struct perf_tool *tool,
1979                               union perf_event *event,
1980                               struct perf_sample *sample,
1981                               struct machine *machine)
1982 {
1983         struct thread *thread;
1984         struct perf_script *script = container_of(tool, struct perf_script, tool);
1985         struct perf_session *session = script->session;
1986         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1987
1988         if (perf_event__process_fork(tool, event, sample, machine) < 0)
1989                 return -1;
1990
1991         thread = machine__findnew_thread(machine, event->fork.pid, event->fork.tid);
1992         if (thread == NULL) {
1993                 pr_debug("problem processing FORK event, skipping it.\n");
1994                 return -1;
1995         }
1996
1997         if (!evsel->attr.sample_id_all) {
1998                 sample->cpu = 0;
1999                 sample->time = event->fork.time;
2000                 sample->tid = event->fork.tid;
2001                 sample->pid = event->fork.pid;
2002         }
2003         perf_sample__fprintf_start(sample, thread, evsel,
2004                                    PERF_RECORD_FORK, stdout);
2005         perf_event__fprintf(event, stdout);
2006         thread__put(thread);
2007
2008         return 0;
2009 }
2010 static int process_exit_event(struct perf_tool *tool,
2011                               union perf_event *event,
2012                               struct perf_sample *sample,
2013                               struct machine *machine)
2014 {
2015         int err = 0;
2016         struct thread *thread;
2017         struct perf_script *script = container_of(tool, struct perf_script, tool);
2018         struct perf_session *session = script->session;
2019         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2020
2021         thread = machine__findnew_thread(machine, event->fork.pid, event->fork.tid);
2022         if (thread == NULL) {
2023                 pr_debug("problem processing EXIT event, skipping it.\n");
2024                 return -1;
2025         }
2026
2027         if (!evsel->attr.sample_id_all) {
2028                 sample->cpu = 0;
2029                 sample->time = 0;
2030                 sample->tid = event->fork.tid;
2031                 sample->pid = event->fork.pid;
2032         }
2033         perf_sample__fprintf_start(sample, thread, evsel,
2034                                    PERF_RECORD_EXIT, stdout);
2035         perf_event__fprintf(event, stdout);
2036
2037         if (perf_event__process_exit(tool, event, sample, machine) < 0)
2038                 err = -1;
2039
2040         thread__put(thread);
2041         return err;
2042 }
2043
2044 static int process_mmap_event(struct perf_tool *tool,
2045                               union perf_event *event,
2046                               struct perf_sample *sample,
2047                               struct machine *machine)
2048 {
2049         struct thread *thread;
2050         struct perf_script *script = container_of(tool, struct perf_script, tool);
2051         struct perf_session *session = script->session;
2052         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2053
2054         if (perf_event__process_mmap(tool, event, sample, machine) < 0)
2055                 return -1;
2056
2057         thread = machine__findnew_thread(machine, event->mmap.pid, event->mmap.tid);
2058         if (thread == NULL) {
2059                 pr_debug("problem processing MMAP event, skipping it.\n");
2060                 return -1;
2061         }
2062
2063         if (!evsel->attr.sample_id_all) {
2064                 sample->cpu = 0;
2065                 sample->time = 0;
2066                 sample->tid = event->mmap.tid;
2067                 sample->pid = event->mmap.pid;
2068         }
2069         perf_sample__fprintf_start(sample, thread, evsel,
2070                                    PERF_RECORD_MMAP, stdout);
2071         perf_event__fprintf(event, stdout);
2072         thread__put(thread);
2073         return 0;
2074 }
2075
2076 static int process_mmap2_event(struct perf_tool *tool,
2077                               union perf_event *event,
2078                               struct perf_sample *sample,
2079                               struct machine *machine)
2080 {
2081         struct thread *thread;
2082         struct perf_script *script = container_of(tool, struct perf_script, tool);
2083         struct perf_session *session = script->session;
2084         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2085
2086         if (perf_event__process_mmap2(tool, event, sample, machine) < 0)
2087                 return -1;
2088
2089         thread = machine__findnew_thread(machine, event->mmap2.pid, event->mmap2.tid);
2090         if (thread == NULL) {
2091                 pr_debug("problem processing MMAP2 event, skipping it.\n");
2092                 return -1;
2093         }
2094
2095         if (!evsel->attr.sample_id_all) {
2096                 sample->cpu = 0;
2097                 sample->time = 0;
2098                 sample->tid = event->mmap2.tid;
2099                 sample->pid = event->mmap2.pid;
2100         }
2101         perf_sample__fprintf_start(sample, thread, evsel,
2102                                    PERF_RECORD_MMAP2, stdout);
2103         perf_event__fprintf(event, stdout);
2104         thread__put(thread);
2105         return 0;
2106 }
2107
2108 static int process_switch_event(struct perf_tool *tool,
2109                                 union perf_event *event,
2110                                 struct perf_sample *sample,
2111                                 struct machine *machine)
2112 {
2113         struct thread *thread;
2114         struct perf_script *script = container_of(tool, struct perf_script, tool);
2115         struct perf_session *session = script->session;
2116         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2117
2118         if (perf_event__process_switch(tool, event, sample, machine) < 0)
2119                 return -1;
2120
2121         thread = machine__findnew_thread(machine, sample->pid,
2122                                          sample->tid);
2123         if (thread == NULL) {
2124                 pr_debug("problem processing SWITCH event, skipping it.\n");
2125                 return -1;
2126         }
2127
2128         perf_sample__fprintf_start(sample, thread, evsel,
2129                                    PERF_RECORD_SWITCH, stdout);
2130         perf_event__fprintf(event, stdout);
2131         thread__put(thread);
2132         return 0;
2133 }
2134
2135 static int
2136 process_lost_event(struct perf_tool *tool,
2137                    union perf_event *event,
2138                    struct perf_sample *sample,
2139                    struct machine *machine)
2140 {
2141         struct perf_script *script = container_of(tool, struct perf_script, tool);
2142         struct perf_session *session = script->session;
2143         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2144         struct thread *thread;
2145
2146         thread = machine__findnew_thread(machine, sample->pid,
2147                                          sample->tid);
2148         if (thread == NULL)
2149                 return -1;
2150
2151         perf_sample__fprintf_start(sample, thread, evsel,
2152                                    PERF_RECORD_LOST, stdout);
2153         perf_event__fprintf(event, stdout);
2154         thread__put(thread);
2155         return 0;
2156 }
2157
2158 static int
2159 process_finished_round_event(struct perf_tool *tool __maybe_unused,
2160                              union perf_event *event,
2161                              struct ordered_events *oe __maybe_unused)
2162
2163 {
2164         perf_event__fprintf(event, stdout);
2165         return 0;
2166 }
2167
2168 static void sig_handler(int sig __maybe_unused)
2169 {
2170         session_done = 1;
2171 }
2172
2173 static void perf_script__fclose_per_event_dump(struct perf_script *script)
2174 {
2175         struct perf_evlist *evlist = script->session->evlist;
2176         struct perf_evsel *evsel;
2177
2178         evlist__for_each_entry(evlist, evsel) {
2179                 if (!evsel->priv)
2180                         break;
2181                 perf_evsel_script__delete(evsel->priv);
2182                 evsel->priv = NULL;
2183         }
2184 }
2185
2186 static int perf_script__fopen_per_event_dump(struct perf_script *script)
2187 {
2188         struct perf_evsel *evsel;
2189
2190         evlist__for_each_entry(script->session->evlist, evsel) {
2191                 /*
2192                  * Already setup? I.e. we may be called twice in cases like
2193                  * Intel PT, one for the intel_pt// and dummy events, then
2194                  * for the evsels syntheized from the auxtrace info.
2195                  *
2196                  * Ses perf_script__process_auxtrace_info.
2197                  */
2198                 if (evsel->priv != NULL)
2199                         continue;
2200
2201                 evsel->priv = perf_evsel_script__new(evsel, script->session->data);
2202                 if (evsel->priv == NULL)
2203                         goto out_err_fclose;
2204         }
2205
2206         return 0;
2207
2208 out_err_fclose:
2209         perf_script__fclose_per_event_dump(script);
2210         return -1;
2211 }
2212
2213 static int perf_script__setup_per_event_dump(struct perf_script *script)
2214 {
2215         struct perf_evsel *evsel;
2216         static struct perf_evsel_script es_stdout;
2217
2218         if (script->per_event_dump)
2219                 return perf_script__fopen_per_event_dump(script);
2220
2221         es_stdout.fp = stdout;
2222
2223         evlist__for_each_entry(script->session->evlist, evsel)
2224                 evsel->priv = &es_stdout;
2225
2226         return 0;
2227 }
2228
2229 static void perf_script__exit_per_event_dump_stats(struct perf_script *script)
2230 {
2231         struct perf_evsel *evsel;
2232
2233         evlist__for_each_entry(script->session->evlist, evsel) {
2234                 struct perf_evsel_script *es = evsel->priv;
2235
2236                 perf_evsel_script__fprintf(es, stdout);
2237                 perf_evsel_script__delete(es);
2238                 evsel->priv = NULL;
2239         }
2240 }
2241
2242 static int __cmd_script(struct perf_script *script)
2243 {
2244         int ret;
2245
2246         signal(SIGINT, sig_handler);
2247
2248         /* override event processing functions */
2249         if (script->show_task_events) {
2250                 script->tool.comm = process_comm_event;
2251                 script->tool.fork = process_fork_event;
2252                 script->tool.exit = process_exit_event;
2253         }
2254         if (script->show_mmap_events) {
2255                 script->tool.mmap = process_mmap_event;
2256                 script->tool.mmap2 = process_mmap2_event;
2257         }
2258         if (script->show_switch_events)
2259                 script->tool.context_switch = process_switch_event;
2260         if (script->show_namespace_events)
2261                 script->tool.namespaces = process_namespaces_event;
2262         if (script->show_lost_events)
2263                 script->tool.lost = process_lost_event;
2264         if (script->show_round_events) {
2265                 script->tool.ordered_events = false;
2266                 script->tool.finished_round = process_finished_round_event;
2267         }
2268
2269         if (perf_script__setup_per_event_dump(script)) {
2270                 pr_err("Couldn't create the per event dump files\n");
2271                 return -1;
2272         }
2273
2274         ret = perf_session__process_events(script->session);
2275
2276         if (script->per_event_dump)
2277                 perf_script__exit_per_event_dump_stats(script);
2278
2279         if (debug_mode)
2280                 pr_err("Misordered timestamps: %" PRIu64 "\n", nr_unordered);
2281
2282         return ret;
2283 }
2284
2285 struct script_spec {
2286         struct list_head        node;
2287         struct scripting_ops    *ops;
2288         char                    spec[0];
2289 };
2290
2291 static LIST_HEAD(script_specs);
2292
2293 static struct script_spec *script_spec__new(const char *spec,
2294                                             struct scripting_ops *ops)
2295 {
2296         struct script_spec *s = malloc(sizeof(*s) + strlen(spec) + 1);
2297
2298         if (s != NULL) {
2299                 strcpy(s->spec, spec);
2300                 s->ops = ops;
2301         }
2302
2303         return s;
2304 }
2305
2306 static void script_spec__add(struct script_spec *s)
2307 {
2308         list_add_tail(&s->node, &script_specs);
2309 }
2310
2311 static struct script_spec *script_spec__find(const char *spec)
2312 {
2313         struct script_spec *s;
2314
2315         list_for_each_entry(s, &script_specs, node)
2316                 if (strcasecmp(s->spec, spec) == 0)
2317                         return s;
2318         return NULL;
2319 }
2320
2321 int script_spec_register(const char *spec, struct scripting_ops *ops)
2322 {
2323         struct script_spec *s;
2324
2325         s = script_spec__find(spec);
2326         if (s)
2327                 return -1;
2328
2329         s = script_spec__new(spec, ops);
2330         if (!s)
2331                 return -1;
2332         else
2333                 script_spec__add(s);
2334
2335         return 0;
2336 }
2337
2338 static struct scripting_ops *script_spec__lookup(const char *spec)
2339 {
2340         struct script_spec *s = script_spec__find(spec);
2341         if (!s)
2342                 return NULL;
2343
2344         return s->ops;
2345 }
2346
2347 static void list_available_languages(void)
2348 {
2349         struct script_spec *s;
2350
2351         fprintf(stderr, "\n");
2352         fprintf(stderr, "Scripting language extensions (used in "
2353                 "perf script -s [spec:]script.[spec]):\n\n");
2354
2355         list_for_each_entry(s, &script_specs, node)
2356                 fprintf(stderr, "  %-42s [%s]\n", s->spec, s->ops->name);
2357
2358         fprintf(stderr, "\n");
2359 }
2360
2361 static int parse_scriptname(const struct option *opt __maybe_unused,
2362                             const char *str, int unset __maybe_unused)
2363 {
2364         char spec[PATH_MAX];
2365         const char *script, *ext;
2366         int len;
2367
2368         if (strcmp(str, "lang") == 0) {
2369                 list_available_languages();
2370                 exit(0);
2371         }
2372
2373         script = strchr(str, ':');
2374         if (script) {
2375                 len = script - str;
2376                 if (len >= PATH_MAX) {
2377                         fprintf(stderr, "invalid language specifier");
2378                         return -1;
2379                 }
2380                 strncpy(spec, str, len);
2381                 spec[len] = '\0';
2382                 scripting_ops = script_spec__lookup(spec);
2383                 if (!scripting_ops) {
2384                         fprintf(stderr, "invalid language specifier");
2385                         return -1;
2386                 }
2387                 script++;
2388         } else {
2389                 script = str;
2390                 ext = strrchr(script, '.');
2391                 if (!ext) {
2392                         fprintf(stderr, "invalid script extension");
2393                         return -1;
2394                 }
2395                 scripting_ops = script_spec__lookup(++ext);
2396                 if (!scripting_ops) {
2397                         fprintf(stderr, "invalid script extension");
2398                         return -1;
2399                 }
2400         }
2401
2402         script_name = strdup(script);
2403
2404         return 0;
2405 }
2406
2407 static int parse_output_fields(const struct option *opt __maybe_unused,
2408                             const char *arg, int unset __maybe_unused)
2409 {
2410         char *tok, *strtok_saveptr = NULL;
2411         int i, imax = ARRAY_SIZE(all_output_options);
2412         int j;
2413         int rc = 0;
2414         char *str = strdup(arg);
2415         int type = -1;
2416         enum { DEFAULT, SET, ADD, REMOVE } change = DEFAULT;
2417
2418         if (!str)
2419                 return -ENOMEM;
2420
2421         /* first word can state for which event type the user is specifying
2422          * the fields. If no type exists, the specified fields apply to all
2423          * event types found in the file minus the invalid fields for a type.
2424          */
2425         tok = strchr(str, ':');
2426         if (tok) {
2427                 *tok = '\0';
2428                 tok++;
2429                 if (!strcmp(str, "hw"))
2430                         type = PERF_TYPE_HARDWARE;
2431                 else if (!strcmp(str, "sw"))
2432                         type = PERF_TYPE_SOFTWARE;
2433                 else if (!strcmp(str, "trace"))
2434                         type = PERF_TYPE_TRACEPOINT;
2435                 else if (!strcmp(str, "raw"))
2436                         type = PERF_TYPE_RAW;
2437                 else if (!strcmp(str, "break"))
2438                         type = PERF_TYPE_BREAKPOINT;
2439                 else if (!strcmp(str, "synth"))
2440                         type = OUTPUT_TYPE_SYNTH;
2441                 else {
2442                         fprintf(stderr, "Invalid event type in field string.\n");
2443                         rc = -EINVAL;
2444                         goto out;
2445                 }
2446
2447                 if (output[type].user_set)
2448                         pr_warning("Overriding previous field request for %s events.\n",
2449                                    event_type(type));
2450
2451                 output[type].fields = 0;
2452                 output[type].user_set = true;
2453                 output[type].wildcard_set = false;
2454
2455         } else {
2456                 tok = str;
2457                 if (strlen(str) == 0) {
2458                         fprintf(stderr,
2459                                 "Cannot set fields to 'none' for all event types.\n");
2460                         rc = -EINVAL;
2461                         goto out;
2462                 }
2463
2464                 /* Don't override defaults for +- */
2465                 if (strchr(str, '+') || strchr(str, '-'))
2466                         goto parse;
2467
2468                 if (output_set_by_user())
2469                         pr_warning("Overriding previous field request for all events.\n");
2470
2471                 for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
2472                         output[j].fields = 0;
2473                         output[j].user_set = true;
2474                         output[j].wildcard_set = true;
2475                 }
2476         }
2477
2478 parse:
2479         for (tok = strtok_r(tok, ",", &strtok_saveptr); tok; tok = strtok_r(NULL, ",", &strtok_saveptr)) {
2480                 if (*tok == '+') {
2481                         if (change == SET)
2482                                 goto out_badmix;
2483                         change = ADD;
2484                         tok++;
2485                 } else if (*tok == '-') {
2486                         if (change == SET)
2487                                 goto out_badmix;
2488                         change = REMOVE;
2489                         tok++;
2490                 } else {
2491                         if (change != SET && change != DEFAULT)
2492                                 goto out_badmix;
2493                         change = SET;
2494                 }
2495
2496                 for (i = 0; i < imax; ++i) {
2497                         if (strcmp(tok, all_output_options[i].str) == 0)
2498                                 break;
2499                 }
2500                 if (i == imax && strcmp(tok, "flags") == 0) {
2501                         print_flags = change == REMOVE ? false : true;
2502                         continue;
2503                 }
2504                 if (i == imax) {
2505                         fprintf(stderr, "Invalid field requested.\n");
2506                         rc = -EINVAL;
2507                         goto out;
2508                 }
2509
2510                 if (type == -1) {
2511                         /* add user option to all events types for
2512                          * which it is valid
2513                          */
2514                         for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
2515                                 if (output[j].invalid_fields & all_output_options[i].field) {
2516                                         pr_warning("\'%s\' not valid for %s events. Ignoring.\n",
2517                                                    all_output_options[i].str, event_type(j));
2518                                 } else {
2519                                         if (change == REMOVE)
2520                                                 output[j].fields &= ~all_output_options[i].field;
2521                                         else
2522                                                 output[j].fields |= all_output_options[i].field;
2523                                         output[j].user_set = true;
2524                                         output[j].wildcard_set = true;
2525                                 }
2526                         }
2527                 } else {
2528                         if (output[type].invalid_fields & all_output_options[i].field) {
2529                                 fprintf(stderr, "\'%s\' not valid for %s events.\n",
2530                                          all_output_options[i].str, event_type(type));
2531
2532                                 rc = -EINVAL;
2533                                 goto out;
2534                         }
2535                         output[type].user_set = true;
2536                         output[type].wildcard_set = true;
2537                 }
2538         }
2539
2540         if (type >= 0) {
2541                 if (output[type].fields == 0) {
2542                         pr_debug("No fields requested for %s type. "
2543                                  "Events will not be displayed.\n", event_type(type));
2544                 }
2545         }
2546         goto out;
2547
2548 out_badmix:
2549         fprintf(stderr, "Cannot mix +-field with overridden fields\n");
2550         rc = -EINVAL;
2551 out:
2552         free(str);
2553         return rc;
2554 }
2555
2556 #define for_each_lang(scripts_path, scripts_dir, lang_dirent)           \
2557         while ((lang_dirent = readdir(scripts_dir)) != NULL)            \
2558                 if ((lang_dirent->d_type == DT_DIR ||                   \
2559                      (lang_dirent->d_type == DT_UNKNOWN &&              \
2560                       is_directory(scripts_path, lang_dirent))) &&      \
2561                     (strcmp(lang_dirent->d_name, ".")) &&               \
2562                     (strcmp(lang_dirent->d_name, "..")))
2563
2564 #define for_each_script(lang_path, lang_dir, script_dirent)             \
2565         while ((script_dirent = readdir(lang_dir)) != NULL)             \
2566                 if (script_dirent->d_type != DT_DIR &&                  \
2567                     (script_dirent->d_type != DT_UNKNOWN ||             \
2568                      !is_directory(lang_path, script_dirent)))
2569
2570
2571 #define RECORD_SUFFIX                   "-record"
2572 #define REPORT_SUFFIX                   "-report"
2573
2574 struct script_desc {
2575         struct list_head        node;
2576         char                    *name;
2577         char                    *half_liner;
2578         char                    *args;
2579 };
2580
2581 static LIST_HEAD(script_descs);
2582
2583 static struct script_desc *script_desc__new(const char *name)
2584 {
2585         struct script_desc *s = zalloc(sizeof(*s));
2586
2587         if (s != NULL && name)
2588                 s->name = strdup(name);
2589
2590         return s;
2591 }
2592
2593 static void script_desc__delete(struct script_desc *s)
2594 {
2595         zfree(&s->name);
2596         zfree(&s->half_liner);
2597         zfree(&s->args);
2598         free(s);
2599 }
2600
2601 static void script_desc__add(struct script_desc *s)
2602 {
2603         list_add_tail(&s->node, &script_descs);
2604 }
2605
2606 static struct script_desc *script_desc__find(const char *name)
2607 {
2608         struct script_desc *s;
2609
2610         list_for_each_entry(s, &script_descs, node)
2611                 if (strcasecmp(s->name, name) == 0)
2612                         return s;
2613         return NULL;
2614 }
2615
2616 static struct script_desc *script_desc__findnew(const char *name)
2617 {
2618         struct script_desc *s = script_desc__find(name);
2619
2620         if (s)
2621                 return s;
2622
2623         s = script_desc__new(name);
2624         if (!s)
2625                 return NULL;
2626
2627         script_desc__add(s);
2628
2629         return s;
2630 }
2631
2632 static const char *ends_with(const char *str, const char *suffix)
2633 {
2634         size_t suffix_len = strlen(suffix);
2635         const char *p = str;
2636
2637         if (strlen(str) > suffix_len) {
2638                 p = str + strlen(str) - suffix_len;
2639                 if (!strncmp(p, suffix, suffix_len))
2640                         return p;
2641         }
2642
2643         return NULL;
2644 }
2645
2646 static int read_script_info(struct script_desc *desc, const char *filename)
2647 {
2648         char line[BUFSIZ], *p;
2649         FILE *fp;
2650
2651         fp = fopen(filename, "r");
2652         if (!fp)
2653                 return -1;
2654
2655         while (fgets(line, sizeof(line), fp)) {
2656                 p = ltrim(line);
2657                 if (strlen(p) == 0)
2658                         continue;
2659                 if (*p != '#')
2660                         continue;
2661                 p++;
2662                 if (strlen(p) && *p == '!')
2663                         continue;
2664
2665                 p = ltrim(p);
2666                 if (strlen(p) && p[strlen(p) - 1] == '\n')
2667                         p[strlen(p) - 1] = '\0';
2668
2669                 if (!strncmp(p, "description:", strlen("description:"))) {
2670                         p += strlen("description:");
2671                         desc->half_liner = strdup(ltrim(p));
2672                         continue;
2673                 }
2674
2675                 if (!strncmp(p, "args:", strlen("args:"))) {
2676                         p += strlen("args:");
2677                         desc->args = strdup(ltrim(p));
2678                         continue;
2679                 }
2680         }
2681
2682         fclose(fp);
2683
2684         return 0;
2685 }
2686
2687 static char *get_script_root(struct dirent *script_dirent, const char *suffix)
2688 {
2689         char *script_root, *str;
2690
2691         script_root = strdup(script_dirent->d_name);
2692         if (!script_root)
2693                 return NULL;
2694
2695         str = (char *)ends_with(script_root, suffix);
2696         if (!str) {
2697                 free(script_root);
2698                 return NULL;
2699         }
2700
2701         *str = '\0';
2702         return script_root;
2703 }
2704
2705 static int list_available_scripts(const struct option *opt __maybe_unused,
2706                                   const char *s __maybe_unused,
2707                                   int unset __maybe_unused)
2708 {
2709         struct dirent *script_dirent, *lang_dirent;
2710         char scripts_path[MAXPATHLEN];
2711         DIR *scripts_dir, *lang_dir;
2712         char script_path[MAXPATHLEN];
2713         char lang_path[MAXPATHLEN];
2714         struct script_desc *desc;
2715         char first_half[BUFSIZ];
2716         char *script_root;
2717
2718         snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2719
2720         scripts_dir = opendir(scripts_path);
2721         if (!scripts_dir) {
2722                 fprintf(stdout,
2723                         "open(%s) failed.\n"
2724                         "Check \"PERF_EXEC_PATH\" env to set scripts dir.\n",
2725                         scripts_path);
2726                 exit(-1);
2727         }
2728
2729         for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2730                 scnprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
2731                           lang_dirent->d_name);
2732                 lang_dir = opendir(lang_path);
2733                 if (!lang_dir)
2734                         continue;
2735
2736                 for_each_script(lang_path, lang_dir, script_dirent) {
2737                         script_root = get_script_root(script_dirent, REPORT_SUFFIX);
2738                         if (script_root) {
2739                                 desc = script_desc__findnew(script_root);
2740                                 scnprintf(script_path, MAXPATHLEN, "%s/%s",
2741                                           lang_path, script_dirent->d_name);
2742                                 read_script_info(desc, script_path);
2743                                 free(script_root);
2744                         }
2745                 }
2746         }
2747
2748         fprintf(stdout, "List of available trace scripts:\n");
2749         list_for_each_entry(desc, &script_descs, node) {
2750                 sprintf(first_half, "%s %s", desc->name,
2751                         desc->args ? desc->args : "");
2752                 fprintf(stdout, "  %-36s %s\n", first_half,
2753                         desc->half_liner ? desc->half_liner : "");
2754         }
2755
2756         exit(0);
2757 }
2758
2759 /*
2760  * Some scripts specify the required events in their "xxx-record" file,
2761  * this function will check if the events in perf.data match those
2762  * mentioned in the "xxx-record".
2763  *
2764  * Fixme: All existing "xxx-record" are all in good formats "-e event ",
2765  * which is covered well now. And new parsing code should be added to
2766  * cover the future complexing formats like event groups etc.
2767  */
2768 static int check_ev_match(char *dir_name, char *scriptname,
2769                         struct perf_session *session)
2770 {
2771         char filename[MAXPATHLEN], evname[128];
2772         char line[BUFSIZ], *p;
2773         struct perf_evsel *pos;
2774         int match, len;
2775         FILE *fp;
2776
2777         scnprintf(filename, MAXPATHLEN, "%s/bin/%s-record", dir_name, scriptname);
2778
2779         fp = fopen(filename, "r");
2780         if (!fp)
2781                 return -1;
2782
2783         while (fgets(line, sizeof(line), fp)) {
2784                 p = ltrim(line);
2785                 if (*p == '#')
2786                         continue;
2787
2788                 while (strlen(p)) {
2789                         p = strstr(p, "-e");
2790                         if (!p)
2791                                 break;
2792
2793                         p += 2;
2794                         p = ltrim(p);
2795                         len = strcspn(p, " \t");
2796                         if (!len)
2797                                 break;
2798
2799                         snprintf(evname, len + 1, "%s", p);
2800
2801                         match = 0;
2802                         evlist__for_each_entry(session->evlist, pos) {
2803                                 if (!strcmp(perf_evsel__name(pos), evname)) {
2804                                         match = 1;
2805                                         break;
2806                                 }
2807                         }
2808
2809                         if (!match) {
2810                                 fclose(fp);
2811                                 return -1;
2812                         }
2813                 }
2814         }
2815
2816         fclose(fp);
2817         return 0;
2818 }
2819
2820 /*
2821  * Return -1 if none is found, otherwise the actual scripts number.
2822  *
2823  * Currently the only user of this function is the script browser, which
2824  * will list all statically runnable scripts, select one, execute it and
2825  * show the output in a perf browser.
2826  */
2827 int find_scripts(char **scripts_array, char **scripts_path_array)
2828 {
2829         struct dirent *script_dirent, *lang_dirent;
2830         char scripts_path[MAXPATHLEN], lang_path[MAXPATHLEN];
2831         DIR *scripts_dir, *lang_dir;
2832         struct perf_session *session;
2833         struct perf_data data = {
2834                 .file      = {
2835                         .path = input_name,
2836                 },
2837                 .mode      = PERF_DATA_MODE_READ,
2838         };
2839         char *temp;
2840         int i = 0;
2841
2842         session = perf_session__new(&data, false, NULL);
2843         if (!session)
2844                 return -1;
2845
2846         snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2847
2848         scripts_dir = opendir(scripts_path);
2849         if (!scripts_dir) {
2850                 perf_session__delete(session);
2851                 return -1;
2852         }
2853
2854         for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2855                 scnprintf(lang_path, MAXPATHLEN, "%s/%s", scripts_path,
2856                           lang_dirent->d_name);
2857 #ifndef HAVE_LIBPERL_SUPPORT
2858                 if (strstr(lang_path, "perl"))
2859                         continue;
2860 #endif
2861 #ifndef HAVE_LIBPYTHON_SUPPORT
2862                 if (strstr(lang_path, "python"))
2863                         continue;
2864 #endif
2865
2866                 lang_dir = opendir(lang_path);
2867                 if (!lang_dir)
2868                         continue;
2869
2870                 for_each_script(lang_path, lang_dir, script_dirent) {
2871                         /* Skip those real time scripts: xxxtop.p[yl] */
2872                         if (strstr(script_dirent->d_name, "top."))
2873                                 continue;
2874                         sprintf(scripts_path_array[i], "%s/%s", lang_path,
2875                                 script_dirent->d_name);
2876                         temp = strchr(script_dirent->d_name, '.');
2877                         snprintf(scripts_array[i],
2878                                 (temp - script_dirent->d_name) + 1,
2879                                 "%s", script_dirent->d_name);
2880
2881                         if (check_ev_match(lang_path,
2882                                         scripts_array[i], session))
2883                                 continue;
2884
2885                         i++;
2886                 }
2887                 closedir(lang_dir);
2888         }
2889
2890         closedir(scripts_dir);
2891         perf_session__delete(session);
2892         return i;
2893 }
2894
2895 static char *get_script_path(const char *script_root, const char *suffix)
2896 {
2897         struct dirent *script_dirent, *lang_dirent;
2898         char scripts_path[MAXPATHLEN];
2899         char script_path[MAXPATHLEN];
2900         DIR *scripts_dir, *lang_dir;
2901         char lang_path[MAXPATHLEN];
2902         char *__script_root;
2903
2904         snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2905
2906         scripts_dir = opendir(scripts_path);
2907         if (!scripts_dir)
2908                 return NULL;
2909
2910         for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2911                 scnprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
2912                           lang_dirent->d_name);
2913                 lang_dir = opendir(lang_path);
2914                 if (!lang_dir)
2915                         continue;
2916
2917                 for_each_script(lang_path, lang_dir, script_dirent) {
2918                         __script_root = get_script_root(script_dirent, suffix);
2919                         if (__script_root && !strcmp(script_root, __script_root)) {
2920                                 free(__script_root);
2921                                 closedir(lang_dir);
2922                                 closedir(scripts_dir);
2923                                 scnprintf(script_path, MAXPATHLEN, "%s/%s",
2924                                           lang_path, script_dirent->d_name);
2925                                 return strdup(script_path);
2926                         }
2927                         free(__script_root);
2928                 }
2929                 closedir(lang_dir);
2930         }
2931         closedir(scripts_dir);
2932
2933         return NULL;
2934 }
2935
2936 static bool is_top_script(const char *script_path)
2937 {
2938         return ends_with(script_path, "top") == NULL ? false : true;
2939 }
2940
2941 static int has_required_arg(char *script_path)
2942 {
2943         struct script_desc *desc;
2944         int n_args = 0;
2945         char *p;
2946
2947         desc = script_desc__new(NULL);
2948
2949         if (read_script_info(desc, script_path))
2950                 goto out;
2951
2952         if (!desc->args)
2953                 goto out;
2954
2955         for (p = desc->args; *p; p++)
2956                 if (*p == '<')
2957                         n_args++;
2958 out:
2959         script_desc__delete(desc);
2960
2961         return n_args;
2962 }
2963
2964 static int have_cmd(int argc, const char **argv)
2965 {
2966         char **__argv = malloc(sizeof(const char *) * argc);
2967
2968         if (!__argv) {
2969                 pr_err("malloc failed\n");
2970                 return -1;
2971         }
2972
2973         memcpy(__argv, argv, sizeof(const char *) * argc);
2974         argc = parse_options(argc, (const char **)__argv, record_options,
2975                              NULL, PARSE_OPT_STOP_AT_NON_OPTION);
2976         free(__argv);
2977
2978         system_wide = (argc == 0);
2979
2980         return 0;
2981 }
2982
2983 static void script__setup_sample_type(struct perf_script *script)
2984 {
2985         struct perf_session *session = script->session;
2986         u64 sample_type = perf_evlist__combined_sample_type(session->evlist);
2987
2988         if (symbol_conf.use_callchain || symbol_conf.cumulate_callchain) {
2989                 if ((sample_type & PERF_SAMPLE_REGS_USER) &&
2990                     (sample_type & PERF_SAMPLE_STACK_USER)) {
2991                         callchain_param.record_mode = CALLCHAIN_DWARF;
2992                         dwarf_callchain_users = true;
2993                 } else if (sample_type & PERF_SAMPLE_BRANCH_STACK)
2994                         callchain_param.record_mode = CALLCHAIN_LBR;
2995                 else
2996                         callchain_param.record_mode = CALLCHAIN_FP;
2997         }
2998 }
2999
3000 static int process_stat_round_event(struct perf_session *session,
3001                                     union perf_event *event)
3002 {
3003         struct stat_round_event *round = &event->stat_round;
3004         struct perf_evsel *counter;
3005
3006         evlist__for_each_entry(session->evlist, counter) {
3007                 perf_stat_process_counter(&stat_config, counter);
3008                 process_stat(counter, round->time);
3009         }
3010
3011         process_stat_interval(round->time);
3012         return 0;
3013 }
3014
3015 static int process_stat_config_event(struct perf_session *session __maybe_unused,
3016                                      union perf_event *event)
3017 {
3018         perf_event__read_stat_config(&stat_config, &event->stat_config);
3019         return 0;
3020 }
3021
3022 static int set_maps(struct perf_script *script)
3023 {
3024         struct perf_evlist *evlist = script->session->evlist;
3025
3026         if (!script->cpus || !script->threads)
3027                 return 0;
3028
3029         if (WARN_ONCE(script->allocated, "stats double allocation\n"))
3030                 return -EINVAL;
3031
3032         perf_evlist__set_maps(evlist, script->cpus, script->threads);
3033
3034         if (perf_evlist__alloc_stats(evlist, true))
3035                 return -ENOMEM;
3036
3037         script->allocated = true;
3038         return 0;
3039 }
3040
3041 static
3042 int process_thread_map_event(struct perf_session *session,
3043                              union perf_event *event)
3044 {
3045         struct perf_tool *tool = session->tool;
3046         struct perf_script *script = container_of(tool, struct perf_script, tool);
3047
3048         if (script->threads) {
3049                 pr_warning("Extra thread map event, ignoring.\n");
3050                 return 0;
3051         }
3052
3053         script->threads = thread_map__new_event(&event->thread_map);
3054         if (!script->threads)
3055                 return -ENOMEM;
3056
3057         return set_maps(script);
3058 }
3059
3060 static
3061 int process_cpu_map_event(struct perf_session *session,
3062                           union perf_event *event)
3063 {
3064         struct perf_tool *tool = session->tool;
3065         struct perf_script *script = container_of(tool, struct perf_script, tool);
3066
3067         if (script->cpus) {
3068                 pr_warning("Extra cpu map event, ignoring.\n");
3069                 return 0;
3070         }
3071
3072         script->cpus = cpu_map__new_data(&event->cpu_map.data);
3073         if (!script->cpus)
3074                 return -ENOMEM;
3075
3076         return set_maps(script);
3077 }
3078
3079 static int process_feature_event(struct perf_session *session,
3080                                  union perf_event *event)
3081 {
3082         if (event->feat.feat_id < HEADER_LAST_FEATURE)
3083                 return perf_event__process_feature(session, event);
3084         return 0;
3085 }
3086
3087 #ifdef HAVE_AUXTRACE_SUPPORT
3088 static int perf_script__process_auxtrace_info(struct perf_session *session,
3089                                               union perf_event *event)
3090 {
3091         struct perf_tool *tool = session->tool;
3092
3093         int ret = perf_event__process_auxtrace_info(session, event);
3094
3095         if (ret == 0) {
3096                 struct perf_script *script = container_of(tool, struct perf_script, tool);
3097
3098                 ret = perf_script__setup_per_event_dump(script);
3099         }
3100
3101         return ret;
3102 }
3103 #else
3104 #define perf_script__process_auxtrace_info 0
3105 #endif
3106
3107 static int parse_insn_trace(const struct option *opt __maybe_unused,
3108                             const char *str __maybe_unused,
3109                             int unset __maybe_unused)
3110 {
3111         parse_output_fields(NULL, "+insn,-event,-period", 0);
3112         itrace_parse_synth_opts(opt, "i0ns", 0);
3113         nanosecs = true;
3114         return 0;
3115 }
3116
3117 static int parse_xed(const struct option *opt __maybe_unused,
3118                      const char *str __maybe_unused,
3119                      int unset __maybe_unused)
3120 {
3121         force_pager("xed -F insn: -A -64 | less");
3122         return 0;
3123 }
3124
3125 int cmd_script(int argc, const char **argv)
3126 {
3127         bool show_full_info = false;
3128         bool header = false;
3129         bool header_only = false;
3130         bool script_started = false;
3131         char *rec_script_path = NULL;
3132         char *rep_script_path = NULL;
3133         struct perf_session *session;
3134         struct itrace_synth_opts itrace_synth_opts = { .set = false, };
3135         char *script_path = NULL;
3136         const char **__argv;
3137         int i, j, err = 0;
3138         struct perf_script script = {
3139                 .tool = {
3140                         .sample          = process_sample_event,
3141                         .mmap            = perf_event__process_mmap,
3142                         .mmap2           = perf_event__process_mmap2,
3143                         .comm            = perf_event__process_comm,
3144                         .namespaces      = perf_event__process_namespaces,
3145                         .exit            = perf_event__process_exit,
3146                         .fork            = perf_event__process_fork,
3147                         .attr            = process_attr,
3148                         .event_update   = perf_event__process_event_update,
3149                         .tracing_data    = perf_event__process_tracing_data,
3150                         .feature         = process_feature_event,
3151                         .build_id        = perf_event__process_build_id,
3152                         .id_index        = perf_event__process_id_index,
3153                         .auxtrace_info   = perf_script__process_auxtrace_info,
3154                         .auxtrace        = perf_event__process_auxtrace,
3155                         .auxtrace_error  = perf_event__process_auxtrace_error,
3156                         .stat            = perf_event__process_stat_event,
3157                         .stat_round      = process_stat_round_event,
3158                         .stat_config     = process_stat_config_event,
3159                         .thread_map      = process_thread_map_event,
3160                         .cpu_map         = process_cpu_map_event,
3161                         .ordered_events  = true,
3162                         .ordering_requires_timestamps = true,
3163                 },
3164         };
3165         struct perf_data data = {
3166                 .mode = PERF_DATA_MODE_READ,
3167         };
3168         const struct option options[] = {
3169         OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
3170                     "dump raw trace in ASCII"),
3171         OPT_INCR('v', "verbose", &verbose,
3172                  "be more verbose (show symbol address, etc)"),
3173         OPT_BOOLEAN('L', "Latency", &latency_format,
3174                     "show latency attributes (irqs/preemption disabled, etc)"),
3175         OPT_CALLBACK_NOOPT('l', "list", NULL, NULL, "list available scripts",
3176                            list_available_scripts),
3177         OPT_CALLBACK('s', "script", NULL, "name",
3178                      "script file name (lang:script name, script name, or *)",
3179                      parse_scriptname),
3180         OPT_STRING('g', "gen-script", &generate_script_lang, "lang",
3181                    "generate perf-script.xx script in specified language"),
3182         OPT_STRING('i', "input", &input_name, "file", "input file name"),
3183         OPT_BOOLEAN('d', "debug-mode", &debug_mode,
3184                    "do various checks like samples ordering and lost events"),
3185         OPT_BOOLEAN(0, "header", &header, "Show data header."),
3186         OPT_BOOLEAN(0, "header-only", &header_only, "Show only data header."),
3187         OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
3188                    "file", "vmlinux pathname"),
3189         OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
3190                    "file", "kallsyms pathname"),
3191         OPT_BOOLEAN('G', "hide-call-graph", &no_callchain,
3192                     "When printing symbols do not display call chain"),
3193         OPT_CALLBACK(0, "symfs", NULL, "directory",
3194                      "Look for files with symbols relative to this directory",
3195                      symbol__config_symfs),
3196         OPT_CALLBACK('F', "fields", NULL, "str",
3197                      "comma separated output fields prepend with 'type:'. "
3198                      "+field to add and -field to remove."
3199                      "Valid types: hw,sw,trace,raw,synth. "
3200                      "Fields: comm,tid,pid,time,cpu,event,trace,ip,sym,dso,"
3201                      "addr,symoff,srcline,period,iregs,uregs,brstack,"
3202                      "brstacksym,flags,bpf-output,brstackinsn,brstackoff,"
3203                      "callindent,insn,insnlen,synth,phys_addr,metric,misc",
3204                      parse_output_fields),
3205         OPT_BOOLEAN('a', "all-cpus", &system_wide,
3206                     "system-wide collection from all CPUs"),
3207         OPT_STRING('S', "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
3208                    "only consider these symbols"),
3209         OPT_CALLBACK_OPTARG(0, "insn-trace", &itrace_synth_opts, NULL, NULL,
3210                         "Decode instructions from itrace", parse_insn_trace),
3211         OPT_CALLBACK_OPTARG(0, "xed", NULL, NULL, NULL,
3212                         "Run xed disassembler on output", parse_xed),
3213         OPT_STRING(0, "stop-bt", &symbol_conf.bt_stop_list_str, "symbol[,symbol...]",
3214                    "Stop display of callgraph at these symbols"),
3215         OPT_STRING('C', "cpu", &cpu_list, "cpu", "list of cpus to profile"),
3216         OPT_STRING('c', "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
3217                    "only display events for these comms"),
3218         OPT_STRING(0, "pid", &symbol_conf.pid_list_str, "pid[,pid...]",
3219                    "only consider symbols in these pids"),
3220         OPT_STRING(0, "tid", &symbol_conf.tid_list_str, "tid[,tid...]",
3221                    "only consider symbols in these tids"),
3222         OPT_UINTEGER(0, "max-stack", &scripting_max_stack,
3223                      "Set the maximum stack depth when parsing the callchain, "
3224                      "anything beyond the specified depth will be ignored. "
3225                      "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
3226         OPT_BOOLEAN('I', "show-info", &show_full_info,
3227                     "display extended information from perf.data file"),
3228         OPT_BOOLEAN('\0', "show-kernel-path", &symbol_conf.show_kernel_path,
3229                     "Show the path of [kernel.kallsyms]"),
3230         OPT_BOOLEAN('\0', "show-task-events", &script.show_task_events,
3231                     "Show the fork/comm/exit events"),
3232         OPT_BOOLEAN('\0', "show-mmap-events", &script.show_mmap_events,
3233                     "Show the mmap events"),
3234         OPT_BOOLEAN('\0', "show-switch-events", &script.show_switch_events,
3235                     "Show context switch events (if recorded)"),
3236         OPT_BOOLEAN('\0', "show-namespace-events", &script.show_namespace_events,
3237                     "Show namespace events (if recorded)"),
3238         OPT_BOOLEAN('\0', "show-lost-events", &script.show_lost_events,
3239                     "Show lost events (if recorded)"),
3240         OPT_BOOLEAN('\0', "show-round-events", &script.show_round_events,
3241                     "Show round events (if recorded)"),
3242         OPT_BOOLEAN('\0', "per-event-dump", &script.per_event_dump,
3243                     "Dump trace output to files named by the monitored events"),
3244         OPT_BOOLEAN('f', "force", &symbol_conf.force, "don't complain, do it"),
3245         OPT_INTEGER(0, "max-blocks", &max_blocks,
3246                     "Maximum number of code blocks to dump with brstackinsn"),
3247         OPT_BOOLEAN(0, "ns", &nanosecs,
3248                     "Use 9 decimal places when displaying time"),
3249         OPT_CALLBACK_OPTARG(0, "itrace", &itrace_synth_opts, NULL, "opts",
3250                             "Instruction Tracing options\n" ITRACE_HELP,
3251                             itrace_parse_synth_opts),
3252         OPT_BOOLEAN(0, "full-source-path", &srcline_full_filename,
3253                         "Show full source file name path for source lines"),
3254         OPT_BOOLEAN(0, "demangle", &symbol_conf.demangle,
3255                         "Enable symbol demangling"),
3256         OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
3257                         "Enable kernel symbol demangling"),
3258         OPT_STRING(0, "time", &script.time_str, "str",
3259                    "Time span of interest (start,stop)"),
3260         OPT_BOOLEAN(0, "inline", &symbol_conf.inline_name,
3261                     "Show inline function"),
3262         OPT_END()
3263         };
3264         const char * const script_subcommands[] = { "record", "report", NULL };
3265         const char *script_usage[] = {
3266                 "perf script [<options>]",
3267                 "perf script [<options>] record <script> [<record-options>] <command>",
3268                 "perf script [<options>] report <script> [script-args]",
3269                 "perf script [<options>] <script> [<record-options>] <command>",
3270                 "perf script [<options>] <top-script> [script-args]",
3271                 NULL
3272         };
3273
3274         perf_set_singlethreaded();
3275
3276         setup_scripting();
3277
3278         argc = parse_options_subcommand(argc, argv, options, script_subcommands, script_usage,
3279                              PARSE_OPT_STOP_AT_NON_OPTION);
3280
3281         data.file.path = input_name;
3282         data.force     = symbol_conf.force;
3283
3284         if (argc > 1 && !strncmp(argv[0], "rec", strlen("rec"))) {
3285                 rec_script_path = get_script_path(argv[1], RECORD_SUFFIX);
3286                 if (!rec_script_path)
3287                         return cmd_record(argc, argv);
3288         }
3289
3290         if (argc > 1 && !strncmp(argv[0], "rep", strlen("rep"))) {
3291                 rep_script_path = get_script_path(argv[1], REPORT_SUFFIX);
3292                 if (!rep_script_path) {
3293                         fprintf(stderr,
3294                                 "Please specify a valid report script"
3295                                 "(see 'perf script -l' for listing)\n");
3296                         return -1;
3297                 }
3298         }
3299
3300         if (itrace_synth_opts.callchain &&
3301             itrace_synth_opts.callchain_sz > scripting_max_stack)
3302                 scripting_max_stack = itrace_synth_opts.callchain_sz;
3303
3304         /* make sure PERF_EXEC_PATH is set for scripts */
3305         set_argv_exec_path(get_argv_exec_path());
3306
3307         if (argc && !script_name && !rec_script_path && !rep_script_path) {
3308                 int live_pipe[2];
3309                 int rep_args;
3310                 pid_t pid;
3311
3312                 rec_script_path = get_script_path(argv[0], RECORD_SUFFIX);
3313                 rep_script_path = get_script_path(argv[0], REPORT_SUFFIX);
3314
3315                 if (!rec_script_path && !rep_script_path) {
3316                         usage_with_options_msg(script_usage, options,
3317                                 "Couldn't find script `%s'\n\n See perf"
3318                                 " script -l for available scripts.\n", argv[0]);
3319                 }
3320
3321                 if (is_top_script(argv[0])) {
3322                         rep_args = argc - 1;
3323                 } else {
3324                         int rec_args;
3325
3326                         rep_args = has_required_arg(rep_script_path);
3327                         rec_args = (argc - 1) - rep_args;
3328                         if (rec_args < 0) {
3329                                 usage_with_options_msg(script_usage, options,
3330                                         "`%s' script requires options."
3331                                         "\n\n See perf script -l for available "
3332                                         "scripts and options.\n", argv[0]);
3333                         }
3334                 }
3335
3336                 if (pipe(live_pipe) < 0) {
3337                         perror("failed to create pipe");
3338                         return -1;
3339                 }
3340
3341                 pid = fork();
3342                 if (pid < 0) {
3343                         perror("failed to fork");
3344                         return -1;
3345                 }
3346
3347                 if (!pid) {
3348                         j = 0;
3349
3350                         dup2(live_pipe[1], 1);
3351                         close(live_pipe[0]);
3352
3353                         if (is_top_script(argv[0])) {
3354                                 system_wide = true;
3355                         } else if (!system_wide) {
3356                                 if (have_cmd(argc - rep_args, &argv[rep_args]) != 0) {
3357                                         err = -1;
3358                                         goto out;
3359                                 }
3360                         }
3361
3362                         __argv = malloc((argc + 6) * sizeof(const char *));
3363                         if (!__argv) {
3364                                 pr_err("malloc failed\n");
3365                                 err = -ENOMEM;
3366                                 goto out;
3367                         }
3368
3369                         __argv[j++] = "/bin/sh";
3370                         __argv[j++] = rec_script_path;
3371                         if (system_wide)
3372                                 __argv[j++] = "-a";
3373                         __argv[j++] = "-q";
3374                         __argv[j++] = "-o";
3375                         __argv[j++] = "-";
3376                         for (i = rep_args + 1; i < argc; i++)
3377                                 __argv[j++] = argv[i];
3378                         __argv[j++] = NULL;
3379
3380                         execvp("/bin/sh", (char **)__argv);
3381                         free(__argv);
3382                         exit(-1);
3383                 }
3384
3385                 dup2(live_pipe[0], 0);
3386                 close(live_pipe[1]);
3387
3388                 __argv = malloc((argc + 4) * sizeof(const char *));
3389                 if (!__argv) {
3390                         pr_err("malloc failed\n");
3391                         err = -ENOMEM;
3392                         goto out;
3393                 }
3394
3395                 j = 0;
3396                 __argv[j++] = "/bin/sh";
3397                 __argv[j++] = rep_script_path;
3398                 for (i = 1; i < rep_args + 1; i++)
3399                         __argv[j++] = argv[i];
3400                 __argv[j++] = "-i";
3401                 __argv[j++] = "-";
3402                 __argv[j++] = NULL;
3403
3404                 execvp("/bin/sh", (char **)__argv);
3405                 free(__argv);
3406                 exit(-1);
3407         }
3408
3409         if (rec_script_path)
3410                 script_path = rec_script_path;
3411         if (rep_script_path)
3412                 script_path = rep_script_path;
3413
3414         if (script_path) {
3415                 j = 0;
3416
3417                 if (!rec_script_path)
3418                         system_wide = false;
3419                 else if (!system_wide) {
3420                         if (have_cmd(argc - 1, &argv[1]) != 0) {
3421                                 err = -1;
3422                                 goto out;
3423                         }
3424                 }
3425
3426                 __argv = malloc((argc + 2) * sizeof(const char *));
3427                 if (!__argv) {
3428                         pr_err("malloc failed\n");
3429                         err = -ENOMEM;
3430                         goto out;
3431                 }
3432
3433                 __argv[j++] = "/bin/sh";
3434                 __argv[j++] = script_path;
3435                 if (system_wide)
3436                         __argv[j++] = "-a";
3437                 for (i = 2; i < argc; i++)
3438                         __argv[j++] = argv[i];
3439                 __argv[j++] = NULL;
3440
3441                 execvp("/bin/sh", (char **)__argv);
3442                 free(__argv);
3443                 exit(-1);
3444         }
3445
3446         if (!script_name) {
3447                 setup_pager();
3448                 use_browser = 0;
3449         }
3450
3451         session = perf_session__new(&data, false, &script.tool);
3452         if (session == NULL)
3453                 return -1;
3454
3455         if (header || header_only) {
3456                 script.tool.show_feat_hdr = SHOW_FEAT_HEADER;
3457                 perf_session__fprintf_info(session, stdout, show_full_info);
3458                 if (header_only)
3459                         goto out_delete;
3460         }
3461         if (show_full_info)
3462                 script.tool.show_feat_hdr = SHOW_FEAT_HEADER_FULL_INFO;
3463
3464         if (symbol__init(&session->header.env) < 0)
3465                 goto out_delete;
3466
3467         script.session = session;
3468         script__setup_sample_type(&script);
3469
3470         if (output[PERF_TYPE_HARDWARE].fields & PERF_OUTPUT_CALLINDENT)
3471                 itrace_synth_opts.thread_stack = true;
3472
3473         session->itrace_synth_opts = &itrace_synth_opts;
3474
3475         if (cpu_list) {
3476                 err = perf_session__cpu_bitmap(session, cpu_list, cpu_bitmap);
3477                 if (err < 0)
3478                         goto out_delete;
3479                 itrace_synth_opts.cpu_bitmap = cpu_bitmap;
3480         }
3481
3482         if (!no_callchain)
3483                 symbol_conf.use_callchain = true;
3484         else
3485                 symbol_conf.use_callchain = false;
3486
3487         if (session->tevent.pevent &&
3488             tep_set_function_resolver(session->tevent.pevent,
3489                                       machine__resolve_kernel_addr,
3490                                       &session->machines.host) < 0) {
3491                 pr_err("%s: failed to set libtraceevent function resolver\n", __func__);
3492                 err = -1;
3493                 goto out_delete;
3494         }
3495
3496         if (generate_script_lang) {
3497                 struct stat perf_stat;
3498                 int input;
3499
3500                 if (output_set_by_user()) {
3501                         fprintf(stderr,
3502                                 "custom fields not supported for generated scripts");
3503                         err = -EINVAL;
3504                         goto out_delete;
3505                 }
3506
3507                 input = open(data.file.path, O_RDONLY); /* input_name */
3508                 if (input < 0) {
3509                         err = -errno;
3510                         perror("failed to open file");
3511                         goto out_delete;
3512                 }
3513
3514                 err = fstat(input, &perf_stat);
3515                 if (err < 0) {
3516                         perror("failed to stat file");
3517                         goto out_delete;
3518                 }
3519
3520                 if (!perf_stat.st_size) {
3521                         fprintf(stderr, "zero-sized file, nothing to do!\n");
3522                         goto out_delete;
3523                 }
3524
3525                 scripting_ops = script_spec__lookup(generate_script_lang);
3526                 if (!scripting_ops) {
3527                         fprintf(stderr, "invalid language specifier");
3528                         err = -ENOENT;
3529                         goto out_delete;
3530                 }
3531
3532                 err = scripting_ops->generate_script(session->tevent.pevent,
3533                                                      "perf-script");
3534                 goto out_delete;
3535         }
3536
3537         if (script_name) {
3538                 err = scripting_ops->start_script(script_name, argc, argv);
3539                 if (err)
3540                         goto out_delete;
3541                 pr_debug("perf script started with script %s\n\n", script_name);
3542                 script_started = true;
3543         }
3544
3545
3546         err = perf_session__check_output_opt(session);
3547         if (err < 0)
3548                 goto out_delete;
3549
3550         script.ptime_range = perf_time__range_alloc(script.time_str,
3551                                                     &script.range_size);
3552         if (!script.ptime_range) {
3553                 err = -ENOMEM;
3554                 goto out_delete;
3555         }
3556
3557         /* needs to be parsed after looking up reference time */
3558         if (perf_time__parse_str(script.ptime_range, script.time_str) != 0) {
3559                 if (session->evlist->first_sample_time == 0 &&
3560                     session->evlist->last_sample_time == 0) {
3561                         pr_err("HINT: no first/last sample time found in perf data.\n"
3562                                "Please use latest perf binary to execute 'perf record'\n"
3563                                "(if '--buildid-all' is enabled, please set '--timestamp-boundary').\n");
3564                         err = -EINVAL;
3565                         goto out_delete;
3566                 }
3567
3568                 script.range_num = perf_time__percent_parse_str(
3569                                         script.ptime_range, script.range_size,
3570                                         script.time_str,
3571                                         session->evlist->first_sample_time,
3572                                         session->evlist->last_sample_time);
3573
3574                 if (script.range_num < 0) {
3575                         pr_err("Invalid time string\n");
3576                         err = -EINVAL;
3577                         goto out_delete;
3578                 }
3579         } else {
3580                 script.range_num = 1;
3581         }
3582
3583         err = __cmd_script(&script);
3584
3585         flush_scripting();
3586
3587 out_delete:
3588         zfree(&script.ptime_range);
3589
3590         perf_evlist__free_stats(session->evlist);
3591         perf_session__delete(session);
3592
3593         if (script_started)
3594                 cleanup_scripting();
3595 out:
3596         return err;
3597 }