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