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