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