can: flexcan: Add provision for variable payload size
[linux-2.6-microblaze.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, int *total_cycles)
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                 *total_cycles += en->flags.cycles;
926                 printed += fprintf(fp, " %d cycles [%d]", en->flags.cycles, *total_cycles);
927                 if (insn)
928                         printed += fprintf(fp, " %.2f IPC", (float)insn / en->flags.cycles);
929         }
930         return printed + fprintf(fp, "\n");
931 }
932
933 static int ip__fprintf_sym(uint64_t addr, struct thread *thread,
934                            u8 cpumode, int cpu, struct symbol **lastsym,
935                            struct perf_event_attr *attr, FILE *fp)
936 {
937         struct addr_location al;
938         int off, printed = 0;
939
940         memset(&al, 0, sizeof(al));
941
942         thread__find_map(thread, cpumode, addr, &al);
943
944         if ((*lastsym) && al.addr >= (*lastsym)->start && al.addr < (*lastsym)->end)
945                 return 0;
946
947         al.cpu = cpu;
948         al.sym = NULL;
949         if (al.map)
950                 al.sym = map__find_symbol(al.map, al.addr);
951
952         if (!al.sym)
953                 return 0;
954
955         if (al.addr < al.sym->end)
956                 off = al.addr - al.sym->start;
957         else
958                 off = al.addr - al.map->start - al.sym->start;
959         printed += fprintf(fp, "\t%s", al.sym->name);
960         if (off)
961                 printed += fprintf(fp, "%+d", off);
962         printed += fprintf(fp, ":");
963         if (PRINT_FIELD(SRCLINE))
964                 printed += map__fprintf_srcline(al.map, al.addr, "\t", fp);
965         printed += fprintf(fp, "\n");
966         *lastsym = al.sym;
967
968         return printed;
969 }
970
971 static int perf_sample__fprintf_brstackinsn(struct perf_sample *sample,
972                                             struct thread *thread,
973                                             struct perf_event_attr *attr,
974                                             struct machine *machine, FILE *fp)
975 {
976         struct branch_stack *br = sample->branch_stack;
977         u64 start, end;
978         int i, insn, len, nr, ilen, printed = 0;
979         struct perf_insn x;
980         u8 buffer[MAXBB];
981         unsigned off;
982         struct symbol *lastsym = NULL;
983         int total_cycles = 0;
984
985         if (!(br && br->nr))
986                 return 0;
987         nr = br->nr;
988         if (max_blocks && nr > max_blocks + 1)
989                 nr = max_blocks + 1;
990
991         x.thread = thread;
992         x.cpu = sample->cpu;
993
994         printed += fprintf(fp, "%c", '\n');
995
996         /* Handle first from jump, of which we don't know the entry. */
997         len = grab_bb(buffer, br->entries[nr-1].from,
998                         br->entries[nr-1].from,
999                         machine, thread, &x.is64bit, &x.cpumode, false);
1000         if (len > 0) {
1001                 printed += ip__fprintf_sym(br->entries[nr - 1].from, thread,
1002                                            x.cpumode, x.cpu, &lastsym, attr, fp);
1003                 printed += ip__fprintf_jump(br->entries[nr - 1].from, &br->entries[nr - 1],
1004                                             &x, buffer, len, 0, fp, &total_cycles);
1005         }
1006
1007         /* Print all blocks */
1008         for (i = nr - 2; i >= 0; i--) {
1009                 if (br->entries[i].from || br->entries[i].to)
1010                         pr_debug("%d: %" PRIx64 "-%" PRIx64 "\n", i,
1011                                  br->entries[i].from,
1012                                  br->entries[i].to);
1013                 start = br->entries[i + 1].to;
1014                 end   = br->entries[i].from;
1015
1016                 len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, false);
1017                 /* Patch up missing kernel transfers due to ring filters */
1018                 if (len == -ENXIO && i > 0) {
1019                         end = br->entries[--i].from;
1020                         pr_debug("\tpatching up to %" PRIx64 "-%" PRIx64 "\n", start, end);
1021                         len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, false);
1022                 }
1023                 if (len <= 0)
1024                         continue;
1025
1026                 insn = 0;
1027                 for (off = 0;; off += ilen) {
1028                         uint64_t ip = start + off;
1029
1030                         printed += ip__fprintf_sym(ip, thread, x.cpumode, x.cpu, &lastsym, attr, fp);
1031                         if (ip == end) {
1032                                 printed += ip__fprintf_jump(ip, &br->entries[i], &x, buffer + off, len - off, insn, fp,
1033                                                             &total_cycles);
1034                                 break;
1035                         } else {
1036                                 printed += fprintf(fp, "\t%016" PRIx64 "\t%s\n", ip,
1037                                                    dump_insn(&x, ip, buffer + off, len - off, &ilen));
1038                                 if (ilen == 0)
1039                                         break;
1040                                 insn++;
1041                         }
1042                 }
1043         }
1044
1045         /*
1046          * Hit the branch? In this case we are already done, and the target
1047          * has not been executed yet.
1048          */
1049         if (br->entries[0].from == sample->ip)
1050                 goto out;
1051         if (br->entries[0].flags.abort)
1052                 goto out;
1053
1054         /*
1055          * Print final block upto sample
1056          */
1057         start = br->entries[0].to;
1058         end = sample->ip;
1059         len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, true);
1060         printed += ip__fprintf_sym(start, thread, x.cpumode, x.cpu, &lastsym, attr, fp);
1061         if (len <= 0) {
1062                 /* Print at least last IP if basic block did not work */
1063                 len = grab_bb(buffer, sample->ip, sample->ip,
1064                               machine, thread, &x.is64bit, &x.cpumode, false);
1065                 if (len <= 0)
1066                         goto out;
1067
1068                 printed += fprintf(fp, "\t%016" PRIx64 "\t%s\n", sample->ip,
1069                         dump_insn(&x, sample->ip, buffer, len, NULL));
1070                 goto out;
1071         }
1072         for (off = 0; off <= end - start; off += ilen) {
1073                 printed += fprintf(fp, "\t%016" PRIx64 "\t%s\n", start + off,
1074                                    dump_insn(&x, start + off, buffer + off, len - off, &ilen));
1075                 if (ilen == 0)
1076                         break;
1077         }
1078 out:
1079         return printed;
1080 }
1081
1082 static int perf_sample__fprintf_addr(struct perf_sample *sample,
1083                                      struct thread *thread,
1084                                      struct perf_event_attr *attr, FILE *fp)
1085 {
1086         struct addr_location al;
1087         int printed = fprintf(fp, "%16" PRIx64, sample->addr);
1088
1089         if (!sample_addr_correlates_sym(attr))
1090                 goto out;
1091
1092         thread__resolve(thread, &al, sample);
1093
1094         if (PRINT_FIELD(SYM)) {
1095                 printed += fprintf(fp, " ");
1096                 if (PRINT_FIELD(SYMOFFSET))
1097                         printed += symbol__fprintf_symname_offs(al.sym, &al, fp);
1098                 else
1099                         printed += symbol__fprintf_symname(al.sym, fp);
1100         }
1101
1102         if (PRINT_FIELD(DSO)) {
1103                 printed += fprintf(fp, " (");
1104                 printed += map__fprintf_dsoname(al.map, fp);
1105                 printed += fprintf(fp, ")");
1106         }
1107 out:
1108         return printed;
1109 }
1110
1111 static const char *resolve_branch_sym(struct perf_sample *sample,
1112                                       struct perf_evsel *evsel,
1113                                       struct thread *thread,
1114                                       struct addr_location *al,
1115                                       u64 *ip)
1116 {
1117         struct addr_location addr_al;
1118         struct perf_event_attr *attr = &evsel->attr;
1119         const char *name = NULL;
1120
1121         if (sample->flags & (PERF_IP_FLAG_CALL | PERF_IP_FLAG_TRACE_BEGIN)) {
1122                 if (sample_addr_correlates_sym(attr)) {
1123                         thread__resolve(thread, &addr_al, sample);
1124                         if (addr_al.sym)
1125                                 name = addr_al.sym->name;
1126                         else
1127                                 *ip = sample->addr;
1128                 } else {
1129                         *ip = sample->addr;
1130                 }
1131         } else if (sample->flags & (PERF_IP_FLAG_RETURN | PERF_IP_FLAG_TRACE_END)) {
1132                 if (al->sym)
1133                         name = al->sym->name;
1134                 else
1135                         *ip = sample->ip;
1136         }
1137         return name;
1138 }
1139
1140 static int perf_sample__fprintf_callindent(struct perf_sample *sample,
1141                                            struct perf_evsel *evsel,
1142                                            struct thread *thread,
1143                                            struct addr_location *al, FILE *fp)
1144 {
1145         struct perf_event_attr *attr = &evsel->attr;
1146         size_t depth = thread_stack__depth(thread);
1147         const char *name = NULL;
1148         static int spacing;
1149         int len = 0;
1150         int dlen = 0;
1151         u64 ip = 0;
1152
1153         /*
1154          * The 'return' has already been popped off the stack so the depth has
1155          * to be adjusted to match the 'call'.
1156          */
1157         if (thread->ts && sample->flags & PERF_IP_FLAG_RETURN)
1158                 depth += 1;
1159
1160         name = resolve_branch_sym(sample, evsel, thread, al, &ip);
1161
1162         if (PRINT_FIELD(DSO) && !(PRINT_FIELD(IP) || PRINT_FIELD(ADDR))) {
1163                 dlen += fprintf(fp, "(");
1164                 dlen += map__fprintf_dsoname(al->map, fp);
1165                 dlen += fprintf(fp, ")\t");
1166         }
1167
1168         if (name)
1169                 len = fprintf(fp, "%*s%s", (int)depth * 4, "", name);
1170         else if (ip)
1171                 len = fprintf(fp, "%*s%16" PRIx64, (int)depth * 4, "", ip);
1172
1173         if (len < 0)
1174                 return len;
1175
1176         /*
1177          * Try to keep the output length from changing frequently so that the
1178          * output lines up more nicely.
1179          */
1180         if (len > spacing || (len && len < spacing - 52))
1181                 spacing = round_up(len + 4, 32);
1182
1183         if (len < spacing)
1184                 len += fprintf(fp, "%*s", spacing - len, "");
1185
1186         return len + dlen;
1187 }
1188
1189 static int perf_sample__fprintf_insn(struct perf_sample *sample,
1190                                      struct perf_event_attr *attr,
1191                                      struct thread *thread,
1192                                      struct machine *machine, FILE *fp)
1193 {
1194         int printed = 0;
1195
1196         if (PRINT_FIELD(INSNLEN))
1197                 printed += fprintf(fp, " ilen: %d", sample->insn_len);
1198         if (PRINT_FIELD(INSN)) {
1199                 int i;
1200
1201                 printed += fprintf(fp, " insn:");
1202                 for (i = 0; i < sample->insn_len; i++)
1203                         printed += fprintf(fp, " %02x", (unsigned char)sample->insn[i]);
1204         }
1205         if (PRINT_FIELD(BRSTACKINSN))
1206                 printed += perf_sample__fprintf_brstackinsn(sample, thread, attr, machine, fp);
1207
1208         return printed;
1209 }
1210
1211 static int perf_sample__fprintf_bts(struct perf_sample *sample,
1212                                     struct perf_evsel *evsel,
1213                                     struct thread *thread,
1214                                     struct addr_location *al,
1215                                     struct machine *machine, FILE *fp)
1216 {
1217         struct perf_event_attr *attr = &evsel->attr;
1218         unsigned int type = output_type(attr->type);
1219         bool print_srcline_last = false;
1220         int printed = 0;
1221
1222         if (PRINT_FIELD(CALLINDENT))
1223                 printed += perf_sample__fprintf_callindent(sample, evsel, thread, al, fp);
1224
1225         /* print branch_from information */
1226         if (PRINT_FIELD(IP)) {
1227                 unsigned int print_opts = output[type].print_ip_opts;
1228                 struct callchain_cursor *cursor = NULL;
1229
1230                 if (symbol_conf.use_callchain && sample->callchain &&
1231                     thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
1232                                               sample, NULL, NULL, scripting_max_stack) == 0)
1233                         cursor = &callchain_cursor;
1234
1235                 if (cursor == NULL) {
1236                         printed += fprintf(fp, " ");
1237                         if (print_opts & EVSEL__PRINT_SRCLINE) {
1238                                 print_srcline_last = true;
1239                                 print_opts &= ~EVSEL__PRINT_SRCLINE;
1240                         }
1241                 } else
1242                         printed += fprintf(fp, "\n");
1243
1244                 printed += sample__fprintf_sym(sample, al, 0, print_opts, cursor, fp);
1245         }
1246
1247         /* print branch_to information */
1248         if (PRINT_FIELD(ADDR) ||
1249             ((evsel->attr.sample_type & PERF_SAMPLE_ADDR) &&
1250              !output[type].user_set)) {
1251                 printed += fprintf(fp, " => ");
1252                 printed += perf_sample__fprintf_addr(sample, thread, attr, fp);
1253         }
1254
1255         if (print_srcline_last)
1256                 printed += map__fprintf_srcline(al->map, al->addr, "\n  ", fp);
1257
1258         printed += perf_sample__fprintf_insn(sample, attr, thread, machine, fp);
1259         return printed + fprintf(fp, "\n");
1260 }
1261
1262 static struct {
1263         u32 flags;
1264         const char *name;
1265 } sample_flags[] = {
1266         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL, "call"},
1267         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN, "return"},
1268         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CONDITIONAL, "jcc"},
1269         {PERF_IP_FLAG_BRANCH, "jmp"},
1270         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_INTERRUPT, "int"},
1271         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN | PERF_IP_FLAG_INTERRUPT, "iret"},
1272         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_SYSCALLRET, "syscall"},
1273         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN | PERF_IP_FLAG_SYSCALLRET, "sysret"},
1274         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_ASYNC, "async"},
1275         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_ASYNC | PERF_IP_FLAG_INTERRUPT, "hw int"},
1276         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TX_ABORT, "tx abrt"},
1277         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TRACE_BEGIN, "tr strt"},
1278         {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TRACE_END, "tr end"},
1279         {0, NULL}
1280 };
1281
1282 static const char *sample_flags_to_name(u32 flags)
1283 {
1284         int i;
1285
1286         for (i = 0; sample_flags[i].name ; i++) {
1287                 if (sample_flags[i].flags == flags)
1288                         return sample_flags[i].name;
1289         }
1290
1291         return NULL;
1292 }
1293
1294 static int perf_sample__fprintf_flags(u32 flags, FILE *fp)
1295 {
1296         const char *chars = PERF_IP_FLAG_CHARS;
1297         const int n = strlen(PERF_IP_FLAG_CHARS);
1298         bool in_tx = flags & PERF_IP_FLAG_IN_TX;
1299         const char *name = NULL;
1300         char str[33];
1301         int i, pos = 0;
1302
1303         name = sample_flags_to_name(flags & ~PERF_IP_FLAG_IN_TX);
1304         if (name)
1305                 return fprintf(fp, "  %-15s%4s ", name, in_tx ? "(x)" : "");
1306
1307         if (flags & PERF_IP_FLAG_TRACE_BEGIN) {
1308                 name = sample_flags_to_name(flags & ~(PERF_IP_FLAG_IN_TX | PERF_IP_FLAG_TRACE_BEGIN));
1309                 if (name)
1310                         return fprintf(fp, "  tr strt %-7s%4s ", name, in_tx ? "(x)" : "");
1311         }
1312
1313         if (flags & PERF_IP_FLAG_TRACE_END) {
1314                 name = sample_flags_to_name(flags & ~(PERF_IP_FLAG_IN_TX | PERF_IP_FLAG_TRACE_END));
1315                 if (name)
1316                         return fprintf(fp, "  tr end  %-7s%4s ", name, in_tx ? "(x)" : "");
1317         }
1318
1319         for (i = 0; i < n; i++, flags >>= 1) {
1320                 if (flags & 1)
1321                         str[pos++] = chars[i];
1322         }
1323         for (; i < 32; i++, flags >>= 1) {
1324                 if (flags & 1)
1325                         str[pos++] = '?';
1326         }
1327         str[pos] = 0;
1328
1329         return fprintf(fp, "  %-19s ", str);
1330 }
1331
1332 struct printer_data {
1333         int line_no;
1334         bool hit_nul;
1335         bool is_printable;
1336 };
1337
1338 static int sample__fprintf_bpf_output(enum binary_printer_ops op,
1339                                       unsigned int val,
1340                                       void *extra, FILE *fp)
1341 {
1342         unsigned char ch = (unsigned char)val;
1343         struct printer_data *printer_data = extra;
1344         int printed = 0;
1345
1346         switch (op) {
1347         case BINARY_PRINT_DATA_BEGIN:
1348                 printed += fprintf(fp, "\n");
1349                 break;
1350         case BINARY_PRINT_LINE_BEGIN:
1351                 printed += fprintf(fp, "%17s", !printer_data->line_no ? "BPF output:" :
1352                                                         "           ");
1353                 break;
1354         case BINARY_PRINT_ADDR:
1355                 printed += fprintf(fp, " %04x:", val);
1356                 break;
1357         case BINARY_PRINT_NUM_DATA:
1358                 printed += fprintf(fp, " %02x", val);
1359                 break;
1360         case BINARY_PRINT_NUM_PAD:
1361                 printed += fprintf(fp, "   ");
1362                 break;
1363         case BINARY_PRINT_SEP:
1364                 printed += fprintf(fp, "  ");
1365                 break;
1366         case BINARY_PRINT_CHAR_DATA:
1367                 if (printer_data->hit_nul && ch)
1368                         printer_data->is_printable = false;
1369
1370                 if (!isprint(ch)) {
1371                         printed += fprintf(fp, "%c", '.');
1372
1373                         if (!printer_data->is_printable)
1374                                 break;
1375
1376                         if (ch == '\0')
1377                                 printer_data->hit_nul = true;
1378                         else
1379                                 printer_data->is_printable = false;
1380                 } else {
1381                         printed += fprintf(fp, "%c", ch);
1382                 }
1383                 break;
1384         case BINARY_PRINT_CHAR_PAD:
1385                 printed += fprintf(fp, " ");
1386                 break;
1387         case BINARY_PRINT_LINE_END:
1388                 printed += fprintf(fp, "\n");
1389                 printer_data->line_no++;
1390                 break;
1391         case BINARY_PRINT_DATA_END:
1392         default:
1393                 break;
1394         }
1395
1396         return printed;
1397 }
1398
1399 static int perf_sample__fprintf_bpf_output(struct perf_sample *sample, FILE *fp)
1400 {
1401         unsigned int nr_bytes = sample->raw_size;
1402         struct printer_data printer_data = {0, false, true};
1403         int printed = binary__fprintf(sample->raw_data, nr_bytes, 8,
1404                                       sample__fprintf_bpf_output, &printer_data, fp);
1405
1406         if (printer_data.is_printable && printer_data.hit_nul)
1407                 printed += fprintf(fp, "%17s \"%s\"\n", "BPF string:", (char *)(sample->raw_data));
1408
1409         return printed;
1410 }
1411
1412 static int perf_sample__fprintf_spacing(int len, int spacing, FILE *fp)
1413 {
1414         if (len > 0 && len < spacing)
1415                 return fprintf(fp, "%*s", spacing - len, "");
1416
1417         return 0;
1418 }
1419
1420 static int perf_sample__fprintf_pt_spacing(int len, FILE *fp)
1421 {
1422         return perf_sample__fprintf_spacing(len, 34, fp);
1423 }
1424
1425 static int perf_sample__fprintf_synth_ptwrite(struct perf_sample *sample, FILE *fp)
1426 {
1427         struct perf_synth_intel_ptwrite *data = perf_sample__synth_ptr(sample);
1428         int len;
1429
1430         if (perf_sample__bad_synth_size(sample, *data))
1431                 return 0;
1432
1433         len = fprintf(fp, " IP: %u payload: %#" PRIx64 " ",
1434                      data->ip, le64_to_cpu(data->payload));
1435         return len + perf_sample__fprintf_pt_spacing(len, fp);
1436 }
1437
1438 static int perf_sample__fprintf_synth_mwait(struct perf_sample *sample, FILE *fp)
1439 {
1440         struct perf_synth_intel_mwait *data = perf_sample__synth_ptr(sample);
1441         int len;
1442
1443         if (perf_sample__bad_synth_size(sample, *data))
1444                 return 0;
1445
1446         len = fprintf(fp, " hints: %#x extensions: %#x ",
1447                       data->hints, data->extensions);
1448         return len + perf_sample__fprintf_pt_spacing(len, fp);
1449 }
1450
1451 static int perf_sample__fprintf_synth_pwre(struct perf_sample *sample, FILE *fp)
1452 {
1453         struct perf_synth_intel_pwre *data = perf_sample__synth_ptr(sample);
1454         int len;
1455
1456         if (perf_sample__bad_synth_size(sample, *data))
1457                 return 0;
1458
1459         len = fprintf(fp, " hw: %u cstate: %u sub-cstate: %u ",
1460                       data->hw, data->cstate, data->subcstate);
1461         return len + perf_sample__fprintf_pt_spacing(len, fp);
1462 }
1463
1464 static int perf_sample__fprintf_synth_exstop(struct perf_sample *sample, FILE *fp)
1465 {
1466         struct perf_synth_intel_exstop *data = perf_sample__synth_ptr(sample);
1467         int len;
1468
1469         if (perf_sample__bad_synth_size(sample, *data))
1470                 return 0;
1471
1472         len = fprintf(fp, " IP: %u ", data->ip);
1473         return len + perf_sample__fprintf_pt_spacing(len, fp);
1474 }
1475
1476 static int perf_sample__fprintf_synth_pwrx(struct perf_sample *sample, FILE *fp)
1477 {
1478         struct perf_synth_intel_pwrx *data = perf_sample__synth_ptr(sample);
1479         int len;
1480
1481         if (perf_sample__bad_synth_size(sample, *data))
1482                 return 0;
1483
1484         len = fprintf(fp, " deepest cstate: %u last cstate: %u wake reason: %#x ",
1485                      data->deepest_cstate, data->last_cstate,
1486                      data->wake_reason);
1487         return len + perf_sample__fprintf_pt_spacing(len, fp);
1488 }
1489
1490 static int perf_sample__fprintf_synth_cbr(struct perf_sample *sample, FILE *fp)
1491 {
1492         struct perf_synth_intel_cbr *data = perf_sample__synth_ptr(sample);
1493         unsigned int percent, freq;
1494         int len;
1495
1496         if (perf_sample__bad_synth_size(sample, *data))
1497                 return 0;
1498
1499         freq = (le32_to_cpu(data->freq) + 500) / 1000;
1500         len = fprintf(fp, " cbr: %2u freq: %4u MHz ", data->cbr, freq);
1501         if (data->max_nonturbo) {
1502                 percent = (5 + (1000 * data->cbr) / data->max_nonturbo) / 10;
1503                 len += fprintf(fp, "(%3u%%) ", percent);
1504         }
1505         return len + perf_sample__fprintf_pt_spacing(len, fp);
1506 }
1507
1508 static int perf_sample__fprintf_synth(struct perf_sample *sample,
1509                                       struct perf_evsel *evsel, FILE *fp)
1510 {
1511         switch (evsel->attr.config) {
1512         case PERF_SYNTH_INTEL_PTWRITE:
1513                 return perf_sample__fprintf_synth_ptwrite(sample, fp);
1514         case PERF_SYNTH_INTEL_MWAIT:
1515                 return perf_sample__fprintf_synth_mwait(sample, fp);
1516         case PERF_SYNTH_INTEL_PWRE:
1517                 return perf_sample__fprintf_synth_pwre(sample, fp);
1518         case PERF_SYNTH_INTEL_EXSTOP:
1519                 return perf_sample__fprintf_synth_exstop(sample, fp);
1520         case PERF_SYNTH_INTEL_PWRX:
1521                 return perf_sample__fprintf_synth_pwrx(sample, fp);
1522         case PERF_SYNTH_INTEL_CBR:
1523                 return perf_sample__fprintf_synth_cbr(sample, fp);
1524         default:
1525                 break;
1526         }
1527
1528         return 0;
1529 }
1530
1531 struct perf_script {
1532         struct perf_tool        tool;
1533         struct perf_session     *session;
1534         bool                    show_task_events;
1535         bool                    show_mmap_events;
1536         bool                    show_switch_events;
1537         bool                    show_namespace_events;
1538         bool                    show_lost_events;
1539         bool                    show_round_events;
1540         bool                    allocated;
1541         bool                    per_event_dump;
1542         struct cpu_map          *cpus;
1543         struct thread_map       *threads;
1544         int                     name_width;
1545         const char              *time_str;
1546         struct perf_time_interval *ptime_range;
1547         int                     range_size;
1548         int                     range_num;
1549 };
1550
1551 static int perf_evlist__max_name_len(struct perf_evlist *evlist)
1552 {
1553         struct perf_evsel *evsel;
1554         int max = 0;
1555
1556         evlist__for_each_entry(evlist, evsel) {
1557                 int len = strlen(perf_evsel__name(evsel));
1558
1559                 max = MAX(len, max);
1560         }
1561
1562         return max;
1563 }
1564
1565 static int data_src__fprintf(u64 data_src, FILE *fp)
1566 {
1567         struct mem_info mi = { .data_src.val = data_src };
1568         char decode[100];
1569         char out[100];
1570         static int maxlen;
1571         int len;
1572
1573         perf_script__meminfo_scnprintf(decode, 100, &mi);
1574
1575         len = scnprintf(out, 100, "%16" PRIx64 " %s", data_src, decode);
1576         if (maxlen < len)
1577                 maxlen = len;
1578
1579         return fprintf(fp, "%-*s", maxlen, out);
1580 }
1581
1582 struct metric_ctx {
1583         struct perf_sample      *sample;
1584         struct thread           *thread;
1585         struct perf_evsel       *evsel;
1586         FILE                    *fp;
1587 };
1588
1589 static void script_print_metric(struct perf_stat_config *config __maybe_unused,
1590                                 void *ctx, const char *color,
1591                                 const char *fmt,
1592                                 const char *unit, double val)
1593 {
1594         struct metric_ctx *mctx = ctx;
1595
1596         if (!fmt)
1597                 return;
1598         perf_sample__fprintf_start(mctx->sample, mctx->thread, mctx->evsel,
1599                                    PERF_RECORD_SAMPLE, mctx->fp);
1600         fputs("\tmetric: ", mctx->fp);
1601         if (color)
1602                 color_fprintf(mctx->fp, color, fmt, val);
1603         else
1604                 printf(fmt, val);
1605         fprintf(mctx->fp, " %s\n", unit);
1606 }
1607
1608 static void script_new_line(struct perf_stat_config *config __maybe_unused,
1609                             void *ctx)
1610 {
1611         struct metric_ctx *mctx = ctx;
1612
1613         perf_sample__fprintf_start(mctx->sample, mctx->thread, mctx->evsel,
1614                                    PERF_RECORD_SAMPLE, mctx->fp);
1615         fputs("\tmetric: ", mctx->fp);
1616 }
1617
1618 static void perf_sample__fprint_metric(struct perf_script *script,
1619                                        struct thread *thread,
1620                                        struct perf_evsel *evsel,
1621                                        struct perf_sample *sample,
1622                                        FILE *fp)
1623 {
1624         struct perf_stat_output_ctx ctx = {
1625                 .print_metric = script_print_metric,
1626                 .new_line = script_new_line,
1627                 .ctx = &(struct metric_ctx) {
1628                                 .sample = sample,
1629                                 .thread = thread,
1630                                 .evsel  = evsel,
1631                                 .fp     = fp,
1632                          },
1633                 .force_header = false,
1634         };
1635         struct perf_evsel *ev2;
1636         static bool init;
1637         u64 val;
1638
1639         if (!init) {
1640                 perf_stat__init_shadow_stats();
1641                 init = true;
1642         }
1643         if (!evsel->stats)
1644                 perf_evlist__alloc_stats(script->session->evlist, false);
1645         if (evsel_script(evsel->leader)->gnum++ == 0)
1646                 perf_stat__reset_shadow_stats();
1647         val = sample->period * evsel->scale;
1648         perf_stat__update_shadow_stats(evsel,
1649                                        val,
1650                                        sample->cpu,
1651                                        &rt_stat);
1652         evsel_script(evsel)->val = val;
1653         if (evsel_script(evsel->leader)->gnum == evsel->leader->nr_members) {
1654                 for_each_group_member (ev2, evsel->leader) {
1655                         perf_stat__print_shadow_stats(&stat_config, ev2,
1656                                                       evsel_script(ev2)->val,
1657                                                       sample->cpu,
1658                                                       &ctx,
1659                                                       NULL,
1660                                                       &rt_stat);
1661                 }
1662                 evsel_script(evsel->leader)->gnum = 0;
1663         }
1664 }
1665
1666 static bool show_event(struct perf_sample *sample,
1667                        struct perf_evsel *evsel,
1668                        struct thread *thread,
1669                        struct addr_location *al)
1670 {
1671         int depth = thread_stack__depth(thread);
1672
1673         if (!symbol_conf.graph_function)
1674                 return true;
1675
1676         if (thread->filter) {
1677                 if (depth <= thread->filter_entry_depth) {
1678                         thread->filter = false;
1679                         return false;
1680                 }
1681                 return true;
1682         } else {
1683                 const char *s = symbol_conf.graph_function;
1684                 u64 ip;
1685                 const char *name = resolve_branch_sym(sample, evsel, thread, al,
1686                                 &ip);
1687                 unsigned nlen;
1688
1689                 if (!name)
1690                         return false;
1691                 nlen = strlen(name);
1692                 while (*s) {
1693                         unsigned len = strcspn(s, ",");
1694                         if (nlen == len && !strncmp(name, s, len)) {
1695                                 thread->filter = true;
1696                                 thread->filter_entry_depth = depth;
1697                                 return true;
1698                         }
1699                         s += len;
1700                         if (*s == ',')
1701                                 s++;
1702                 }
1703                 return false;
1704         }
1705 }
1706
1707 static void process_event(struct perf_script *script,
1708                           struct perf_sample *sample, struct perf_evsel *evsel,
1709                           struct addr_location *al,
1710                           struct machine *machine)
1711 {
1712         struct thread *thread = al->thread;
1713         struct perf_event_attr *attr = &evsel->attr;
1714         unsigned int type = output_type(attr->type);
1715         struct perf_evsel_script *es = evsel->priv;
1716         FILE *fp = es->fp;
1717
1718         if (output[type].fields == 0)
1719                 return;
1720
1721         if (!show_event(sample, evsel, thread, al))
1722                 return;
1723
1724         ++es->samples;
1725
1726         perf_sample__fprintf_start(sample, thread, evsel,
1727                                    PERF_RECORD_SAMPLE, fp);
1728
1729         if (PRINT_FIELD(PERIOD))
1730                 fprintf(fp, "%10" PRIu64 " ", sample->period);
1731
1732         if (PRINT_FIELD(EVNAME)) {
1733                 const char *evname = perf_evsel__name(evsel);
1734
1735                 if (!script->name_width)
1736                         script->name_width = perf_evlist__max_name_len(script->session->evlist);
1737
1738                 fprintf(fp, "%*s: ", script->name_width, evname ?: "[unknown]");
1739         }
1740
1741         if (print_flags)
1742                 perf_sample__fprintf_flags(sample->flags, fp);
1743
1744         if (is_bts_event(attr)) {
1745                 perf_sample__fprintf_bts(sample, evsel, thread, al, machine, fp);
1746                 return;
1747         }
1748
1749         if (PRINT_FIELD(TRACE)) {
1750                 event_format__fprintf(evsel->tp_format, sample->cpu,
1751                                       sample->raw_data, sample->raw_size, fp);
1752         }
1753
1754         if (attr->type == PERF_TYPE_SYNTH && PRINT_FIELD(SYNTH))
1755                 perf_sample__fprintf_synth(sample, evsel, fp);
1756
1757         if (PRINT_FIELD(ADDR))
1758                 perf_sample__fprintf_addr(sample, thread, attr, fp);
1759
1760         if (PRINT_FIELD(DATA_SRC))
1761                 data_src__fprintf(sample->data_src, fp);
1762
1763         if (PRINT_FIELD(WEIGHT))
1764                 fprintf(fp, "%16" PRIu64, sample->weight);
1765
1766         if (PRINT_FIELD(IP)) {
1767                 struct callchain_cursor *cursor = NULL;
1768
1769                 if (symbol_conf.use_callchain && sample->callchain &&
1770                     thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
1771                                               sample, NULL, NULL, scripting_max_stack) == 0)
1772                         cursor = &callchain_cursor;
1773
1774                 fputc(cursor ? '\n' : ' ', fp);
1775                 sample__fprintf_sym(sample, al, 0, output[type].print_ip_opts, cursor, fp);
1776         }
1777
1778         if (PRINT_FIELD(IREGS))
1779                 perf_sample__fprintf_iregs(sample, attr, fp);
1780
1781         if (PRINT_FIELD(UREGS))
1782                 perf_sample__fprintf_uregs(sample, attr, fp);
1783
1784         if (PRINT_FIELD(BRSTACK))
1785                 perf_sample__fprintf_brstack(sample, thread, attr, fp);
1786         else if (PRINT_FIELD(BRSTACKSYM))
1787                 perf_sample__fprintf_brstacksym(sample, thread, attr, fp);
1788         else if (PRINT_FIELD(BRSTACKOFF))
1789                 perf_sample__fprintf_brstackoff(sample, thread, attr, fp);
1790
1791         if (perf_evsel__is_bpf_output(evsel) && PRINT_FIELD(BPF_OUTPUT))
1792                 perf_sample__fprintf_bpf_output(sample, fp);
1793         perf_sample__fprintf_insn(sample, attr, thread, machine, fp);
1794
1795         if (PRINT_FIELD(PHYS_ADDR))
1796                 fprintf(fp, "%16" PRIx64, sample->phys_addr);
1797         fprintf(fp, "\n");
1798
1799         if (PRINT_FIELD(METRIC))
1800                 perf_sample__fprint_metric(script, thread, evsel, sample, fp);
1801
1802         if (verbose)
1803                 fflush(fp);
1804 }
1805
1806 static struct scripting_ops     *scripting_ops;
1807
1808 static void __process_stat(struct perf_evsel *counter, u64 tstamp)
1809 {
1810         int nthreads = thread_map__nr(counter->threads);
1811         int ncpus = perf_evsel__nr_cpus(counter);
1812         int cpu, thread;
1813         static int header_printed;
1814
1815         if (counter->system_wide)
1816                 nthreads = 1;
1817
1818         if (!header_printed) {
1819                 printf("%3s %8s %15s %15s %15s %15s %s\n",
1820                        "CPU", "THREAD", "VAL", "ENA", "RUN", "TIME", "EVENT");
1821                 header_printed = 1;
1822         }
1823
1824         for (thread = 0; thread < nthreads; thread++) {
1825                 for (cpu = 0; cpu < ncpus; cpu++) {
1826                         struct perf_counts_values *counts;
1827
1828                         counts = perf_counts(counter->counts, cpu, thread);
1829
1830                         printf("%3d %8d %15" PRIu64 " %15" PRIu64 " %15" PRIu64 " %15" PRIu64 " %s\n",
1831                                 counter->cpus->map[cpu],
1832                                 thread_map__pid(counter->threads, thread),
1833                                 counts->val,
1834                                 counts->ena,
1835                                 counts->run,
1836                                 tstamp,
1837                                 perf_evsel__name(counter));
1838                 }
1839         }
1840 }
1841
1842 static void process_stat(struct perf_evsel *counter, u64 tstamp)
1843 {
1844         if (scripting_ops && scripting_ops->process_stat)
1845                 scripting_ops->process_stat(&stat_config, counter, tstamp);
1846         else
1847                 __process_stat(counter, tstamp);
1848 }
1849
1850 static void process_stat_interval(u64 tstamp)
1851 {
1852         if (scripting_ops && scripting_ops->process_stat_interval)
1853                 scripting_ops->process_stat_interval(tstamp);
1854 }
1855
1856 static void setup_scripting(void)
1857 {
1858         setup_perl_scripting();
1859         setup_python_scripting();
1860 }
1861
1862 static int flush_scripting(void)
1863 {
1864         return scripting_ops ? scripting_ops->flush_script() : 0;
1865 }
1866
1867 static int cleanup_scripting(void)
1868 {
1869         pr_debug("\nperf script stopped\n");
1870
1871         return scripting_ops ? scripting_ops->stop_script() : 0;
1872 }
1873
1874 static int process_sample_event(struct perf_tool *tool,
1875                                 union perf_event *event,
1876                                 struct perf_sample *sample,
1877                                 struct perf_evsel *evsel,
1878                                 struct machine *machine)
1879 {
1880         struct perf_script *scr = container_of(tool, struct perf_script, tool);
1881         struct addr_location al;
1882
1883         if (perf_time__ranges_skip_sample(scr->ptime_range, scr->range_num,
1884                                           sample->time)) {
1885                 return 0;
1886         }
1887
1888         if (debug_mode) {
1889                 if (sample->time < last_timestamp) {
1890                         pr_err("Samples misordered, previous: %" PRIu64
1891                                 " this: %" PRIu64 "\n", last_timestamp,
1892                                 sample->time);
1893                         nr_unordered++;
1894                 }
1895                 last_timestamp = sample->time;
1896                 return 0;
1897         }
1898
1899         if (machine__resolve(machine, &al, sample) < 0) {
1900                 pr_err("problem processing %d event, skipping it.\n",
1901                        event->header.type);
1902                 return -1;
1903         }
1904
1905         if (al.filtered)
1906                 goto out_put;
1907
1908         if (cpu_list && !test_bit(sample->cpu, cpu_bitmap))
1909                 goto out_put;
1910
1911         if (scripting_ops)
1912                 scripting_ops->process_event(event, sample, evsel, &al);
1913         else
1914                 process_event(scr, sample, evsel, &al, machine);
1915
1916 out_put:
1917         addr_location__put(&al);
1918         return 0;
1919 }
1920
1921 static int process_attr(struct perf_tool *tool, union perf_event *event,
1922                         struct perf_evlist **pevlist)
1923 {
1924         struct perf_script *scr = container_of(tool, struct perf_script, tool);
1925         struct perf_evlist *evlist;
1926         struct perf_evsel *evsel, *pos;
1927         int err;
1928         static struct perf_evsel_script *es;
1929
1930         err = perf_event__process_attr(tool, event, pevlist);
1931         if (err)
1932                 return err;
1933
1934         evlist = *pevlist;
1935         evsel = perf_evlist__last(*pevlist);
1936
1937         if (!evsel->priv) {
1938                 if (scr->per_event_dump) {
1939                         evsel->priv = perf_evsel_script__new(evsel,
1940                                                 scr->session->data);
1941                 } else {
1942                         es = zalloc(sizeof(*es));
1943                         if (!es)
1944                                 return -ENOMEM;
1945                         es->fp = stdout;
1946                         evsel->priv = es;
1947                 }
1948         }
1949
1950         if (evsel->attr.type >= PERF_TYPE_MAX &&
1951             evsel->attr.type != PERF_TYPE_SYNTH)
1952                 return 0;
1953
1954         evlist__for_each_entry(evlist, pos) {
1955                 if (pos->attr.type == evsel->attr.type && pos != evsel)
1956                         return 0;
1957         }
1958
1959         set_print_ip_opts(&evsel->attr);
1960
1961         if (evsel->attr.sample_type)
1962                 err = perf_evsel__check_attr(evsel, scr->session);
1963
1964         return err;
1965 }
1966
1967 static int process_comm_event(struct perf_tool *tool,
1968                               union perf_event *event,
1969                               struct perf_sample *sample,
1970                               struct machine *machine)
1971 {
1972         struct thread *thread;
1973         struct perf_script *script = container_of(tool, struct perf_script, tool);
1974         struct perf_session *session = script->session;
1975         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1976         int ret = -1;
1977
1978         thread = machine__findnew_thread(machine, event->comm.pid, event->comm.tid);
1979         if (thread == NULL) {
1980                 pr_debug("problem processing COMM event, skipping it.\n");
1981                 return -1;
1982         }
1983
1984         if (perf_event__process_comm(tool, event, sample, machine) < 0)
1985                 goto out;
1986
1987         if (!evsel->attr.sample_id_all) {
1988                 sample->cpu = 0;
1989                 sample->time = 0;
1990                 sample->tid = event->comm.tid;
1991                 sample->pid = event->comm.pid;
1992         }
1993         perf_sample__fprintf_start(sample, thread, evsel,
1994                                    PERF_RECORD_COMM, stdout);
1995         perf_event__fprintf(event, stdout);
1996         ret = 0;
1997 out:
1998         thread__put(thread);
1999         return ret;
2000 }
2001
2002 static int process_namespaces_event(struct perf_tool *tool,
2003                                     union perf_event *event,
2004                                     struct perf_sample *sample,
2005                                     struct machine *machine)
2006 {
2007         struct thread *thread;
2008         struct perf_script *script = container_of(tool, struct perf_script, tool);
2009         struct perf_session *session = script->session;
2010         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2011         int ret = -1;
2012
2013         thread = machine__findnew_thread(machine, event->namespaces.pid,
2014                                          event->namespaces.tid);
2015         if (thread == NULL) {
2016                 pr_debug("problem processing NAMESPACES event, skipping it.\n");
2017                 return -1;
2018         }
2019
2020         if (perf_event__process_namespaces(tool, event, sample, machine) < 0)
2021                 goto out;
2022
2023         if (!evsel->attr.sample_id_all) {
2024                 sample->cpu = 0;
2025                 sample->time = 0;
2026                 sample->tid = event->namespaces.tid;
2027                 sample->pid = event->namespaces.pid;
2028         }
2029         perf_sample__fprintf_start(sample, thread, evsel,
2030                                    PERF_RECORD_NAMESPACES, stdout);
2031         perf_event__fprintf(event, stdout);
2032         ret = 0;
2033 out:
2034         thread__put(thread);
2035         return ret;
2036 }
2037
2038 static int process_fork_event(struct perf_tool *tool,
2039                               union perf_event *event,
2040                               struct perf_sample *sample,
2041                               struct machine *machine)
2042 {
2043         struct thread *thread;
2044         struct perf_script *script = container_of(tool, struct perf_script, tool);
2045         struct perf_session *session = script->session;
2046         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2047
2048         if (perf_event__process_fork(tool, event, sample, machine) < 0)
2049                 return -1;
2050
2051         thread = machine__findnew_thread(machine, event->fork.pid, event->fork.tid);
2052         if (thread == NULL) {
2053                 pr_debug("problem processing FORK event, skipping it.\n");
2054                 return -1;
2055         }
2056
2057         if (!evsel->attr.sample_id_all) {
2058                 sample->cpu = 0;
2059                 sample->time = event->fork.time;
2060                 sample->tid = event->fork.tid;
2061                 sample->pid = event->fork.pid;
2062         }
2063         perf_sample__fprintf_start(sample, thread, evsel,
2064                                    PERF_RECORD_FORK, stdout);
2065         perf_event__fprintf(event, stdout);
2066         thread__put(thread);
2067
2068         return 0;
2069 }
2070 static int process_exit_event(struct perf_tool *tool,
2071                               union perf_event *event,
2072                               struct perf_sample *sample,
2073                               struct machine *machine)
2074 {
2075         int err = 0;
2076         struct thread *thread;
2077         struct perf_script *script = container_of(tool, struct perf_script, tool);
2078         struct perf_session *session = script->session;
2079         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2080
2081         thread = machine__findnew_thread(machine, event->fork.pid, event->fork.tid);
2082         if (thread == NULL) {
2083                 pr_debug("problem processing EXIT event, skipping it.\n");
2084                 return -1;
2085         }
2086
2087         if (!evsel->attr.sample_id_all) {
2088                 sample->cpu = 0;
2089                 sample->time = 0;
2090                 sample->tid = event->fork.tid;
2091                 sample->pid = event->fork.pid;
2092         }
2093         perf_sample__fprintf_start(sample, thread, evsel,
2094                                    PERF_RECORD_EXIT, stdout);
2095         perf_event__fprintf(event, stdout);
2096
2097         if (perf_event__process_exit(tool, event, sample, machine) < 0)
2098                 err = -1;
2099
2100         thread__put(thread);
2101         return err;
2102 }
2103
2104 static int process_mmap_event(struct perf_tool *tool,
2105                               union perf_event *event,
2106                               struct perf_sample *sample,
2107                               struct machine *machine)
2108 {
2109         struct thread *thread;
2110         struct perf_script *script = container_of(tool, struct perf_script, tool);
2111         struct perf_session *session = script->session;
2112         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2113
2114         if (perf_event__process_mmap(tool, event, sample, machine) < 0)
2115                 return -1;
2116
2117         thread = machine__findnew_thread(machine, event->mmap.pid, event->mmap.tid);
2118         if (thread == NULL) {
2119                 pr_debug("problem processing MMAP event, skipping it.\n");
2120                 return -1;
2121         }
2122
2123         if (!evsel->attr.sample_id_all) {
2124                 sample->cpu = 0;
2125                 sample->time = 0;
2126                 sample->tid = event->mmap.tid;
2127                 sample->pid = event->mmap.pid;
2128         }
2129         perf_sample__fprintf_start(sample, thread, evsel,
2130                                    PERF_RECORD_MMAP, stdout);
2131         perf_event__fprintf(event, stdout);
2132         thread__put(thread);
2133         return 0;
2134 }
2135
2136 static int process_mmap2_event(struct perf_tool *tool,
2137                               union perf_event *event,
2138                               struct perf_sample *sample,
2139                               struct machine *machine)
2140 {
2141         struct thread *thread;
2142         struct perf_script *script = container_of(tool, struct perf_script, tool);
2143         struct perf_session *session = script->session;
2144         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2145
2146         if (perf_event__process_mmap2(tool, event, sample, machine) < 0)
2147                 return -1;
2148
2149         thread = machine__findnew_thread(machine, event->mmap2.pid, event->mmap2.tid);
2150         if (thread == NULL) {
2151                 pr_debug("problem processing MMAP2 event, skipping it.\n");
2152                 return -1;
2153         }
2154
2155         if (!evsel->attr.sample_id_all) {
2156                 sample->cpu = 0;
2157                 sample->time = 0;
2158                 sample->tid = event->mmap2.tid;
2159                 sample->pid = event->mmap2.pid;
2160         }
2161         perf_sample__fprintf_start(sample, thread, evsel,
2162                                    PERF_RECORD_MMAP2, stdout);
2163         perf_event__fprintf(event, stdout);
2164         thread__put(thread);
2165         return 0;
2166 }
2167
2168 static int process_switch_event(struct perf_tool *tool,
2169                                 union perf_event *event,
2170                                 struct perf_sample *sample,
2171                                 struct machine *machine)
2172 {
2173         struct thread *thread;
2174         struct perf_script *script = container_of(tool, struct perf_script, tool);
2175         struct perf_session *session = script->session;
2176         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2177
2178         if (perf_event__process_switch(tool, event, sample, machine) < 0)
2179                 return -1;
2180
2181         thread = machine__findnew_thread(machine, sample->pid,
2182                                          sample->tid);
2183         if (thread == NULL) {
2184                 pr_debug("problem processing SWITCH event, skipping it.\n");
2185                 return -1;
2186         }
2187
2188         perf_sample__fprintf_start(sample, thread, evsel,
2189                                    PERF_RECORD_SWITCH, stdout);
2190         perf_event__fprintf(event, stdout);
2191         thread__put(thread);
2192         return 0;
2193 }
2194
2195 static int
2196 process_lost_event(struct perf_tool *tool,
2197                    union perf_event *event,
2198                    struct perf_sample *sample,
2199                    struct machine *machine)
2200 {
2201         struct perf_script *script = container_of(tool, struct perf_script, tool);
2202         struct perf_session *session = script->session;
2203         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2204         struct thread *thread;
2205
2206         thread = machine__findnew_thread(machine, sample->pid,
2207                                          sample->tid);
2208         if (thread == NULL)
2209                 return -1;
2210
2211         perf_sample__fprintf_start(sample, thread, evsel,
2212                                    PERF_RECORD_LOST, stdout);
2213         perf_event__fprintf(event, stdout);
2214         thread__put(thread);
2215         return 0;
2216 }
2217
2218 static int
2219 process_finished_round_event(struct perf_tool *tool __maybe_unused,
2220                              union perf_event *event,
2221                              struct ordered_events *oe __maybe_unused)
2222
2223 {
2224         perf_event__fprintf(event, stdout);
2225         return 0;
2226 }
2227
2228 static void sig_handler(int sig __maybe_unused)
2229 {
2230         session_done = 1;
2231 }
2232
2233 static void perf_script__fclose_per_event_dump(struct perf_script *script)
2234 {
2235         struct perf_evlist *evlist = script->session->evlist;
2236         struct perf_evsel *evsel;
2237
2238         evlist__for_each_entry(evlist, evsel) {
2239                 if (!evsel->priv)
2240                         break;
2241                 perf_evsel_script__delete(evsel->priv);
2242                 evsel->priv = NULL;
2243         }
2244 }
2245
2246 static int perf_script__fopen_per_event_dump(struct perf_script *script)
2247 {
2248         struct perf_evsel *evsel;
2249
2250         evlist__for_each_entry(script->session->evlist, evsel) {
2251                 /*
2252                  * Already setup? I.e. we may be called twice in cases like
2253                  * Intel PT, one for the intel_pt// and dummy events, then
2254                  * for the evsels syntheized from the auxtrace info.
2255                  *
2256                  * Ses perf_script__process_auxtrace_info.
2257                  */
2258                 if (evsel->priv != NULL)
2259                         continue;
2260
2261                 evsel->priv = perf_evsel_script__new(evsel, script->session->data);
2262                 if (evsel->priv == NULL)
2263                         goto out_err_fclose;
2264         }
2265
2266         return 0;
2267
2268 out_err_fclose:
2269         perf_script__fclose_per_event_dump(script);
2270         return -1;
2271 }
2272
2273 static int perf_script__setup_per_event_dump(struct perf_script *script)
2274 {
2275         struct perf_evsel *evsel;
2276         static struct perf_evsel_script es_stdout;
2277
2278         if (script->per_event_dump)
2279                 return perf_script__fopen_per_event_dump(script);
2280
2281         es_stdout.fp = stdout;
2282
2283         evlist__for_each_entry(script->session->evlist, evsel)
2284                 evsel->priv = &es_stdout;
2285
2286         return 0;
2287 }
2288
2289 static void perf_script__exit_per_event_dump_stats(struct perf_script *script)
2290 {
2291         struct perf_evsel *evsel;
2292
2293         evlist__for_each_entry(script->session->evlist, evsel) {
2294                 struct perf_evsel_script *es = evsel->priv;
2295
2296                 perf_evsel_script__fprintf(es, stdout);
2297                 perf_evsel_script__delete(es);
2298                 evsel->priv = NULL;
2299         }
2300 }
2301
2302 static int __cmd_script(struct perf_script *script)
2303 {
2304         int ret;
2305
2306         signal(SIGINT, sig_handler);
2307
2308         /* override event processing functions */
2309         if (script->show_task_events) {
2310                 script->tool.comm = process_comm_event;
2311                 script->tool.fork = process_fork_event;
2312                 script->tool.exit = process_exit_event;
2313         }
2314         if (script->show_mmap_events) {
2315                 script->tool.mmap = process_mmap_event;
2316                 script->tool.mmap2 = process_mmap2_event;
2317         }
2318         if (script->show_switch_events)
2319                 script->tool.context_switch = process_switch_event;
2320         if (script->show_namespace_events)
2321                 script->tool.namespaces = process_namespaces_event;
2322         if (script->show_lost_events)
2323                 script->tool.lost = process_lost_event;
2324         if (script->show_round_events) {
2325                 script->tool.ordered_events = false;
2326                 script->tool.finished_round = process_finished_round_event;
2327         }
2328
2329         if (perf_script__setup_per_event_dump(script)) {
2330                 pr_err("Couldn't create the per event dump files\n");
2331                 return -1;
2332         }
2333
2334         ret = perf_session__process_events(script->session);
2335
2336         if (script->per_event_dump)
2337                 perf_script__exit_per_event_dump_stats(script);
2338
2339         if (debug_mode)
2340                 pr_err("Misordered timestamps: %" PRIu64 "\n", nr_unordered);
2341
2342         return ret;
2343 }
2344
2345 struct script_spec {
2346         struct list_head        node;
2347         struct scripting_ops    *ops;
2348         char                    spec[0];
2349 };
2350
2351 static LIST_HEAD(script_specs);
2352
2353 static struct script_spec *script_spec__new(const char *spec,
2354                                             struct scripting_ops *ops)
2355 {
2356         struct script_spec *s = malloc(sizeof(*s) + strlen(spec) + 1);
2357
2358         if (s != NULL) {
2359                 strcpy(s->spec, spec);
2360                 s->ops = ops;
2361         }
2362
2363         return s;
2364 }
2365
2366 static void script_spec__add(struct script_spec *s)
2367 {
2368         list_add_tail(&s->node, &script_specs);
2369 }
2370
2371 static struct script_spec *script_spec__find(const char *spec)
2372 {
2373         struct script_spec *s;
2374
2375         list_for_each_entry(s, &script_specs, node)
2376                 if (strcasecmp(s->spec, spec) == 0)
2377                         return s;
2378         return NULL;
2379 }
2380
2381 int script_spec_register(const char *spec, struct scripting_ops *ops)
2382 {
2383         struct script_spec *s;
2384
2385         s = script_spec__find(spec);
2386         if (s)
2387                 return -1;
2388
2389         s = script_spec__new(spec, ops);
2390         if (!s)
2391                 return -1;
2392         else
2393                 script_spec__add(s);
2394
2395         return 0;
2396 }
2397
2398 static struct scripting_ops *script_spec__lookup(const char *spec)
2399 {
2400         struct script_spec *s = script_spec__find(spec);
2401         if (!s)
2402                 return NULL;
2403
2404         return s->ops;
2405 }
2406
2407 static void list_available_languages(void)
2408 {
2409         struct script_spec *s;
2410
2411         fprintf(stderr, "\n");
2412         fprintf(stderr, "Scripting language extensions (used in "
2413                 "perf script -s [spec:]script.[spec]):\n\n");
2414
2415         list_for_each_entry(s, &script_specs, node)
2416                 fprintf(stderr, "  %-42s [%s]\n", s->spec, s->ops->name);
2417
2418         fprintf(stderr, "\n");
2419 }
2420
2421 static int parse_scriptname(const struct option *opt __maybe_unused,
2422                             const char *str, int unset __maybe_unused)
2423 {
2424         char spec[PATH_MAX];
2425         const char *script, *ext;
2426         int len;
2427
2428         if (strcmp(str, "lang") == 0) {
2429                 list_available_languages();
2430                 exit(0);
2431         }
2432
2433         script = strchr(str, ':');
2434         if (script) {
2435                 len = script - str;
2436                 if (len >= PATH_MAX) {
2437                         fprintf(stderr, "invalid language specifier");
2438                         return -1;
2439                 }
2440                 strncpy(spec, str, len);
2441                 spec[len] = '\0';
2442                 scripting_ops = script_spec__lookup(spec);
2443                 if (!scripting_ops) {
2444                         fprintf(stderr, "invalid language specifier");
2445                         return -1;
2446                 }
2447                 script++;
2448         } else {
2449                 script = str;
2450                 ext = strrchr(script, '.');
2451                 if (!ext) {
2452                         fprintf(stderr, "invalid script extension");
2453                         return -1;
2454                 }
2455                 scripting_ops = script_spec__lookup(++ext);
2456                 if (!scripting_ops) {
2457                         fprintf(stderr, "invalid script extension");
2458                         return -1;
2459                 }
2460         }
2461
2462         script_name = strdup(script);
2463
2464         return 0;
2465 }
2466
2467 static int parse_output_fields(const struct option *opt __maybe_unused,
2468                             const char *arg, int unset __maybe_unused)
2469 {
2470         char *tok, *strtok_saveptr = NULL;
2471         int i, imax = ARRAY_SIZE(all_output_options);
2472         int j;
2473         int rc = 0;
2474         char *str = strdup(arg);
2475         int type = -1;
2476         enum { DEFAULT, SET, ADD, REMOVE } change = DEFAULT;
2477
2478         if (!str)
2479                 return -ENOMEM;
2480
2481         /* first word can state for which event type the user is specifying
2482          * the fields. If no type exists, the specified fields apply to all
2483          * event types found in the file minus the invalid fields for a type.
2484          */
2485         tok = strchr(str, ':');
2486         if (tok) {
2487                 *tok = '\0';
2488                 tok++;
2489                 if (!strcmp(str, "hw"))
2490                         type = PERF_TYPE_HARDWARE;
2491                 else if (!strcmp(str, "sw"))
2492                         type = PERF_TYPE_SOFTWARE;
2493                 else if (!strcmp(str, "trace"))
2494                         type = PERF_TYPE_TRACEPOINT;
2495                 else if (!strcmp(str, "raw"))
2496                         type = PERF_TYPE_RAW;
2497                 else if (!strcmp(str, "break"))
2498                         type = PERF_TYPE_BREAKPOINT;
2499                 else if (!strcmp(str, "synth"))
2500                         type = OUTPUT_TYPE_SYNTH;
2501                 else {
2502                         fprintf(stderr, "Invalid event type in field string.\n");
2503                         rc = -EINVAL;
2504                         goto out;
2505                 }
2506
2507                 if (output[type].user_set)
2508                         pr_warning("Overriding previous field request for %s events.\n",
2509                                    event_type(type));
2510
2511                 output[type].fields = 0;
2512                 output[type].user_set = true;
2513                 output[type].wildcard_set = false;
2514
2515         } else {
2516                 tok = str;
2517                 if (strlen(str) == 0) {
2518                         fprintf(stderr,
2519                                 "Cannot set fields to 'none' for all event types.\n");
2520                         rc = -EINVAL;
2521                         goto out;
2522                 }
2523
2524                 /* Don't override defaults for +- */
2525                 if (strchr(str, '+') || strchr(str, '-'))
2526                         goto parse;
2527
2528                 if (output_set_by_user())
2529                         pr_warning("Overriding previous field request for all events.\n");
2530
2531                 for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
2532                         output[j].fields = 0;
2533                         output[j].user_set = true;
2534                         output[j].wildcard_set = true;
2535                 }
2536         }
2537
2538 parse:
2539         for (tok = strtok_r(tok, ",", &strtok_saveptr); tok; tok = strtok_r(NULL, ",", &strtok_saveptr)) {
2540                 if (*tok == '+') {
2541                         if (change == SET)
2542                                 goto out_badmix;
2543                         change = ADD;
2544                         tok++;
2545                 } else if (*tok == '-') {
2546                         if (change == SET)
2547                                 goto out_badmix;
2548                         change = REMOVE;
2549                         tok++;
2550                 } else {
2551                         if (change != SET && change != DEFAULT)
2552                                 goto out_badmix;
2553                         change = SET;
2554                 }
2555
2556                 for (i = 0; i < imax; ++i) {
2557                         if (strcmp(tok, all_output_options[i].str) == 0)
2558                                 break;
2559                 }
2560                 if (i == imax && strcmp(tok, "flags") == 0) {
2561                         print_flags = change == REMOVE ? false : true;
2562                         continue;
2563                 }
2564                 if (i == imax) {
2565                         fprintf(stderr, "Invalid field requested.\n");
2566                         rc = -EINVAL;
2567                         goto out;
2568                 }
2569
2570                 if (type == -1) {
2571                         /* add user option to all events types for
2572                          * which it is valid
2573                          */
2574                         for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
2575                                 if (output[j].invalid_fields & all_output_options[i].field) {
2576                                         pr_warning("\'%s\' not valid for %s events. Ignoring.\n",
2577                                                    all_output_options[i].str, event_type(j));
2578                                 } else {
2579                                         if (change == REMOVE)
2580                                                 output[j].fields &= ~all_output_options[i].field;
2581                                         else
2582                                                 output[j].fields |= all_output_options[i].field;
2583                                         output[j].user_set = true;
2584                                         output[j].wildcard_set = true;
2585                                 }
2586                         }
2587                 } else {
2588                         if (output[type].invalid_fields & all_output_options[i].field) {
2589                                 fprintf(stderr, "\'%s\' not valid for %s events.\n",
2590                                          all_output_options[i].str, event_type(type));
2591
2592                                 rc = -EINVAL;
2593                                 goto out;
2594                         }
2595                         output[type].user_set = true;
2596                         output[type].wildcard_set = true;
2597                 }
2598         }
2599
2600         if (type >= 0) {
2601                 if (output[type].fields == 0) {
2602                         pr_debug("No fields requested for %s type. "
2603                                  "Events will not be displayed.\n", event_type(type));
2604                 }
2605         }
2606         goto out;
2607
2608 out_badmix:
2609         fprintf(stderr, "Cannot mix +-field with overridden fields\n");
2610         rc = -EINVAL;
2611 out:
2612         free(str);
2613         return rc;
2614 }
2615
2616 #define for_each_lang(scripts_path, scripts_dir, lang_dirent)           \
2617         while ((lang_dirent = readdir(scripts_dir)) != NULL)            \
2618                 if ((lang_dirent->d_type == DT_DIR ||                   \
2619                      (lang_dirent->d_type == DT_UNKNOWN &&              \
2620                       is_directory(scripts_path, lang_dirent))) &&      \
2621                     (strcmp(lang_dirent->d_name, ".")) &&               \
2622                     (strcmp(lang_dirent->d_name, "..")))
2623
2624 #define for_each_script(lang_path, lang_dir, script_dirent)             \
2625         while ((script_dirent = readdir(lang_dir)) != NULL)             \
2626                 if (script_dirent->d_type != DT_DIR &&                  \
2627                     (script_dirent->d_type != DT_UNKNOWN ||             \
2628                      !is_directory(lang_path, script_dirent)))
2629
2630
2631 #define RECORD_SUFFIX                   "-record"
2632 #define REPORT_SUFFIX                   "-report"
2633
2634 struct script_desc {
2635         struct list_head        node;
2636         char                    *name;
2637         char                    *half_liner;
2638         char                    *args;
2639 };
2640
2641 static LIST_HEAD(script_descs);
2642
2643 static struct script_desc *script_desc__new(const char *name)
2644 {
2645         struct script_desc *s = zalloc(sizeof(*s));
2646
2647         if (s != NULL && name)
2648                 s->name = strdup(name);
2649
2650         return s;
2651 }
2652
2653 static void script_desc__delete(struct script_desc *s)
2654 {
2655         zfree(&s->name);
2656         zfree(&s->half_liner);
2657         zfree(&s->args);
2658         free(s);
2659 }
2660
2661 static void script_desc__add(struct script_desc *s)
2662 {
2663         list_add_tail(&s->node, &script_descs);
2664 }
2665
2666 static struct script_desc *script_desc__find(const char *name)
2667 {
2668         struct script_desc *s;
2669
2670         list_for_each_entry(s, &script_descs, node)
2671                 if (strcasecmp(s->name, name) == 0)
2672                         return s;
2673         return NULL;
2674 }
2675
2676 static struct script_desc *script_desc__findnew(const char *name)
2677 {
2678         struct script_desc *s = script_desc__find(name);
2679
2680         if (s)
2681                 return s;
2682
2683         s = script_desc__new(name);
2684         if (!s)
2685                 return NULL;
2686
2687         script_desc__add(s);
2688
2689         return s;
2690 }
2691
2692 static const char *ends_with(const char *str, const char *suffix)
2693 {
2694         size_t suffix_len = strlen(suffix);
2695         const char *p = str;
2696
2697         if (strlen(str) > suffix_len) {
2698                 p = str + strlen(str) - suffix_len;
2699                 if (!strncmp(p, suffix, suffix_len))
2700                         return p;
2701         }
2702
2703         return NULL;
2704 }
2705
2706 static int read_script_info(struct script_desc *desc, const char *filename)
2707 {
2708         char line[BUFSIZ], *p;
2709         FILE *fp;
2710
2711         fp = fopen(filename, "r");
2712         if (!fp)
2713                 return -1;
2714
2715         while (fgets(line, sizeof(line), fp)) {
2716                 p = ltrim(line);
2717                 if (strlen(p) == 0)
2718                         continue;
2719                 if (*p != '#')
2720                         continue;
2721                 p++;
2722                 if (strlen(p) && *p == '!')
2723                         continue;
2724
2725                 p = ltrim(p);
2726                 if (strlen(p) && p[strlen(p) - 1] == '\n')
2727                         p[strlen(p) - 1] = '\0';
2728
2729                 if (!strncmp(p, "description:", strlen("description:"))) {
2730                         p += strlen("description:");
2731                         desc->half_liner = strdup(ltrim(p));
2732                         continue;
2733                 }
2734
2735                 if (!strncmp(p, "args:", strlen("args:"))) {
2736                         p += strlen("args:");
2737                         desc->args = strdup(ltrim(p));
2738                         continue;
2739                 }
2740         }
2741
2742         fclose(fp);
2743
2744         return 0;
2745 }
2746
2747 static char *get_script_root(struct dirent *script_dirent, const char *suffix)
2748 {
2749         char *script_root, *str;
2750
2751         script_root = strdup(script_dirent->d_name);
2752         if (!script_root)
2753                 return NULL;
2754
2755         str = (char *)ends_with(script_root, suffix);
2756         if (!str) {
2757                 free(script_root);
2758                 return NULL;
2759         }
2760
2761         *str = '\0';
2762         return script_root;
2763 }
2764
2765 static int list_available_scripts(const struct option *opt __maybe_unused,
2766                                   const char *s __maybe_unused,
2767                                   int unset __maybe_unused)
2768 {
2769         struct dirent *script_dirent, *lang_dirent;
2770         char scripts_path[MAXPATHLEN];
2771         DIR *scripts_dir, *lang_dir;
2772         char script_path[MAXPATHLEN];
2773         char lang_path[MAXPATHLEN];
2774         struct script_desc *desc;
2775         char first_half[BUFSIZ];
2776         char *script_root;
2777
2778         snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2779
2780         scripts_dir = opendir(scripts_path);
2781         if (!scripts_dir) {
2782                 fprintf(stdout,
2783                         "open(%s) failed.\n"
2784                         "Check \"PERF_EXEC_PATH\" env to set scripts dir.\n",
2785                         scripts_path);
2786                 exit(-1);
2787         }
2788
2789         for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2790                 scnprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
2791                           lang_dirent->d_name);
2792                 lang_dir = opendir(lang_path);
2793                 if (!lang_dir)
2794                         continue;
2795
2796                 for_each_script(lang_path, lang_dir, script_dirent) {
2797                         script_root = get_script_root(script_dirent, REPORT_SUFFIX);
2798                         if (script_root) {
2799                                 desc = script_desc__findnew(script_root);
2800                                 scnprintf(script_path, MAXPATHLEN, "%s/%s",
2801                                           lang_path, script_dirent->d_name);
2802                                 read_script_info(desc, script_path);
2803                                 free(script_root);
2804                         }
2805                 }
2806         }
2807
2808         fprintf(stdout, "List of available trace scripts:\n");
2809         list_for_each_entry(desc, &script_descs, node) {
2810                 sprintf(first_half, "%s %s", desc->name,
2811                         desc->args ? desc->args : "");
2812                 fprintf(stdout, "  %-36s %s\n", first_half,
2813                         desc->half_liner ? desc->half_liner : "");
2814         }
2815
2816         exit(0);
2817 }
2818
2819 /*
2820  * Some scripts specify the required events in their "xxx-record" file,
2821  * this function will check if the events in perf.data match those
2822  * mentioned in the "xxx-record".
2823  *
2824  * Fixme: All existing "xxx-record" are all in good formats "-e event ",
2825  * which is covered well now. And new parsing code should be added to
2826  * cover the future complexing formats like event groups etc.
2827  */
2828 static int check_ev_match(char *dir_name, char *scriptname,
2829                         struct perf_session *session)
2830 {
2831         char filename[MAXPATHLEN], evname[128];
2832         char line[BUFSIZ], *p;
2833         struct perf_evsel *pos;
2834         int match, len;
2835         FILE *fp;
2836
2837         scnprintf(filename, MAXPATHLEN, "%s/bin/%s-record", dir_name, scriptname);
2838
2839         fp = fopen(filename, "r");
2840         if (!fp)
2841                 return -1;
2842
2843         while (fgets(line, sizeof(line), fp)) {
2844                 p = ltrim(line);
2845                 if (*p == '#')
2846                         continue;
2847
2848                 while (strlen(p)) {
2849                         p = strstr(p, "-e");
2850                         if (!p)
2851                                 break;
2852
2853                         p += 2;
2854                         p = ltrim(p);
2855                         len = strcspn(p, " \t");
2856                         if (!len)
2857                                 break;
2858
2859                         snprintf(evname, len + 1, "%s", p);
2860
2861                         match = 0;
2862                         evlist__for_each_entry(session->evlist, pos) {
2863                                 if (!strcmp(perf_evsel__name(pos), evname)) {
2864                                         match = 1;
2865                                         break;
2866                                 }
2867                         }
2868
2869                         if (!match) {
2870                                 fclose(fp);
2871                                 return -1;
2872                         }
2873                 }
2874         }
2875
2876         fclose(fp);
2877         return 0;
2878 }
2879
2880 /*
2881  * Return -1 if none is found, otherwise the actual scripts number.
2882  *
2883  * Currently the only user of this function is the script browser, which
2884  * will list all statically runnable scripts, select one, execute it and
2885  * show the output in a perf browser.
2886  */
2887 int find_scripts(char **scripts_array, char **scripts_path_array)
2888 {
2889         struct dirent *script_dirent, *lang_dirent;
2890         char scripts_path[MAXPATHLEN], lang_path[MAXPATHLEN];
2891         DIR *scripts_dir, *lang_dir;
2892         struct perf_session *session;
2893         struct perf_data data = {
2894                 .file      = {
2895                         .path = input_name,
2896                 },
2897                 .mode      = PERF_DATA_MODE_READ,
2898         };
2899         char *temp;
2900         int i = 0;
2901
2902         session = perf_session__new(&data, false, NULL);
2903         if (!session)
2904                 return -1;
2905
2906         snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2907
2908         scripts_dir = opendir(scripts_path);
2909         if (!scripts_dir) {
2910                 perf_session__delete(session);
2911                 return -1;
2912         }
2913
2914         for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2915                 scnprintf(lang_path, MAXPATHLEN, "%s/%s", scripts_path,
2916                           lang_dirent->d_name);
2917 #ifndef HAVE_LIBPERL_SUPPORT
2918                 if (strstr(lang_path, "perl"))
2919                         continue;
2920 #endif
2921 #ifndef HAVE_LIBPYTHON_SUPPORT
2922                 if (strstr(lang_path, "python"))
2923                         continue;
2924 #endif
2925
2926                 lang_dir = opendir(lang_path);
2927                 if (!lang_dir)
2928                         continue;
2929
2930                 for_each_script(lang_path, lang_dir, script_dirent) {
2931                         /* Skip those real time scripts: xxxtop.p[yl] */
2932                         if (strstr(script_dirent->d_name, "top."))
2933                                 continue;
2934                         sprintf(scripts_path_array[i], "%s/%s", lang_path,
2935                                 script_dirent->d_name);
2936                         temp = strchr(script_dirent->d_name, '.');
2937                         snprintf(scripts_array[i],
2938                                 (temp - script_dirent->d_name) + 1,
2939                                 "%s", script_dirent->d_name);
2940
2941                         if (check_ev_match(lang_path,
2942                                         scripts_array[i], session))
2943                                 continue;
2944
2945                         i++;
2946                 }
2947                 closedir(lang_dir);
2948         }
2949
2950         closedir(scripts_dir);
2951         perf_session__delete(session);
2952         return i;
2953 }
2954
2955 static char *get_script_path(const char *script_root, const char *suffix)
2956 {
2957         struct dirent *script_dirent, *lang_dirent;
2958         char scripts_path[MAXPATHLEN];
2959         char script_path[MAXPATHLEN];
2960         DIR *scripts_dir, *lang_dir;
2961         char lang_path[MAXPATHLEN];
2962         char *__script_root;
2963
2964         snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2965
2966         scripts_dir = opendir(scripts_path);
2967         if (!scripts_dir)
2968                 return NULL;
2969
2970         for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2971                 scnprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
2972                           lang_dirent->d_name);
2973                 lang_dir = opendir(lang_path);
2974                 if (!lang_dir)
2975                         continue;
2976
2977                 for_each_script(lang_path, lang_dir, script_dirent) {
2978                         __script_root = get_script_root(script_dirent, suffix);
2979                         if (__script_root && !strcmp(script_root, __script_root)) {
2980                                 free(__script_root);
2981                                 closedir(lang_dir);
2982                                 closedir(scripts_dir);
2983                                 scnprintf(script_path, MAXPATHLEN, "%s/%s",
2984                                           lang_path, script_dirent->d_name);
2985                                 return strdup(script_path);
2986                         }
2987                         free(__script_root);
2988                 }
2989                 closedir(lang_dir);
2990         }
2991         closedir(scripts_dir);
2992
2993         return NULL;
2994 }
2995
2996 static bool is_top_script(const char *script_path)
2997 {
2998         return ends_with(script_path, "top") == NULL ? false : true;
2999 }
3000
3001 static int has_required_arg(char *script_path)
3002 {
3003         struct script_desc *desc;
3004         int n_args = 0;
3005         char *p;
3006
3007         desc = script_desc__new(NULL);
3008
3009         if (read_script_info(desc, script_path))
3010                 goto out;
3011
3012         if (!desc->args)
3013                 goto out;
3014
3015         for (p = desc->args; *p; p++)
3016                 if (*p == '<')
3017                         n_args++;
3018 out:
3019         script_desc__delete(desc);
3020
3021         return n_args;
3022 }
3023
3024 static int have_cmd(int argc, const char **argv)
3025 {
3026         char **__argv = malloc(sizeof(const char *) * argc);
3027
3028         if (!__argv) {
3029                 pr_err("malloc failed\n");
3030                 return -1;
3031         }
3032
3033         memcpy(__argv, argv, sizeof(const char *) * argc);
3034         argc = parse_options(argc, (const char **)__argv, record_options,
3035                              NULL, PARSE_OPT_STOP_AT_NON_OPTION);
3036         free(__argv);
3037
3038         system_wide = (argc == 0);
3039
3040         return 0;
3041 }
3042
3043 static void script__setup_sample_type(struct perf_script *script)
3044 {
3045         struct perf_session *session = script->session;
3046         u64 sample_type = perf_evlist__combined_sample_type(session->evlist);
3047
3048         if (symbol_conf.use_callchain || symbol_conf.cumulate_callchain) {
3049                 if ((sample_type & PERF_SAMPLE_REGS_USER) &&
3050                     (sample_type & PERF_SAMPLE_STACK_USER)) {
3051                         callchain_param.record_mode = CALLCHAIN_DWARF;
3052                         dwarf_callchain_users = true;
3053                 } else if (sample_type & PERF_SAMPLE_BRANCH_STACK)
3054                         callchain_param.record_mode = CALLCHAIN_LBR;
3055                 else
3056                         callchain_param.record_mode = CALLCHAIN_FP;
3057         }
3058 }
3059
3060 static int process_stat_round_event(struct perf_session *session,
3061                                     union perf_event *event)
3062 {
3063         struct stat_round_event *round = &event->stat_round;
3064         struct perf_evsel *counter;
3065
3066         evlist__for_each_entry(session->evlist, counter) {
3067                 perf_stat_process_counter(&stat_config, counter);
3068                 process_stat(counter, round->time);
3069         }
3070
3071         process_stat_interval(round->time);
3072         return 0;
3073 }
3074
3075 static int process_stat_config_event(struct perf_session *session __maybe_unused,
3076                                      union perf_event *event)
3077 {
3078         perf_event__read_stat_config(&stat_config, &event->stat_config);
3079         return 0;
3080 }
3081
3082 static int set_maps(struct perf_script *script)
3083 {
3084         struct perf_evlist *evlist = script->session->evlist;
3085
3086         if (!script->cpus || !script->threads)
3087                 return 0;
3088
3089         if (WARN_ONCE(script->allocated, "stats double allocation\n"))
3090                 return -EINVAL;
3091
3092         perf_evlist__set_maps(evlist, script->cpus, script->threads);
3093
3094         if (perf_evlist__alloc_stats(evlist, true))
3095                 return -ENOMEM;
3096
3097         script->allocated = true;
3098         return 0;
3099 }
3100
3101 static
3102 int process_thread_map_event(struct perf_session *session,
3103                              union perf_event *event)
3104 {
3105         struct perf_tool *tool = session->tool;
3106         struct perf_script *script = container_of(tool, struct perf_script, tool);
3107
3108         if (script->threads) {
3109                 pr_warning("Extra thread map event, ignoring.\n");
3110                 return 0;
3111         }
3112
3113         script->threads = thread_map__new_event(&event->thread_map);
3114         if (!script->threads)
3115                 return -ENOMEM;
3116
3117         return set_maps(script);
3118 }
3119
3120 static
3121 int process_cpu_map_event(struct perf_session *session,
3122                           union perf_event *event)
3123 {
3124         struct perf_tool *tool = session->tool;
3125         struct perf_script *script = container_of(tool, struct perf_script, tool);
3126
3127         if (script->cpus) {
3128                 pr_warning("Extra cpu map event, ignoring.\n");
3129                 return 0;
3130         }
3131
3132         script->cpus = cpu_map__new_data(&event->cpu_map.data);
3133         if (!script->cpus)
3134                 return -ENOMEM;
3135
3136         return set_maps(script);
3137 }
3138
3139 static int process_feature_event(struct perf_session *session,
3140                                  union perf_event *event)
3141 {
3142         if (event->feat.feat_id < HEADER_LAST_FEATURE)
3143                 return perf_event__process_feature(session, event);
3144         return 0;
3145 }
3146
3147 #ifdef HAVE_AUXTRACE_SUPPORT
3148 static int perf_script__process_auxtrace_info(struct perf_session *session,
3149                                               union perf_event *event)
3150 {
3151         struct perf_tool *tool = session->tool;
3152
3153         int ret = perf_event__process_auxtrace_info(session, event);
3154
3155         if (ret == 0) {
3156                 struct perf_script *script = container_of(tool, struct perf_script, tool);
3157
3158                 ret = perf_script__setup_per_event_dump(script);
3159         }
3160
3161         return ret;
3162 }
3163 #else
3164 #define perf_script__process_auxtrace_info 0
3165 #endif
3166
3167 static int parse_insn_trace(const struct option *opt __maybe_unused,
3168                             const char *str __maybe_unused,
3169                             int unset __maybe_unused)
3170 {
3171         parse_output_fields(NULL, "+insn,-event,-period", 0);
3172         itrace_parse_synth_opts(opt, "i0ns", 0);
3173         nanosecs = true;
3174         return 0;
3175 }
3176
3177 static int parse_xed(const struct option *opt __maybe_unused,
3178                      const char *str __maybe_unused,
3179                      int unset __maybe_unused)
3180 {
3181         force_pager("xed -F insn: -A -64 | less");
3182         return 0;
3183 }
3184
3185 static int parse_call_trace(const struct option *opt __maybe_unused,
3186                             const char *str __maybe_unused,
3187                             int unset __maybe_unused)
3188 {
3189         parse_output_fields(NULL, "-ip,-addr,-event,-period,+callindent", 0);
3190         itrace_parse_synth_opts(opt, "cewp", 0);
3191         nanosecs = true;
3192         return 0;
3193 }
3194
3195 static int parse_callret_trace(const struct option *opt __maybe_unused,
3196                             const char *str __maybe_unused,
3197                             int unset __maybe_unused)
3198 {
3199         parse_output_fields(NULL, "-ip,-addr,-event,-period,+callindent,+flags", 0);
3200         itrace_parse_synth_opts(opt, "crewp", 0);
3201         nanosecs = true;
3202         return 0;
3203 }
3204
3205 int cmd_script(int argc, const char **argv)
3206 {
3207         bool show_full_info = false;
3208         bool header = false;
3209         bool header_only = false;
3210         bool script_started = false;
3211         char *rec_script_path = NULL;
3212         char *rep_script_path = NULL;
3213         struct perf_session *session;
3214         struct itrace_synth_opts itrace_synth_opts = {
3215                 .set = false,
3216                 .default_no_sample = true,
3217         };
3218         char *script_path = NULL;
3219         const char **__argv;
3220         int i, j, err = 0;
3221         struct perf_script script = {
3222                 .tool = {
3223                         .sample          = process_sample_event,
3224                         .mmap            = perf_event__process_mmap,
3225                         .mmap2           = perf_event__process_mmap2,
3226                         .comm            = perf_event__process_comm,
3227                         .namespaces      = perf_event__process_namespaces,
3228                         .exit            = perf_event__process_exit,
3229                         .fork            = perf_event__process_fork,
3230                         .attr            = process_attr,
3231                         .event_update   = perf_event__process_event_update,
3232                         .tracing_data    = perf_event__process_tracing_data,
3233                         .feature         = process_feature_event,
3234                         .build_id        = perf_event__process_build_id,
3235                         .id_index        = perf_event__process_id_index,
3236                         .auxtrace_info   = perf_script__process_auxtrace_info,
3237                         .auxtrace        = perf_event__process_auxtrace,
3238                         .auxtrace_error  = perf_event__process_auxtrace_error,
3239                         .stat            = perf_event__process_stat_event,
3240                         .stat_round      = process_stat_round_event,
3241                         .stat_config     = process_stat_config_event,
3242                         .thread_map      = process_thread_map_event,
3243                         .cpu_map         = process_cpu_map_event,
3244                         .ordered_events  = true,
3245                         .ordering_requires_timestamps = true,
3246                 },
3247         };
3248         struct perf_data data = {
3249                 .mode = PERF_DATA_MODE_READ,
3250         };
3251         const struct option options[] = {
3252         OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
3253                     "dump raw trace in ASCII"),
3254         OPT_INCR('v', "verbose", &verbose,
3255                  "be more verbose (show symbol address, etc)"),
3256         OPT_BOOLEAN('L', "Latency", &latency_format,
3257                     "show latency attributes (irqs/preemption disabled, etc)"),
3258         OPT_CALLBACK_NOOPT('l', "list", NULL, NULL, "list available scripts",
3259                            list_available_scripts),
3260         OPT_CALLBACK('s', "script", NULL, "name",
3261                      "script file name (lang:script name, script name, or *)",
3262                      parse_scriptname),
3263         OPT_STRING('g', "gen-script", &generate_script_lang, "lang",
3264                    "generate perf-script.xx script in specified language"),
3265         OPT_STRING('i', "input", &input_name, "file", "input file name"),
3266         OPT_BOOLEAN('d', "debug-mode", &debug_mode,
3267                    "do various checks like samples ordering and lost events"),
3268         OPT_BOOLEAN(0, "header", &header, "Show data header."),
3269         OPT_BOOLEAN(0, "header-only", &header_only, "Show only data header."),
3270         OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
3271                    "file", "vmlinux pathname"),
3272         OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
3273                    "file", "kallsyms pathname"),
3274         OPT_BOOLEAN('G', "hide-call-graph", &no_callchain,
3275                     "When printing symbols do not display call chain"),
3276         OPT_CALLBACK(0, "symfs", NULL, "directory",
3277                      "Look for files with symbols relative to this directory",
3278                      symbol__config_symfs),
3279         OPT_CALLBACK('F', "fields", NULL, "str",
3280                      "comma separated output fields prepend with 'type:'. "
3281                      "+field to add and -field to remove."
3282                      "Valid types: hw,sw,trace,raw,synth. "
3283                      "Fields: comm,tid,pid,time,cpu,event,trace,ip,sym,dso,"
3284                      "addr,symoff,srcline,period,iregs,uregs,brstack,"
3285                      "brstacksym,flags,bpf-output,brstackinsn,brstackoff,"
3286                      "callindent,insn,insnlen,synth,phys_addr,metric,misc",
3287                      parse_output_fields),
3288         OPT_BOOLEAN('a', "all-cpus", &system_wide,
3289                     "system-wide collection from all CPUs"),
3290         OPT_STRING('S', "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
3291                    "only consider these symbols"),
3292         OPT_CALLBACK_OPTARG(0, "insn-trace", &itrace_synth_opts, NULL, NULL,
3293                         "Decode instructions from itrace", parse_insn_trace),
3294         OPT_CALLBACK_OPTARG(0, "xed", NULL, NULL, NULL,
3295                         "Run xed disassembler on output", parse_xed),
3296         OPT_CALLBACK_OPTARG(0, "call-trace", &itrace_synth_opts, NULL, NULL,
3297                         "Decode calls from from itrace", parse_call_trace),
3298         OPT_CALLBACK_OPTARG(0, "call-ret-trace", &itrace_synth_opts, NULL, NULL,
3299                         "Decode calls and returns from itrace", parse_callret_trace),
3300         OPT_STRING(0, "graph-function", &symbol_conf.graph_function, "symbol[,symbol...]",
3301                         "Only print symbols and callees with --call-trace/--call-ret-trace"),
3302         OPT_STRING(0, "stop-bt", &symbol_conf.bt_stop_list_str, "symbol[,symbol...]",
3303                    "Stop display of callgraph at these symbols"),
3304         OPT_STRING('C', "cpu", &cpu_list, "cpu", "list of cpus to profile"),
3305         OPT_STRING('c', "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
3306                    "only display events for these comms"),
3307         OPT_STRING(0, "pid", &symbol_conf.pid_list_str, "pid[,pid...]",
3308                    "only consider symbols in these pids"),
3309         OPT_STRING(0, "tid", &symbol_conf.tid_list_str, "tid[,tid...]",
3310                    "only consider symbols in these tids"),
3311         OPT_UINTEGER(0, "max-stack", &scripting_max_stack,
3312                      "Set the maximum stack depth when parsing the callchain, "
3313                      "anything beyond the specified depth will be ignored. "
3314                      "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
3315         OPT_BOOLEAN('I', "show-info", &show_full_info,
3316                     "display extended information from perf.data file"),
3317         OPT_BOOLEAN('\0', "show-kernel-path", &symbol_conf.show_kernel_path,
3318                     "Show the path of [kernel.kallsyms]"),
3319         OPT_BOOLEAN('\0', "show-task-events", &script.show_task_events,
3320                     "Show the fork/comm/exit events"),
3321         OPT_BOOLEAN('\0', "show-mmap-events", &script.show_mmap_events,
3322                     "Show the mmap events"),
3323         OPT_BOOLEAN('\0', "show-switch-events", &script.show_switch_events,
3324                     "Show context switch events (if recorded)"),
3325         OPT_BOOLEAN('\0', "show-namespace-events", &script.show_namespace_events,
3326                     "Show namespace events (if recorded)"),
3327         OPT_BOOLEAN('\0', "show-lost-events", &script.show_lost_events,
3328                     "Show lost events (if recorded)"),
3329         OPT_BOOLEAN('\0', "show-round-events", &script.show_round_events,
3330                     "Show round events (if recorded)"),
3331         OPT_BOOLEAN('\0', "per-event-dump", &script.per_event_dump,
3332                     "Dump trace output to files named by the monitored events"),
3333         OPT_BOOLEAN('f', "force", &symbol_conf.force, "don't complain, do it"),
3334         OPT_INTEGER(0, "max-blocks", &max_blocks,
3335                     "Maximum number of code blocks to dump with brstackinsn"),
3336         OPT_BOOLEAN(0, "ns", &nanosecs,
3337                     "Use 9 decimal places when displaying time"),
3338         OPT_CALLBACK_OPTARG(0, "itrace", &itrace_synth_opts, NULL, "opts",
3339                             "Instruction Tracing options\n" ITRACE_HELP,
3340                             itrace_parse_synth_opts),
3341         OPT_BOOLEAN(0, "full-source-path", &srcline_full_filename,
3342                         "Show full source file name path for source lines"),
3343         OPT_BOOLEAN(0, "demangle", &symbol_conf.demangle,
3344                         "Enable symbol demangling"),
3345         OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
3346                         "Enable kernel symbol demangling"),
3347         OPT_STRING(0, "time", &script.time_str, "str",
3348                    "Time span of interest (start,stop)"),
3349         OPT_BOOLEAN(0, "inline", &symbol_conf.inline_name,
3350                     "Show inline function"),
3351         OPT_END()
3352         };
3353         const char * const script_subcommands[] = { "record", "report", NULL };
3354         const char *script_usage[] = {
3355                 "perf script [<options>]",
3356                 "perf script [<options>] record <script> [<record-options>] <command>",
3357                 "perf script [<options>] report <script> [script-args]",
3358                 "perf script [<options>] <script> [<record-options>] <command>",
3359                 "perf script [<options>] <top-script> [script-args]",
3360                 NULL
3361         };
3362
3363         perf_set_singlethreaded();
3364
3365         setup_scripting();
3366
3367         argc = parse_options_subcommand(argc, argv, options, script_subcommands, script_usage,
3368                              PARSE_OPT_STOP_AT_NON_OPTION);
3369
3370         data.file.path = input_name;
3371         data.force     = symbol_conf.force;
3372
3373         if (argc > 1 && !strncmp(argv[0], "rec", strlen("rec"))) {
3374                 rec_script_path = get_script_path(argv[1], RECORD_SUFFIX);
3375                 if (!rec_script_path)
3376                         return cmd_record(argc, argv);
3377         }
3378
3379         if (argc > 1 && !strncmp(argv[0], "rep", strlen("rep"))) {
3380                 rep_script_path = get_script_path(argv[1], REPORT_SUFFIX);
3381                 if (!rep_script_path) {
3382                         fprintf(stderr,
3383                                 "Please specify a valid report script"
3384                                 "(see 'perf script -l' for listing)\n");
3385                         return -1;
3386                 }
3387         }
3388
3389         if (itrace_synth_opts.callchain &&
3390             itrace_synth_opts.callchain_sz > scripting_max_stack)
3391                 scripting_max_stack = itrace_synth_opts.callchain_sz;
3392
3393         /* make sure PERF_EXEC_PATH is set for scripts */
3394         set_argv_exec_path(get_argv_exec_path());
3395
3396         if (argc && !script_name && !rec_script_path && !rep_script_path) {
3397                 int live_pipe[2];
3398                 int rep_args;
3399                 pid_t pid;
3400
3401                 rec_script_path = get_script_path(argv[0], RECORD_SUFFIX);
3402                 rep_script_path = get_script_path(argv[0], REPORT_SUFFIX);
3403
3404                 if (!rec_script_path && !rep_script_path) {
3405                         usage_with_options_msg(script_usage, options,
3406                                 "Couldn't find script `%s'\n\n See perf"
3407                                 " script -l for available scripts.\n", argv[0]);
3408                 }
3409
3410                 if (is_top_script(argv[0])) {
3411                         rep_args = argc - 1;
3412                 } else {
3413                         int rec_args;
3414
3415                         rep_args = has_required_arg(rep_script_path);
3416                         rec_args = (argc - 1) - rep_args;
3417                         if (rec_args < 0) {
3418                                 usage_with_options_msg(script_usage, options,
3419                                         "`%s' script requires options."
3420                                         "\n\n See perf script -l for available "
3421                                         "scripts and options.\n", argv[0]);
3422                         }
3423                 }
3424
3425                 if (pipe(live_pipe) < 0) {
3426                         perror("failed to create pipe");
3427                         return -1;
3428                 }
3429
3430                 pid = fork();
3431                 if (pid < 0) {
3432                         perror("failed to fork");
3433                         return -1;
3434                 }
3435
3436                 if (!pid) {
3437                         j = 0;
3438
3439                         dup2(live_pipe[1], 1);
3440                         close(live_pipe[0]);
3441
3442                         if (is_top_script(argv[0])) {
3443                                 system_wide = true;
3444                         } else if (!system_wide) {
3445                                 if (have_cmd(argc - rep_args, &argv[rep_args]) != 0) {
3446                                         err = -1;
3447                                         goto out;
3448                                 }
3449                         }
3450
3451                         __argv = malloc((argc + 6) * sizeof(const char *));
3452                         if (!__argv) {
3453                                 pr_err("malloc failed\n");
3454                                 err = -ENOMEM;
3455                                 goto out;
3456                         }
3457
3458                         __argv[j++] = "/bin/sh";
3459                         __argv[j++] = rec_script_path;
3460                         if (system_wide)
3461                                 __argv[j++] = "-a";
3462                         __argv[j++] = "-q";
3463                         __argv[j++] = "-o";
3464                         __argv[j++] = "-";
3465                         for (i = rep_args + 1; i < argc; i++)
3466                                 __argv[j++] = argv[i];
3467                         __argv[j++] = NULL;
3468
3469                         execvp("/bin/sh", (char **)__argv);
3470                         free(__argv);
3471                         exit(-1);
3472                 }
3473
3474                 dup2(live_pipe[0], 0);
3475                 close(live_pipe[1]);
3476
3477                 __argv = malloc((argc + 4) * sizeof(const char *));
3478                 if (!__argv) {
3479                         pr_err("malloc failed\n");
3480                         err = -ENOMEM;
3481                         goto out;
3482                 }
3483
3484                 j = 0;
3485                 __argv[j++] = "/bin/sh";
3486                 __argv[j++] = rep_script_path;
3487                 for (i = 1; i < rep_args + 1; i++)
3488                         __argv[j++] = argv[i];
3489                 __argv[j++] = "-i";
3490                 __argv[j++] = "-";
3491                 __argv[j++] = NULL;
3492
3493                 execvp("/bin/sh", (char **)__argv);
3494                 free(__argv);
3495                 exit(-1);
3496         }
3497
3498         if (rec_script_path)
3499                 script_path = rec_script_path;
3500         if (rep_script_path)
3501                 script_path = rep_script_path;
3502
3503         if (script_path) {
3504                 j = 0;
3505
3506                 if (!rec_script_path)
3507                         system_wide = false;
3508                 else if (!system_wide) {
3509                         if (have_cmd(argc - 1, &argv[1]) != 0) {
3510                                 err = -1;
3511                                 goto out;
3512                         }
3513                 }
3514
3515                 __argv = malloc((argc + 2) * sizeof(const char *));
3516                 if (!__argv) {
3517                         pr_err("malloc failed\n");
3518                         err = -ENOMEM;
3519                         goto out;
3520                 }
3521
3522                 __argv[j++] = "/bin/sh";
3523                 __argv[j++] = script_path;
3524                 if (system_wide)
3525                         __argv[j++] = "-a";
3526                 for (i = 2; i < argc; i++)
3527                         __argv[j++] = argv[i];
3528                 __argv[j++] = NULL;
3529
3530                 execvp("/bin/sh", (char **)__argv);
3531                 free(__argv);
3532                 exit(-1);
3533         }
3534
3535         if (!script_name) {
3536                 setup_pager();
3537                 use_browser = 0;
3538         }
3539
3540         session = perf_session__new(&data, false, &script.tool);
3541         if (session == NULL)
3542                 return -1;
3543
3544         if (header || header_only) {
3545                 script.tool.show_feat_hdr = SHOW_FEAT_HEADER;
3546                 perf_session__fprintf_info(session, stdout, show_full_info);
3547                 if (header_only)
3548                         goto out_delete;
3549         }
3550         if (show_full_info)
3551                 script.tool.show_feat_hdr = SHOW_FEAT_HEADER_FULL_INFO;
3552
3553         if (symbol__init(&session->header.env) < 0)
3554                 goto out_delete;
3555
3556         script.session = session;
3557         script__setup_sample_type(&script);
3558
3559         if ((output[PERF_TYPE_HARDWARE].fields & PERF_OUTPUT_CALLINDENT) ||
3560             symbol_conf.graph_function)
3561                 itrace_synth_opts.thread_stack = true;
3562
3563         session->itrace_synth_opts = &itrace_synth_opts;
3564
3565         if (cpu_list) {
3566                 err = perf_session__cpu_bitmap(session, cpu_list, cpu_bitmap);
3567                 if (err < 0)
3568                         goto out_delete;
3569                 itrace_synth_opts.cpu_bitmap = cpu_bitmap;
3570         }
3571
3572         if (!no_callchain)
3573                 symbol_conf.use_callchain = true;
3574         else
3575                 symbol_conf.use_callchain = false;
3576
3577         if (session->tevent.pevent &&
3578             tep_set_function_resolver(session->tevent.pevent,
3579                                       machine__resolve_kernel_addr,
3580                                       &session->machines.host) < 0) {
3581                 pr_err("%s: failed to set libtraceevent function resolver\n", __func__);
3582                 err = -1;
3583                 goto out_delete;
3584         }
3585
3586         if (generate_script_lang) {
3587                 struct stat perf_stat;
3588                 int input;
3589
3590                 if (output_set_by_user()) {
3591                         fprintf(stderr,
3592                                 "custom fields not supported for generated scripts");
3593                         err = -EINVAL;
3594                         goto out_delete;
3595                 }
3596
3597                 input = open(data.file.path, O_RDONLY); /* input_name */
3598                 if (input < 0) {
3599                         err = -errno;
3600                         perror("failed to open file");
3601                         goto out_delete;
3602                 }
3603
3604                 err = fstat(input, &perf_stat);
3605                 if (err < 0) {
3606                         perror("failed to stat file");
3607                         goto out_delete;
3608                 }
3609
3610                 if (!perf_stat.st_size) {
3611                         fprintf(stderr, "zero-sized file, nothing to do!\n");
3612                         goto out_delete;
3613                 }
3614
3615                 scripting_ops = script_spec__lookup(generate_script_lang);
3616                 if (!scripting_ops) {
3617                         fprintf(stderr, "invalid language specifier");
3618                         err = -ENOENT;
3619                         goto out_delete;
3620                 }
3621
3622                 err = scripting_ops->generate_script(session->tevent.pevent,
3623                                                      "perf-script");
3624                 goto out_delete;
3625         }
3626
3627         if (script_name) {
3628                 err = scripting_ops->start_script(script_name, argc, argv);
3629                 if (err)
3630                         goto out_delete;
3631                 pr_debug("perf script started with script %s\n\n", script_name);
3632                 script_started = true;
3633         }
3634
3635
3636         err = perf_session__check_output_opt(session);
3637         if (err < 0)
3638                 goto out_delete;
3639
3640         script.ptime_range = perf_time__range_alloc(script.time_str,
3641                                                     &script.range_size);
3642         if (!script.ptime_range) {
3643                 err = -ENOMEM;
3644                 goto out_delete;
3645         }
3646
3647         /* needs to be parsed after looking up reference time */
3648         if (perf_time__parse_str(script.ptime_range, script.time_str) != 0) {
3649                 if (session->evlist->first_sample_time == 0 &&
3650                     session->evlist->last_sample_time == 0) {
3651                         pr_err("HINT: no first/last sample time found in perf data.\n"
3652                                "Please use latest perf binary to execute 'perf record'\n"
3653                                "(if '--buildid-all' is enabled, please set '--timestamp-boundary').\n");
3654                         err = -EINVAL;
3655                         goto out_delete;
3656                 }
3657
3658                 script.range_num = perf_time__percent_parse_str(
3659                                         script.ptime_range, script.range_size,
3660                                         script.time_str,
3661                                         session->evlist->first_sample_time,
3662                                         session->evlist->last_sample_time);
3663
3664                 if (script.range_num < 0) {
3665                         pr_err("Invalid time string\n");
3666                         err = -EINVAL;
3667                         goto out_delete;
3668                 }
3669         } else {
3670                 script.range_num = 1;
3671         }
3672
3673         err = __cmd_script(&script);
3674
3675         flush_scripting();
3676
3677 out_delete:
3678         zfree(&script.ptime_range);
3679
3680         perf_evlist__free_stats(session->evlist);
3681         perf_session__delete(session);
3682
3683         if (script_started)
3684                 cleanup_scripting();
3685 out:
3686         return err;
3687 }