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