cachepc-linux

Fork of AMDESE/linux with modifications for CachePC side-channel attack
git clone https://git.sinitax.com/sinitax/cachepc-linux
Log | Files | Refs | README | LICENSE | sfeed.txt

builtin-script.c (115198B)


      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__do_check_stype(evsel, PERF_SAMPLE_DATA_SRC, "DATA_SRC", PERF_OUTPUT_DATA_SRC, allow_user_set))
    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, &ltime) == NULL) {
    708		scnprintf(buf, buflen, "failed");
    709	} else {
    710		strftime(date, sizeof(date), DEFAULT_TOD_FMT, &ltime);
    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
   1745/* If a value contains only printable ASCII characters padded with NULLs */
   1746static bool ptw_is_prt(u64 val)
   1747{
   1748	char c;
   1749	u32 i;
   1750
   1751	for (i = 0; i < sizeof(val); i++) {
   1752		c = ((char *)&val)[i];
   1753		if (!c)
   1754			break;
   1755		if (!isprint(c) || !isascii(c))
   1756			return false;
   1757	}
   1758	for (; i < sizeof(val); i++) {
   1759		c = ((char *)&val)[i];
   1760		if (c)
   1761			return false;
   1762	}
   1763	return true;
   1764}
   1765
   1766static int perf_sample__fprintf_synth_ptwrite(struct perf_sample *sample, FILE *fp)
   1767{
   1768	struct perf_synth_intel_ptwrite *data = perf_sample__synth_ptr(sample);
   1769	char str[sizeof(u64) + 1] = "";
   1770	int len;
   1771	u64 val;
   1772
   1773	if (perf_sample__bad_synth_size(sample, *data))
   1774		return 0;
   1775
   1776	val = le64_to_cpu(data->payload);
   1777	if (ptw_is_prt(val)) {
   1778		memcpy(str, &val, sizeof(val));
   1779		str[sizeof(val)] = 0;
   1780	}
   1781	len = fprintf(fp, " IP: %u payload: %#" PRIx64 " %s ",
   1782		      data->ip, val, str);
   1783	return len + perf_sample__fprintf_pt_spacing(len, fp);
   1784}
   1785
   1786static int perf_sample__fprintf_synth_mwait(struct perf_sample *sample, FILE *fp)
   1787{
   1788	struct perf_synth_intel_mwait *data = perf_sample__synth_ptr(sample);
   1789	int len;
   1790
   1791	if (perf_sample__bad_synth_size(sample, *data))
   1792		return 0;
   1793
   1794	len = fprintf(fp, " hints: %#x extensions: %#x ",
   1795		      data->hints, data->extensions);
   1796	return len + perf_sample__fprintf_pt_spacing(len, fp);
   1797}
   1798
   1799static int perf_sample__fprintf_synth_pwre(struct perf_sample *sample, FILE *fp)
   1800{
   1801	struct perf_synth_intel_pwre *data = perf_sample__synth_ptr(sample);
   1802	int len;
   1803
   1804	if (perf_sample__bad_synth_size(sample, *data))
   1805		return 0;
   1806
   1807	len = fprintf(fp, " hw: %u cstate: %u sub-cstate: %u ",
   1808		      data->hw, data->cstate, data->subcstate);
   1809	return len + perf_sample__fprintf_pt_spacing(len, fp);
   1810}
   1811
   1812static int perf_sample__fprintf_synth_exstop(struct perf_sample *sample, FILE *fp)
   1813{
   1814	struct perf_synth_intel_exstop *data = perf_sample__synth_ptr(sample);
   1815	int len;
   1816
   1817	if (perf_sample__bad_synth_size(sample, *data))
   1818		return 0;
   1819
   1820	len = fprintf(fp, " IP: %u ", data->ip);
   1821	return len + perf_sample__fprintf_pt_spacing(len, fp);
   1822}
   1823
   1824static int perf_sample__fprintf_synth_pwrx(struct perf_sample *sample, FILE *fp)
   1825{
   1826	struct perf_synth_intel_pwrx *data = perf_sample__synth_ptr(sample);
   1827	int len;
   1828
   1829	if (perf_sample__bad_synth_size(sample, *data))
   1830		return 0;
   1831
   1832	len = fprintf(fp, " deepest cstate: %u last cstate: %u wake reason: %#x ",
   1833		     data->deepest_cstate, data->last_cstate,
   1834		     data->wake_reason);
   1835	return len + perf_sample__fprintf_pt_spacing(len, fp);
   1836}
   1837
   1838static int perf_sample__fprintf_synth_cbr(struct perf_sample *sample, FILE *fp)
   1839{
   1840	struct perf_synth_intel_cbr *data = perf_sample__synth_ptr(sample);
   1841	unsigned int percent, freq;
   1842	int len;
   1843
   1844	if (perf_sample__bad_synth_size(sample, *data))
   1845		return 0;
   1846
   1847	freq = (le32_to_cpu(data->freq) + 500) / 1000;
   1848	len = fprintf(fp, " cbr: %2u freq: %4u MHz ", data->cbr, freq);
   1849	if (data->max_nonturbo) {
   1850		percent = (5 + (1000 * data->cbr) / data->max_nonturbo) / 10;
   1851		len += fprintf(fp, "(%3u%%) ", percent);
   1852	}
   1853	return len + perf_sample__fprintf_pt_spacing(len, fp);
   1854}
   1855
   1856static int perf_sample__fprintf_synth_psb(struct perf_sample *sample, FILE *fp)
   1857{
   1858	struct perf_synth_intel_psb *data = perf_sample__synth_ptr(sample);
   1859	int len;
   1860
   1861	if (perf_sample__bad_synth_size(sample, *data))
   1862		return 0;
   1863
   1864	len = fprintf(fp, " psb offs: %#" PRIx64, data->offset);
   1865	return len + perf_sample__fprintf_pt_spacing(len, fp);
   1866}
   1867
   1868/* Intel PT Event Trace */
   1869static int perf_sample__fprintf_synth_evt(struct perf_sample *sample, FILE *fp)
   1870{
   1871	struct perf_synth_intel_evt *data = perf_sample__synth_ptr(sample);
   1872	const char *cfe[32] = {NULL, "INTR", "IRET", "SMI", "RSM", "SIPI",
   1873			       "INIT", "VMENTRY", "VMEXIT", "VMEXIT_INTR",
   1874			       "SHUTDOWN"};
   1875	const char *evd[64] = {"PFA", "VMXQ", "VMXR"};
   1876	const char *s;
   1877	int len, i;
   1878
   1879	if (perf_sample__bad_synth_size(sample, *data))
   1880		return 0;
   1881
   1882	s = cfe[data->type];
   1883	if (s) {
   1884		len = fprintf(fp, " cfe: %s IP: %d vector: %u",
   1885			      s, data->ip, data->vector);
   1886	} else {
   1887		len = fprintf(fp, " cfe: %u IP: %d vector: %u",
   1888			      data->type, data->ip, data->vector);
   1889	}
   1890	for (i = 0; i < data->evd_cnt; i++) {
   1891		unsigned int et = data->evd[i].evd_type & 0x3f;
   1892
   1893		s = evd[et];
   1894		if (s) {
   1895			len += fprintf(fp, " %s: %#" PRIx64,
   1896				       s, data->evd[i].payload);
   1897		} else {
   1898			len += fprintf(fp, " EVD_%u: %#" PRIx64,
   1899				       et, data->evd[i].payload);
   1900		}
   1901	}
   1902	return len + perf_sample__fprintf_pt_spacing(len, fp);
   1903}
   1904
   1905static int perf_sample__fprintf_synth_iflag_chg(struct perf_sample *sample, FILE *fp)
   1906{
   1907	struct perf_synth_intel_iflag_chg *data = perf_sample__synth_ptr(sample);
   1908	int len;
   1909
   1910	if (perf_sample__bad_synth_size(sample, *data))
   1911		return 0;
   1912
   1913	len = fprintf(fp, " IFLAG: %d->%d %s branch", !data->iflag, data->iflag,
   1914		      data->via_branch ? "via" : "non");
   1915	return len + perf_sample__fprintf_pt_spacing(len, fp);
   1916}
   1917
   1918static int perf_sample__fprintf_synth(struct perf_sample *sample,
   1919				      struct evsel *evsel, FILE *fp)
   1920{
   1921	switch (evsel->core.attr.config) {
   1922	case PERF_SYNTH_INTEL_PTWRITE:
   1923		return perf_sample__fprintf_synth_ptwrite(sample, fp);
   1924	case PERF_SYNTH_INTEL_MWAIT:
   1925		return perf_sample__fprintf_synth_mwait(sample, fp);
   1926	case PERF_SYNTH_INTEL_PWRE:
   1927		return perf_sample__fprintf_synth_pwre(sample, fp);
   1928	case PERF_SYNTH_INTEL_EXSTOP:
   1929		return perf_sample__fprintf_synth_exstop(sample, fp);
   1930	case PERF_SYNTH_INTEL_PWRX:
   1931		return perf_sample__fprintf_synth_pwrx(sample, fp);
   1932	case PERF_SYNTH_INTEL_CBR:
   1933		return perf_sample__fprintf_synth_cbr(sample, fp);
   1934	case PERF_SYNTH_INTEL_PSB:
   1935		return perf_sample__fprintf_synth_psb(sample, fp);
   1936	case PERF_SYNTH_INTEL_EVT:
   1937		return perf_sample__fprintf_synth_evt(sample, fp);
   1938	case PERF_SYNTH_INTEL_IFLAG_CHG:
   1939		return perf_sample__fprintf_synth_iflag_chg(sample, fp);
   1940	default:
   1941		break;
   1942	}
   1943
   1944	return 0;
   1945}
   1946
   1947static int evlist__max_name_len(struct evlist *evlist)
   1948{
   1949	struct evsel *evsel;
   1950	int max = 0;
   1951
   1952	evlist__for_each_entry(evlist, evsel) {
   1953		int len = strlen(evsel__name(evsel));
   1954
   1955		max = MAX(len, max);
   1956	}
   1957
   1958	return max;
   1959}
   1960
   1961static int data_src__fprintf(u64 data_src, FILE *fp)
   1962{
   1963	struct mem_info mi = { .data_src.val = data_src };
   1964	char decode[100];
   1965	char out[100];
   1966	static int maxlen;
   1967	int len;
   1968
   1969	perf_script__meminfo_scnprintf(decode, 100, &mi);
   1970
   1971	len = scnprintf(out, 100, "%16" PRIx64 " %s", data_src, decode);
   1972	if (maxlen < len)
   1973		maxlen = len;
   1974
   1975	return fprintf(fp, "%-*s", maxlen, out);
   1976}
   1977
   1978struct metric_ctx {
   1979	struct perf_sample	*sample;
   1980	struct thread		*thread;
   1981	struct evsel	*evsel;
   1982	FILE 			*fp;
   1983};
   1984
   1985static void script_print_metric(struct perf_stat_config *config __maybe_unused,
   1986				void *ctx, const char *color,
   1987			        const char *fmt,
   1988			        const char *unit, double val)
   1989{
   1990	struct metric_ctx *mctx = ctx;
   1991
   1992	if (!fmt)
   1993		return;
   1994	perf_sample__fprintf_start(NULL, mctx->sample, mctx->thread, mctx->evsel,
   1995				   PERF_RECORD_SAMPLE, mctx->fp);
   1996	fputs("\tmetric: ", mctx->fp);
   1997	if (color)
   1998		color_fprintf(mctx->fp, color, fmt, val);
   1999	else
   2000		printf(fmt, val);
   2001	fprintf(mctx->fp, " %s\n", unit);
   2002}
   2003
   2004static void script_new_line(struct perf_stat_config *config __maybe_unused,
   2005			    void *ctx)
   2006{
   2007	struct metric_ctx *mctx = ctx;
   2008
   2009	perf_sample__fprintf_start(NULL, mctx->sample, mctx->thread, mctx->evsel,
   2010				   PERF_RECORD_SAMPLE, mctx->fp);
   2011	fputs("\tmetric: ", mctx->fp);
   2012}
   2013
   2014static void perf_sample__fprint_metric(struct perf_script *script,
   2015				       struct thread *thread,
   2016				       struct evsel *evsel,
   2017				       struct perf_sample *sample,
   2018				       FILE *fp)
   2019{
   2020	struct evsel *leader = evsel__leader(evsel);
   2021	struct perf_stat_output_ctx ctx = {
   2022		.print_metric = script_print_metric,
   2023		.new_line = script_new_line,
   2024		.ctx = &(struct metric_ctx) {
   2025				.sample = sample,
   2026				.thread = thread,
   2027				.evsel  = evsel,
   2028				.fp     = fp,
   2029			 },
   2030		.force_header = false,
   2031	};
   2032	struct evsel *ev2;
   2033	u64 val;
   2034
   2035	if (!evsel->stats)
   2036		evlist__alloc_stats(script->session->evlist, false);
   2037	if (evsel_script(leader)->gnum++ == 0)
   2038		perf_stat__reset_shadow_stats();
   2039	val = sample->period * evsel->scale;
   2040	perf_stat__update_shadow_stats(evsel,
   2041				       val,
   2042				       sample->cpu,
   2043				       &rt_stat);
   2044	evsel_script(evsel)->val = val;
   2045	if (evsel_script(leader)->gnum == leader->core.nr_members) {
   2046		for_each_group_member (ev2, leader) {
   2047			perf_stat__print_shadow_stats(&stat_config, ev2,
   2048						      evsel_script(ev2)->val,
   2049						      sample->cpu,
   2050						      &ctx,
   2051						      NULL,
   2052						      &rt_stat);
   2053		}
   2054		evsel_script(leader)->gnum = 0;
   2055	}
   2056}
   2057
   2058static bool show_event(struct perf_sample *sample,
   2059		       struct evsel *evsel,
   2060		       struct thread *thread,
   2061		       struct addr_location *al,
   2062		       struct addr_location *addr_al)
   2063{
   2064	int depth = thread_stack__depth(thread, sample->cpu);
   2065
   2066	if (!symbol_conf.graph_function)
   2067		return true;
   2068
   2069	if (thread->filter) {
   2070		if (depth <= thread->filter_entry_depth) {
   2071			thread->filter = false;
   2072			return false;
   2073		}
   2074		return true;
   2075	} else {
   2076		const char *s = symbol_conf.graph_function;
   2077		u64 ip;
   2078		const char *name = resolve_branch_sym(sample, evsel, thread, al, addr_al,
   2079				&ip);
   2080		unsigned nlen;
   2081
   2082		if (!name)
   2083			return false;
   2084		nlen = strlen(name);
   2085		while (*s) {
   2086			unsigned len = strcspn(s, ",");
   2087			if (nlen == len && !strncmp(name, s, len)) {
   2088				thread->filter = true;
   2089				thread->filter_entry_depth = depth;
   2090				return true;
   2091			}
   2092			s += len;
   2093			if (*s == ',')
   2094				s++;
   2095		}
   2096		return false;
   2097	}
   2098}
   2099
   2100static void process_event(struct perf_script *script,
   2101			  struct perf_sample *sample, struct evsel *evsel,
   2102			  struct addr_location *al,
   2103			  struct addr_location *addr_al,
   2104			  struct machine *machine)
   2105{
   2106	struct thread *thread = al->thread;
   2107	struct perf_event_attr *attr = &evsel->core.attr;
   2108	unsigned int type = output_type(attr->type);
   2109	struct evsel_script *es = evsel->priv;
   2110	FILE *fp = es->fp;
   2111	char str[PAGE_SIZE_NAME_LEN];
   2112	const char *arch = perf_env__arch(machine->env);
   2113
   2114	if (output[type].fields == 0)
   2115		return;
   2116
   2117	++es->samples;
   2118
   2119	perf_sample__fprintf_start(script, sample, thread, evsel,
   2120				   PERF_RECORD_SAMPLE, fp);
   2121
   2122	if (PRINT_FIELD(PERIOD))
   2123		fprintf(fp, "%10" PRIu64 " ", sample->period);
   2124
   2125	if (PRINT_FIELD(EVNAME)) {
   2126		const char *evname = evsel__name(evsel);
   2127
   2128		if (!script->name_width)
   2129			script->name_width = evlist__max_name_len(script->session->evlist);
   2130
   2131		fprintf(fp, "%*s: ", script->name_width, evname ?: "[unknown]");
   2132	}
   2133
   2134	if (print_flags)
   2135		perf_sample__fprintf_flags(sample->flags, fp);
   2136
   2137	if (is_bts_event(attr)) {
   2138		perf_sample__fprintf_bts(sample, evsel, thread, al, addr_al, machine, fp);
   2139		return;
   2140	}
   2141
   2142	if (PRINT_FIELD(TRACE) && sample->raw_data) {
   2143		event_format__fprintf(evsel->tp_format, sample->cpu,
   2144				      sample->raw_data, sample->raw_size, fp);
   2145	}
   2146
   2147	if (attr->type == PERF_TYPE_SYNTH && PRINT_FIELD(SYNTH))
   2148		perf_sample__fprintf_synth(sample, evsel, fp);
   2149
   2150	if (PRINT_FIELD(ADDR))
   2151		perf_sample__fprintf_addr(sample, thread, attr, fp);
   2152
   2153	if (PRINT_FIELD(DATA_SRC))
   2154		data_src__fprintf(sample->data_src, fp);
   2155
   2156	if (PRINT_FIELD(WEIGHT))
   2157		fprintf(fp, "%16" PRIu64, sample->weight);
   2158
   2159	if (PRINT_FIELD(INS_LAT))
   2160		fprintf(fp, "%16" PRIu16, sample->ins_lat);
   2161
   2162	if (PRINT_FIELD(IP)) {
   2163		struct callchain_cursor *cursor = NULL;
   2164
   2165		if (script->stitch_lbr)
   2166			al->thread->lbr_stitch_enable = true;
   2167
   2168		if (symbol_conf.use_callchain && sample->callchain &&
   2169		    thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
   2170					      sample, NULL, NULL, scripting_max_stack) == 0)
   2171			cursor = &callchain_cursor;
   2172
   2173		fputc(cursor ? '\n' : ' ', fp);
   2174		sample__fprintf_sym(sample, al, 0, output[type].print_ip_opts, cursor,
   2175				    symbol_conf.bt_stop_list, fp);
   2176	}
   2177
   2178	if (PRINT_FIELD(IREGS))
   2179		perf_sample__fprintf_iregs(sample, attr, arch, fp);
   2180
   2181	if (PRINT_FIELD(UREGS))
   2182		perf_sample__fprintf_uregs(sample, attr, arch, fp);
   2183
   2184	if (PRINT_FIELD(BRSTACK))
   2185		perf_sample__fprintf_brstack(sample, thread, attr, fp);
   2186	else if (PRINT_FIELD(BRSTACKSYM))
   2187		perf_sample__fprintf_brstacksym(sample, thread, attr, fp);
   2188	else if (PRINT_FIELD(BRSTACKOFF))
   2189		perf_sample__fprintf_brstackoff(sample, thread, attr, fp);
   2190
   2191	if (evsel__is_bpf_output(evsel) && PRINT_FIELD(BPF_OUTPUT))
   2192		perf_sample__fprintf_bpf_output(sample, fp);
   2193	perf_sample__fprintf_insn(sample, attr, thread, machine, fp);
   2194
   2195	if (PRINT_FIELD(PHYS_ADDR))
   2196		fprintf(fp, "%16" PRIx64, sample->phys_addr);
   2197
   2198	if (PRINT_FIELD(DATA_PAGE_SIZE))
   2199		fprintf(fp, " %s", get_page_size_name(sample->data_page_size, str));
   2200
   2201	if (PRINT_FIELD(CODE_PAGE_SIZE))
   2202		fprintf(fp, " %s", get_page_size_name(sample->code_page_size, str));
   2203
   2204	perf_sample__fprintf_ipc(sample, attr, fp);
   2205
   2206	fprintf(fp, "\n");
   2207
   2208	if (PRINT_FIELD(SRCCODE)) {
   2209		if (map__fprintf_srccode(al->map, al->addr, stdout,
   2210					 &thread->srccode_state))
   2211			printf("\n");
   2212	}
   2213
   2214	if (PRINT_FIELD(METRIC))
   2215		perf_sample__fprint_metric(script, thread, evsel, sample, fp);
   2216
   2217	if (verbose)
   2218		fflush(fp);
   2219}
   2220
   2221static struct scripting_ops	*scripting_ops;
   2222
   2223static void __process_stat(struct evsel *counter, u64 tstamp)
   2224{
   2225	int nthreads = perf_thread_map__nr(counter->core.threads);
   2226	int idx, thread;
   2227	struct perf_cpu cpu;
   2228	static int header_printed;
   2229
   2230	if (counter->core.system_wide)
   2231		nthreads = 1;
   2232
   2233	if (!header_printed) {
   2234		printf("%3s %8s %15s %15s %15s %15s %s\n",
   2235		       "CPU", "THREAD", "VAL", "ENA", "RUN", "TIME", "EVENT");
   2236		header_printed = 1;
   2237	}
   2238
   2239	for (thread = 0; thread < nthreads; thread++) {
   2240		perf_cpu_map__for_each_cpu(cpu, idx, evsel__cpus(counter)) {
   2241			struct perf_counts_values *counts;
   2242
   2243			counts = perf_counts(counter->counts, idx, thread);
   2244
   2245			printf("%3d %8d %15" PRIu64 " %15" PRIu64 " %15" PRIu64 " %15" PRIu64 " %s\n",
   2246				cpu.cpu,
   2247				perf_thread_map__pid(counter->core.threads, thread),
   2248				counts->val,
   2249				counts->ena,
   2250				counts->run,
   2251				tstamp,
   2252				evsel__name(counter));
   2253		}
   2254	}
   2255}
   2256
   2257static void process_stat(struct evsel *counter, u64 tstamp)
   2258{
   2259	if (scripting_ops && scripting_ops->process_stat)
   2260		scripting_ops->process_stat(&stat_config, counter, tstamp);
   2261	else
   2262		__process_stat(counter, tstamp);
   2263}
   2264
   2265static void process_stat_interval(u64 tstamp)
   2266{
   2267	if (scripting_ops && scripting_ops->process_stat_interval)
   2268		scripting_ops->process_stat_interval(tstamp);
   2269}
   2270
   2271static void setup_scripting(void)
   2272{
   2273	setup_perl_scripting();
   2274	setup_python_scripting();
   2275}
   2276
   2277static int flush_scripting(void)
   2278{
   2279	return scripting_ops ? scripting_ops->flush_script() : 0;
   2280}
   2281
   2282static int cleanup_scripting(void)
   2283{
   2284	pr_debug("\nperf script stopped\n");
   2285
   2286	return scripting_ops ? scripting_ops->stop_script() : 0;
   2287}
   2288
   2289static bool filter_cpu(struct perf_sample *sample)
   2290{
   2291	if (cpu_list && sample->cpu != (u32)-1)
   2292		return !test_bit(sample->cpu, cpu_bitmap);
   2293	return false;
   2294}
   2295
   2296static int process_sample_event(struct perf_tool *tool,
   2297				union perf_event *event,
   2298				struct perf_sample *sample,
   2299				struct evsel *evsel,
   2300				struct machine *machine)
   2301{
   2302	struct perf_script *scr = container_of(tool, struct perf_script, tool);
   2303	struct addr_location al;
   2304	struct addr_location addr_al;
   2305	int ret = 0;
   2306
   2307	/* Set thread to NULL to indicate addr_al and al are not initialized */
   2308	addr_al.thread = NULL;
   2309	al.thread = NULL;
   2310
   2311	ret = dlfilter__filter_event_early(dlfilter, event, sample, evsel, machine, &al, &addr_al);
   2312	if (ret) {
   2313		if (ret > 0)
   2314			ret = 0;
   2315		goto out_put;
   2316	}
   2317
   2318	if (perf_time__ranges_skip_sample(scr->ptime_range, scr->range_num,
   2319					  sample->time)) {
   2320		goto out_put;
   2321	}
   2322
   2323	if (debug_mode) {
   2324		if (sample->time < last_timestamp) {
   2325			pr_err("Samples misordered, previous: %" PRIu64
   2326				" this: %" PRIu64 "\n", last_timestamp,
   2327				sample->time);
   2328			nr_unordered++;
   2329		}
   2330		last_timestamp = sample->time;
   2331		goto out_put;
   2332	}
   2333
   2334	if (filter_cpu(sample))
   2335		goto out_put;
   2336
   2337	if (!al.thread && machine__resolve(machine, &al, sample) < 0) {
   2338		pr_err("problem processing %d event, skipping it.\n",
   2339		       event->header.type);
   2340		ret = -1;
   2341		goto out_put;
   2342	}
   2343
   2344	if (al.filtered)
   2345		goto out_put;
   2346
   2347	if (!show_event(sample, evsel, al.thread, &al, &addr_al))
   2348		goto out_put;
   2349
   2350	if (evswitch__discard(&scr->evswitch, evsel))
   2351		goto out_put;
   2352
   2353	ret = dlfilter__filter_event(dlfilter, event, sample, evsel, machine, &al, &addr_al);
   2354	if (ret) {
   2355		if (ret > 0)
   2356			ret = 0;
   2357		goto out_put;
   2358	}
   2359
   2360	if (scripting_ops) {
   2361		struct addr_location *addr_al_ptr = NULL;
   2362
   2363		if ((evsel->core.attr.sample_type & PERF_SAMPLE_ADDR) &&
   2364		    sample_addr_correlates_sym(&evsel->core.attr)) {
   2365			if (!addr_al.thread)
   2366				thread__resolve(al.thread, &addr_al, sample);
   2367			addr_al_ptr = &addr_al;
   2368		}
   2369		scripting_ops->process_event(event, sample, evsel, &al, addr_al_ptr);
   2370	} else {
   2371		process_event(scr, sample, evsel, &al, &addr_al, machine);
   2372	}
   2373
   2374out_put:
   2375	if (al.thread)
   2376		addr_location__put(&al);
   2377	return ret;
   2378}
   2379
   2380static int process_attr(struct perf_tool *tool, union perf_event *event,
   2381			struct evlist **pevlist)
   2382{
   2383	struct perf_script *scr = container_of(tool, struct perf_script, tool);
   2384	struct evlist *evlist;
   2385	struct evsel *evsel, *pos;
   2386	u64 sample_type;
   2387	int err;
   2388	static struct evsel_script *es;
   2389
   2390	err = perf_event__process_attr(tool, event, pevlist);
   2391	if (err)
   2392		return err;
   2393
   2394	evlist = *pevlist;
   2395	evsel = evlist__last(*pevlist);
   2396
   2397	if (!evsel->priv) {
   2398		if (scr->per_event_dump) {
   2399			evsel->priv = evsel_script__new(evsel, scr->session->data);
   2400		} else {
   2401			es = zalloc(sizeof(*es));
   2402			if (!es)
   2403				return -ENOMEM;
   2404			es->fp = stdout;
   2405			evsel->priv = es;
   2406		}
   2407	}
   2408
   2409	if (evsel->core.attr.type >= PERF_TYPE_MAX &&
   2410	    evsel->core.attr.type != PERF_TYPE_SYNTH)
   2411		return 0;
   2412
   2413	evlist__for_each_entry(evlist, pos) {
   2414		if (pos->core.attr.type == evsel->core.attr.type && pos != evsel)
   2415			return 0;
   2416	}
   2417
   2418	if (evsel->core.attr.sample_type) {
   2419		err = evsel__check_attr(evsel, scr->session);
   2420		if (err)
   2421			return err;
   2422	}
   2423
   2424	/*
   2425	 * Check if we need to enable callchains based
   2426	 * on events sample_type.
   2427	 */
   2428	sample_type = evlist__combined_sample_type(evlist);
   2429	callchain_param_setup(sample_type, perf_env__arch((*pevlist)->env));
   2430
   2431	/* Enable fields for callchain entries */
   2432	if (symbol_conf.use_callchain &&
   2433	    (sample_type & PERF_SAMPLE_CALLCHAIN ||
   2434	     sample_type & PERF_SAMPLE_BRANCH_STACK ||
   2435	     (sample_type & PERF_SAMPLE_REGS_USER &&
   2436	      sample_type & PERF_SAMPLE_STACK_USER))) {
   2437		int type = output_type(evsel->core.attr.type);
   2438
   2439		if (!(output[type].user_unset_fields & PERF_OUTPUT_IP))
   2440			output[type].fields |= PERF_OUTPUT_IP;
   2441		if (!(output[type].user_unset_fields & PERF_OUTPUT_SYM))
   2442			output[type].fields |= PERF_OUTPUT_SYM;
   2443	}
   2444	set_print_ip_opts(&evsel->core.attr);
   2445	return 0;
   2446}
   2447
   2448static int print_event_with_time(struct perf_tool *tool,
   2449				 union perf_event *event,
   2450				 struct perf_sample *sample,
   2451				 struct machine *machine,
   2452				 pid_t pid, pid_t tid, u64 timestamp)
   2453{
   2454	struct perf_script *script = container_of(tool, struct perf_script, tool);
   2455	struct perf_session *session = script->session;
   2456	struct evsel *evsel = evlist__id2evsel(session->evlist, sample->id);
   2457	struct thread *thread = NULL;
   2458
   2459	if (evsel && !evsel->core.attr.sample_id_all) {
   2460		sample->cpu = 0;
   2461		sample->time = timestamp;
   2462		sample->pid = pid;
   2463		sample->tid = tid;
   2464	}
   2465
   2466	if (filter_cpu(sample))
   2467		return 0;
   2468
   2469	if (tid != -1)
   2470		thread = machine__findnew_thread(machine, pid, tid);
   2471
   2472	if (evsel) {
   2473		perf_sample__fprintf_start(script, sample, thread, evsel,
   2474					   event->header.type, stdout);
   2475	}
   2476
   2477	perf_event__fprintf(event, machine, stdout);
   2478
   2479	thread__put(thread);
   2480
   2481	return 0;
   2482}
   2483
   2484static int print_event(struct perf_tool *tool, union perf_event *event,
   2485		       struct perf_sample *sample, struct machine *machine,
   2486		       pid_t pid, pid_t tid)
   2487{
   2488	return print_event_with_time(tool, event, sample, machine, pid, tid, 0);
   2489}
   2490
   2491static int process_comm_event(struct perf_tool *tool,
   2492			      union perf_event *event,
   2493			      struct perf_sample *sample,
   2494			      struct machine *machine)
   2495{
   2496	if (perf_event__process_comm(tool, event, sample, machine) < 0)
   2497		return -1;
   2498
   2499	return print_event(tool, event, sample, machine, event->comm.pid,
   2500			   event->comm.tid);
   2501}
   2502
   2503static int process_namespaces_event(struct perf_tool *tool,
   2504				    union perf_event *event,
   2505				    struct perf_sample *sample,
   2506				    struct machine *machine)
   2507{
   2508	if (perf_event__process_namespaces(tool, event, sample, machine) < 0)
   2509		return -1;
   2510
   2511	return print_event(tool, event, sample, machine, event->namespaces.pid,
   2512			   event->namespaces.tid);
   2513}
   2514
   2515static int process_cgroup_event(struct perf_tool *tool,
   2516				union perf_event *event,
   2517				struct perf_sample *sample,
   2518				struct machine *machine)
   2519{
   2520	if (perf_event__process_cgroup(tool, event, sample, machine) < 0)
   2521		return -1;
   2522
   2523	return print_event(tool, event, sample, machine, sample->pid,
   2524			    sample->tid);
   2525}
   2526
   2527static int process_fork_event(struct perf_tool *tool,
   2528			      union perf_event *event,
   2529			      struct perf_sample *sample,
   2530			      struct machine *machine)
   2531{
   2532	if (perf_event__process_fork(tool, event, sample, machine) < 0)
   2533		return -1;
   2534
   2535	return print_event_with_time(tool, event, sample, machine,
   2536				     event->fork.pid, event->fork.tid,
   2537				     event->fork.time);
   2538}
   2539static int process_exit_event(struct perf_tool *tool,
   2540			      union perf_event *event,
   2541			      struct perf_sample *sample,
   2542			      struct machine *machine)
   2543{
   2544	/* Print before 'exit' deletes anything */
   2545	if (print_event_with_time(tool, event, sample, machine, event->fork.pid,
   2546				  event->fork.tid, event->fork.time))
   2547		return -1;
   2548
   2549	return perf_event__process_exit(tool, event, sample, machine);
   2550}
   2551
   2552static int process_mmap_event(struct perf_tool *tool,
   2553			      union perf_event *event,
   2554			      struct perf_sample *sample,
   2555			      struct machine *machine)
   2556{
   2557	if (perf_event__process_mmap(tool, event, sample, machine) < 0)
   2558		return -1;
   2559
   2560	return print_event(tool, event, sample, machine, event->mmap.pid,
   2561			   event->mmap.tid);
   2562}
   2563
   2564static int process_mmap2_event(struct perf_tool *tool,
   2565			      union perf_event *event,
   2566			      struct perf_sample *sample,
   2567			      struct machine *machine)
   2568{
   2569	if (perf_event__process_mmap2(tool, event, sample, machine) < 0)
   2570		return -1;
   2571
   2572	return print_event(tool, event, sample, machine, event->mmap2.pid,
   2573			   event->mmap2.tid);
   2574}
   2575
   2576static int process_switch_event(struct perf_tool *tool,
   2577				union perf_event *event,
   2578				struct perf_sample *sample,
   2579				struct machine *machine)
   2580{
   2581	struct perf_script *script = container_of(tool, struct perf_script, tool);
   2582
   2583	if (perf_event__process_switch(tool, event, sample, machine) < 0)
   2584		return -1;
   2585
   2586	if (scripting_ops && scripting_ops->process_switch && !filter_cpu(sample))
   2587		scripting_ops->process_switch(event, sample, machine);
   2588
   2589	if (!script->show_switch_events)
   2590		return 0;
   2591
   2592	return print_event(tool, event, sample, machine, sample->pid,
   2593			   sample->tid);
   2594}
   2595
   2596static int process_auxtrace_error(struct perf_session *session,
   2597				  union perf_event *event)
   2598{
   2599	if (scripting_ops && scripting_ops->process_auxtrace_error) {
   2600		scripting_ops->process_auxtrace_error(session, event);
   2601		return 0;
   2602	}
   2603
   2604	return perf_event__process_auxtrace_error(session, event);
   2605}
   2606
   2607static int
   2608process_lost_event(struct perf_tool *tool,
   2609		   union perf_event *event,
   2610		   struct perf_sample *sample,
   2611		   struct machine *machine)
   2612{
   2613	return print_event(tool, event, sample, machine, sample->pid,
   2614			   sample->tid);
   2615}
   2616
   2617static int
   2618process_throttle_event(struct perf_tool *tool __maybe_unused,
   2619		       union perf_event *event,
   2620		       struct perf_sample *sample,
   2621		       struct machine *machine)
   2622{
   2623	if (scripting_ops && scripting_ops->process_throttle)
   2624		scripting_ops->process_throttle(event, sample, machine);
   2625	return 0;
   2626}
   2627
   2628static int
   2629process_finished_round_event(struct perf_tool *tool __maybe_unused,
   2630			     union perf_event *event,
   2631			     struct ordered_events *oe __maybe_unused)
   2632
   2633{
   2634	perf_event__fprintf(event, NULL, stdout);
   2635	return 0;
   2636}
   2637
   2638static int
   2639process_bpf_events(struct perf_tool *tool __maybe_unused,
   2640		   union perf_event *event,
   2641		   struct perf_sample *sample,
   2642		   struct machine *machine)
   2643{
   2644	if (machine__process_ksymbol(machine, event, sample) < 0)
   2645		return -1;
   2646
   2647	return print_event(tool, event, sample, machine, sample->pid,
   2648			   sample->tid);
   2649}
   2650
   2651static int process_text_poke_events(struct perf_tool *tool,
   2652				    union perf_event *event,
   2653				    struct perf_sample *sample,
   2654				    struct machine *machine)
   2655{
   2656	if (perf_event__process_text_poke(tool, event, sample, machine) < 0)
   2657		return -1;
   2658
   2659	return print_event(tool, event, sample, machine, sample->pid,
   2660			   sample->tid);
   2661}
   2662
   2663static void sig_handler(int sig __maybe_unused)
   2664{
   2665	session_done = 1;
   2666}
   2667
   2668static void perf_script__fclose_per_event_dump(struct perf_script *script)
   2669{
   2670	struct evlist *evlist = script->session->evlist;
   2671	struct evsel *evsel;
   2672
   2673	evlist__for_each_entry(evlist, evsel) {
   2674		if (!evsel->priv)
   2675			break;
   2676		evsel_script__delete(evsel->priv);
   2677		evsel->priv = NULL;
   2678	}
   2679}
   2680
   2681static int perf_script__fopen_per_event_dump(struct perf_script *script)
   2682{
   2683	struct evsel *evsel;
   2684
   2685	evlist__for_each_entry(script->session->evlist, evsel) {
   2686		/*
   2687		 * Already setup? I.e. we may be called twice in cases like
   2688		 * Intel PT, one for the intel_pt// and dummy events, then
   2689		 * for the evsels synthesized from the auxtrace info.
   2690		 *
   2691		 * Ses perf_script__process_auxtrace_info.
   2692		 */
   2693		if (evsel->priv != NULL)
   2694			continue;
   2695
   2696		evsel->priv = evsel_script__new(evsel, script->session->data);
   2697		if (evsel->priv == NULL)
   2698			goto out_err_fclose;
   2699	}
   2700
   2701	return 0;
   2702
   2703out_err_fclose:
   2704	perf_script__fclose_per_event_dump(script);
   2705	return -1;
   2706}
   2707
   2708static int perf_script__setup_per_event_dump(struct perf_script *script)
   2709{
   2710	struct evsel *evsel;
   2711	static struct evsel_script es_stdout;
   2712
   2713	if (script->per_event_dump)
   2714		return perf_script__fopen_per_event_dump(script);
   2715
   2716	es_stdout.fp = stdout;
   2717
   2718	evlist__for_each_entry(script->session->evlist, evsel)
   2719		evsel->priv = &es_stdout;
   2720
   2721	return 0;
   2722}
   2723
   2724static void perf_script__exit_per_event_dump_stats(struct perf_script *script)
   2725{
   2726	struct evsel *evsel;
   2727
   2728	evlist__for_each_entry(script->session->evlist, evsel) {
   2729		struct evsel_script *es = evsel->priv;
   2730
   2731		evsel_script__fprintf(es, stdout);
   2732		evsel_script__delete(es);
   2733		evsel->priv = NULL;
   2734	}
   2735}
   2736
   2737static void perf_script__exit(struct perf_script *script)
   2738{
   2739	perf_thread_map__put(script->threads);
   2740	perf_cpu_map__put(script->cpus);
   2741}
   2742
   2743static int __cmd_script(struct perf_script *script)
   2744{
   2745	int ret;
   2746
   2747	signal(SIGINT, sig_handler);
   2748
   2749	perf_stat__init_shadow_stats();
   2750
   2751	/* override event processing functions */
   2752	if (script->show_task_events) {
   2753		script->tool.comm = process_comm_event;
   2754		script->tool.fork = process_fork_event;
   2755		script->tool.exit = process_exit_event;
   2756	}
   2757	if (script->show_mmap_events) {
   2758		script->tool.mmap = process_mmap_event;
   2759		script->tool.mmap2 = process_mmap2_event;
   2760	}
   2761	if (script->show_switch_events || (scripting_ops && scripting_ops->process_switch))
   2762		script->tool.context_switch = process_switch_event;
   2763	if (scripting_ops && scripting_ops->process_auxtrace_error)
   2764		script->tool.auxtrace_error = process_auxtrace_error;
   2765	if (script->show_namespace_events)
   2766		script->tool.namespaces = process_namespaces_event;
   2767	if (script->show_cgroup_events)
   2768		script->tool.cgroup = process_cgroup_event;
   2769	if (script->show_lost_events)
   2770		script->tool.lost = process_lost_event;
   2771	if (script->show_round_events) {
   2772		script->tool.ordered_events = false;
   2773		script->tool.finished_round = process_finished_round_event;
   2774	}
   2775	if (script->show_bpf_events) {
   2776		script->tool.ksymbol = process_bpf_events;
   2777		script->tool.bpf     = process_bpf_events;
   2778	}
   2779	if (script->show_text_poke_events) {
   2780		script->tool.ksymbol   = process_bpf_events;
   2781		script->tool.text_poke = process_text_poke_events;
   2782	}
   2783
   2784	if (perf_script__setup_per_event_dump(script)) {
   2785		pr_err("Couldn't create the per event dump files\n");
   2786		return -1;
   2787	}
   2788
   2789	ret = perf_session__process_events(script->session);
   2790
   2791	if (script->per_event_dump)
   2792		perf_script__exit_per_event_dump_stats(script);
   2793
   2794	if (debug_mode)
   2795		pr_err("Misordered timestamps: %" PRIu64 "\n", nr_unordered);
   2796
   2797	return ret;
   2798}
   2799
   2800struct script_spec {
   2801	struct list_head	node;
   2802	struct scripting_ops	*ops;
   2803	char			spec[];
   2804};
   2805
   2806static LIST_HEAD(script_specs);
   2807
   2808static struct script_spec *script_spec__new(const char *spec,
   2809					    struct scripting_ops *ops)
   2810{
   2811	struct script_spec *s = malloc(sizeof(*s) + strlen(spec) + 1);
   2812
   2813	if (s != NULL) {
   2814		strcpy(s->spec, spec);
   2815		s->ops = ops;
   2816	}
   2817
   2818	return s;
   2819}
   2820
   2821static void script_spec__add(struct script_spec *s)
   2822{
   2823	list_add_tail(&s->node, &script_specs);
   2824}
   2825
   2826static struct script_spec *script_spec__find(const char *spec)
   2827{
   2828	struct script_spec *s;
   2829
   2830	list_for_each_entry(s, &script_specs, node)
   2831		if (strcasecmp(s->spec, spec) == 0)
   2832			return s;
   2833	return NULL;
   2834}
   2835
   2836int script_spec_register(const char *spec, struct scripting_ops *ops)
   2837{
   2838	struct script_spec *s;
   2839
   2840	s = script_spec__find(spec);
   2841	if (s)
   2842		return -1;
   2843
   2844	s = script_spec__new(spec, ops);
   2845	if (!s)
   2846		return -1;
   2847	else
   2848		script_spec__add(s);
   2849
   2850	return 0;
   2851}
   2852
   2853static struct scripting_ops *script_spec__lookup(const char *spec)
   2854{
   2855	struct script_spec *s = script_spec__find(spec);
   2856	if (!s)
   2857		return NULL;
   2858
   2859	return s->ops;
   2860}
   2861
   2862static void list_available_languages(void)
   2863{
   2864	struct script_spec *s;
   2865
   2866	fprintf(stderr, "\n");
   2867	fprintf(stderr, "Scripting language extensions (used in "
   2868		"perf script -s [spec:]script.[spec]):\n\n");
   2869
   2870	list_for_each_entry(s, &script_specs, node)
   2871		fprintf(stderr, "  %-42s [%s]\n", s->spec, s->ops->name);
   2872
   2873	fprintf(stderr, "\n");
   2874}
   2875
   2876/* Find script file relative to current directory or exec path */
   2877static char *find_script(const char *script)
   2878{
   2879	char path[PATH_MAX];
   2880
   2881	if (!scripting_ops) {
   2882		const char *ext = strrchr(script, '.');
   2883
   2884		if (!ext)
   2885			return NULL;
   2886
   2887		scripting_ops = script_spec__lookup(++ext);
   2888		if (!scripting_ops)
   2889			return NULL;
   2890	}
   2891
   2892	if (access(script, R_OK)) {
   2893		char *exec_path = get_argv_exec_path();
   2894
   2895		if (!exec_path)
   2896			return NULL;
   2897		snprintf(path, sizeof(path), "%s/scripts/%s/%s",
   2898			 exec_path, scripting_ops->dirname, script);
   2899		free(exec_path);
   2900		script = path;
   2901		if (access(script, R_OK))
   2902			return NULL;
   2903	}
   2904	return strdup(script);
   2905}
   2906
   2907static int parse_scriptname(const struct option *opt __maybe_unused,
   2908			    const char *str, int unset __maybe_unused)
   2909{
   2910	char spec[PATH_MAX];
   2911	const char *script, *ext;
   2912	int len;
   2913
   2914	if (strcmp(str, "lang") == 0) {
   2915		list_available_languages();
   2916		exit(0);
   2917	}
   2918
   2919	script = strchr(str, ':');
   2920	if (script) {
   2921		len = script - str;
   2922		if (len >= PATH_MAX) {
   2923			fprintf(stderr, "invalid language specifier");
   2924			return -1;
   2925		}
   2926		strncpy(spec, str, len);
   2927		spec[len] = '\0';
   2928		scripting_ops = script_spec__lookup(spec);
   2929		if (!scripting_ops) {
   2930			fprintf(stderr, "invalid language specifier");
   2931			return -1;
   2932		}
   2933		script++;
   2934	} else {
   2935		script = str;
   2936		ext = strrchr(script, '.');
   2937		if (!ext) {
   2938			fprintf(stderr, "invalid script extension");
   2939			return -1;
   2940		}
   2941		scripting_ops = script_spec__lookup(++ext);
   2942		if (!scripting_ops) {
   2943			fprintf(stderr, "invalid script extension");
   2944			return -1;
   2945		}
   2946	}
   2947
   2948	script_name = find_script(script);
   2949	if (!script_name)
   2950		script_name = strdup(script);
   2951
   2952	return 0;
   2953}
   2954
   2955static int parse_output_fields(const struct option *opt __maybe_unused,
   2956			    const char *arg, int unset __maybe_unused)
   2957{
   2958	char *tok, *strtok_saveptr = NULL;
   2959	int i, imax = ARRAY_SIZE(all_output_options);
   2960	int j;
   2961	int rc = 0;
   2962	char *str = strdup(arg);
   2963	int type = -1;
   2964	enum { DEFAULT, SET, ADD, REMOVE } change = DEFAULT;
   2965
   2966	if (!str)
   2967		return -ENOMEM;
   2968
   2969	/* first word can state for which event type the user is specifying
   2970	 * the fields. If no type exists, the specified fields apply to all
   2971	 * event types found in the file minus the invalid fields for a type.
   2972	 */
   2973	tok = strchr(str, ':');
   2974	if (tok) {
   2975		*tok = '\0';
   2976		tok++;
   2977		if (!strcmp(str, "hw"))
   2978			type = PERF_TYPE_HARDWARE;
   2979		else if (!strcmp(str, "sw"))
   2980			type = PERF_TYPE_SOFTWARE;
   2981		else if (!strcmp(str, "trace"))
   2982			type = PERF_TYPE_TRACEPOINT;
   2983		else if (!strcmp(str, "raw"))
   2984			type = PERF_TYPE_RAW;
   2985		else if (!strcmp(str, "break"))
   2986			type = PERF_TYPE_BREAKPOINT;
   2987		else if (!strcmp(str, "synth"))
   2988			type = OUTPUT_TYPE_SYNTH;
   2989		else {
   2990			fprintf(stderr, "Invalid event type in field string.\n");
   2991			rc = -EINVAL;
   2992			goto out;
   2993		}
   2994
   2995		if (output[type].user_set)
   2996			pr_warning("Overriding previous field request for %s events.\n",
   2997				   event_type(type));
   2998
   2999		/* Don't override defaults for +- */
   3000		if (strchr(tok, '+') || strchr(tok, '-'))
   3001			goto parse;
   3002
   3003		output[type].fields = 0;
   3004		output[type].user_set = true;
   3005		output[type].wildcard_set = false;
   3006
   3007	} else {
   3008		tok = str;
   3009		if (strlen(str) == 0) {
   3010			fprintf(stderr,
   3011				"Cannot set fields to 'none' for all event types.\n");
   3012			rc = -EINVAL;
   3013			goto out;
   3014		}
   3015
   3016		/* Don't override defaults for +- */
   3017		if (strchr(str, '+') || strchr(str, '-'))
   3018			goto parse;
   3019
   3020		if (output_set_by_user())
   3021			pr_warning("Overriding previous field request for all events.\n");
   3022
   3023		for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
   3024			output[j].fields = 0;
   3025			output[j].user_set = true;
   3026			output[j].wildcard_set = true;
   3027		}
   3028	}
   3029
   3030parse:
   3031	for (tok = strtok_r(tok, ",", &strtok_saveptr); tok; tok = strtok_r(NULL, ",", &strtok_saveptr)) {
   3032		if (*tok == '+') {
   3033			if (change == SET)
   3034				goto out_badmix;
   3035			change = ADD;
   3036			tok++;
   3037		} else if (*tok == '-') {
   3038			if (change == SET)
   3039				goto out_badmix;
   3040			change = REMOVE;
   3041			tok++;
   3042		} else {
   3043			if (change != SET && change != DEFAULT)
   3044				goto out_badmix;
   3045			change = SET;
   3046		}
   3047
   3048		for (i = 0; i < imax; ++i) {
   3049			if (strcmp(tok, all_output_options[i].str) == 0)
   3050				break;
   3051		}
   3052		if (i == imax && strcmp(tok, "flags") == 0) {
   3053			print_flags = change != REMOVE;
   3054			continue;
   3055		}
   3056		if (i == imax) {
   3057			fprintf(stderr, "Invalid field requested.\n");
   3058			rc = -EINVAL;
   3059			goto out;
   3060		}
   3061
   3062		if (type == -1) {
   3063			/* add user option to all events types for
   3064			 * which it is valid
   3065			 */
   3066			for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
   3067				if (output[j].invalid_fields & all_output_options[i].field) {
   3068					pr_warning("\'%s\' not valid for %s events. Ignoring.\n",
   3069						   all_output_options[i].str, event_type(j));
   3070				} else {
   3071					if (change == REMOVE) {
   3072						output[j].fields &= ~all_output_options[i].field;
   3073						output[j].user_set_fields &= ~all_output_options[i].field;
   3074						output[j].user_unset_fields |= all_output_options[i].field;
   3075					} else {
   3076						output[j].fields |= all_output_options[i].field;
   3077						output[j].user_set_fields |= all_output_options[i].field;
   3078						output[j].user_unset_fields &= ~all_output_options[i].field;
   3079					}
   3080					output[j].user_set = true;
   3081					output[j].wildcard_set = true;
   3082				}
   3083			}
   3084		} else {
   3085			if (output[type].invalid_fields & all_output_options[i].field) {
   3086				fprintf(stderr, "\'%s\' not valid for %s events.\n",
   3087					 all_output_options[i].str, event_type(type));
   3088
   3089				rc = -EINVAL;
   3090				goto out;
   3091			}
   3092			if (change == REMOVE)
   3093				output[type].fields &= ~all_output_options[i].field;
   3094			else
   3095				output[type].fields |= all_output_options[i].field;
   3096			output[type].user_set = true;
   3097			output[type].wildcard_set = true;
   3098		}
   3099	}
   3100
   3101	if (type >= 0) {
   3102		if (output[type].fields == 0) {
   3103			pr_debug("No fields requested for %s type. "
   3104				 "Events will not be displayed.\n", event_type(type));
   3105		}
   3106	}
   3107	goto out;
   3108
   3109out_badmix:
   3110	fprintf(stderr, "Cannot mix +-field with overridden fields\n");
   3111	rc = -EINVAL;
   3112out:
   3113	free(str);
   3114	return rc;
   3115}
   3116
   3117#define for_each_lang(scripts_path, scripts_dir, lang_dirent)		\
   3118	while ((lang_dirent = readdir(scripts_dir)) != NULL)		\
   3119		if ((lang_dirent->d_type == DT_DIR ||			\
   3120		     (lang_dirent->d_type == DT_UNKNOWN &&		\
   3121		      is_directory(scripts_path, lang_dirent))) &&	\
   3122		    (strcmp(lang_dirent->d_name, ".")) &&		\
   3123		    (strcmp(lang_dirent->d_name, "..")))
   3124
   3125#define for_each_script(lang_path, lang_dir, script_dirent)		\
   3126	while ((script_dirent = readdir(lang_dir)) != NULL)		\
   3127		if (script_dirent->d_type != DT_DIR &&			\
   3128		    (script_dirent->d_type != DT_UNKNOWN ||		\
   3129		     !is_directory(lang_path, script_dirent)))
   3130
   3131
   3132#define RECORD_SUFFIX			"-record"
   3133#define REPORT_SUFFIX			"-report"
   3134
   3135struct script_desc {
   3136	struct list_head	node;
   3137	char			*name;
   3138	char			*half_liner;
   3139	char			*args;
   3140};
   3141
   3142static LIST_HEAD(script_descs);
   3143
   3144static struct script_desc *script_desc__new(const char *name)
   3145{
   3146	struct script_desc *s = zalloc(sizeof(*s));
   3147
   3148	if (s != NULL && name)
   3149		s->name = strdup(name);
   3150
   3151	return s;
   3152}
   3153
   3154static void script_desc__delete(struct script_desc *s)
   3155{
   3156	zfree(&s->name);
   3157	zfree(&s->half_liner);
   3158	zfree(&s->args);
   3159	free(s);
   3160}
   3161
   3162static void script_desc__add(struct script_desc *s)
   3163{
   3164	list_add_tail(&s->node, &script_descs);
   3165}
   3166
   3167static struct script_desc *script_desc__find(const char *name)
   3168{
   3169	struct script_desc *s;
   3170
   3171	list_for_each_entry(s, &script_descs, node)
   3172		if (strcasecmp(s->name, name) == 0)
   3173			return s;
   3174	return NULL;
   3175}
   3176
   3177static struct script_desc *script_desc__findnew(const char *name)
   3178{
   3179	struct script_desc *s = script_desc__find(name);
   3180
   3181	if (s)
   3182		return s;
   3183
   3184	s = script_desc__new(name);
   3185	if (!s)
   3186		return NULL;
   3187
   3188	script_desc__add(s);
   3189
   3190	return s;
   3191}
   3192
   3193static const char *ends_with(const char *str, const char *suffix)
   3194{
   3195	size_t suffix_len = strlen(suffix);
   3196	const char *p = str;
   3197
   3198	if (strlen(str) > suffix_len) {
   3199		p = str + strlen(str) - suffix_len;
   3200		if (!strncmp(p, suffix, suffix_len))
   3201			return p;
   3202	}
   3203
   3204	return NULL;
   3205}
   3206
   3207static int read_script_info(struct script_desc *desc, const char *filename)
   3208{
   3209	char line[BUFSIZ], *p;
   3210	FILE *fp;
   3211
   3212	fp = fopen(filename, "r");
   3213	if (!fp)
   3214		return -1;
   3215
   3216	while (fgets(line, sizeof(line), fp)) {
   3217		p = skip_spaces(line);
   3218		if (strlen(p) == 0)
   3219			continue;
   3220		if (*p != '#')
   3221			continue;
   3222		p++;
   3223		if (strlen(p) && *p == '!')
   3224			continue;
   3225
   3226		p = skip_spaces(p);
   3227		if (strlen(p) && p[strlen(p) - 1] == '\n')
   3228			p[strlen(p) - 1] = '\0';
   3229
   3230		if (!strncmp(p, "description:", strlen("description:"))) {
   3231			p += strlen("description:");
   3232			desc->half_liner = strdup(skip_spaces(p));
   3233			continue;
   3234		}
   3235
   3236		if (!strncmp(p, "args:", strlen("args:"))) {
   3237			p += strlen("args:");
   3238			desc->args = strdup(skip_spaces(p));
   3239			continue;
   3240		}
   3241	}
   3242
   3243	fclose(fp);
   3244
   3245	return 0;
   3246}
   3247
   3248static char *get_script_root(struct dirent *script_dirent, const char *suffix)
   3249{
   3250	char *script_root, *str;
   3251
   3252	script_root = strdup(script_dirent->d_name);
   3253	if (!script_root)
   3254		return NULL;
   3255
   3256	str = (char *)ends_with(script_root, suffix);
   3257	if (!str) {
   3258		free(script_root);
   3259		return NULL;
   3260	}
   3261
   3262	*str = '\0';
   3263	return script_root;
   3264}
   3265
   3266static int list_available_scripts(const struct option *opt __maybe_unused,
   3267				  const char *s __maybe_unused,
   3268				  int unset __maybe_unused)
   3269{
   3270	struct dirent *script_dirent, *lang_dirent;
   3271	char scripts_path[MAXPATHLEN];
   3272	DIR *scripts_dir, *lang_dir;
   3273	char script_path[MAXPATHLEN];
   3274	char lang_path[MAXPATHLEN];
   3275	struct script_desc *desc;
   3276	char first_half[BUFSIZ];
   3277	char *script_root;
   3278
   3279	snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
   3280
   3281	scripts_dir = opendir(scripts_path);
   3282	if (!scripts_dir) {
   3283		fprintf(stdout,
   3284			"open(%s) failed.\n"
   3285			"Check \"PERF_EXEC_PATH\" env to set scripts dir.\n",
   3286			scripts_path);
   3287		exit(-1);
   3288	}
   3289
   3290	for_each_lang(scripts_path, scripts_dir, lang_dirent) {
   3291		scnprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
   3292			  lang_dirent->d_name);
   3293		lang_dir = opendir(lang_path);
   3294		if (!lang_dir)
   3295			continue;
   3296
   3297		for_each_script(lang_path, lang_dir, script_dirent) {
   3298			script_root = get_script_root(script_dirent, REPORT_SUFFIX);
   3299			if (script_root) {
   3300				desc = script_desc__findnew(script_root);
   3301				scnprintf(script_path, MAXPATHLEN, "%s/%s",
   3302					  lang_path, script_dirent->d_name);
   3303				read_script_info(desc, script_path);
   3304				free(script_root);
   3305			}
   3306		}
   3307	}
   3308
   3309	fprintf(stdout, "List of available trace scripts:\n");
   3310	list_for_each_entry(desc, &script_descs, node) {
   3311		sprintf(first_half, "%s %s", desc->name,
   3312			desc->args ? desc->args : "");
   3313		fprintf(stdout, "  %-36s %s\n", first_half,
   3314			desc->half_liner ? desc->half_liner : "");
   3315	}
   3316
   3317	exit(0);
   3318}
   3319
   3320static int add_dlarg(const struct option *opt __maybe_unused,
   3321		     const char *s, int unset __maybe_unused)
   3322{
   3323	char *arg = strdup(s);
   3324	void *a;
   3325
   3326	if (!arg)
   3327		return -1;
   3328
   3329	a = realloc(dlargv, sizeof(dlargv[0]) * (dlargc + 1));
   3330	if (!a) {
   3331		free(arg);
   3332		return -1;
   3333	}
   3334
   3335	dlargv = a;
   3336	dlargv[dlargc++] = arg;
   3337
   3338	return 0;
   3339}
   3340
   3341static void free_dlarg(void)
   3342{
   3343	while (dlargc--)
   3344		free(dlargv[dlargc]);
   3345	free(dlargv);
   3346}
   3347
   3348/*
   3349 * Some scripts specify the required events in their "xxx-record" file,
   3350 * this function will check if the events in perf.data match those
   3351 * mentioned in the "xxx-record".
   3352 *
   3353 * Fixme: All existing "xxx-record" are all in good formats "-e event ",
   3354 * which is covered well now. And new parsing code should be added to
   3355 * cover the future complex formats like event groups etc.
   3356 */
   3357static int check_ev_match(char *dir_name, char *scriptname,
   3358			struct perf_session *session)
   3359{
   3360	char filename[MAXPATHLEN], evname[128];
   3361	char line[BUFSIZ], *p;
   3362	struct evsel *pos;
   3363	int match, len;
   3364	FILE *fp;
   3365
   3366	scnprintf(filename, MAXPATHLEN, "%s/bin/%s-record", dir_name, scriptname);
   3367
   3368	fp = fopen(filename, "r");
   3369	if (!fp)
   3370		return -1;
   3371
   3372	while (fgets(line, sizeof(line), fp)) {
   3373		p = skip_spaces(line);
   3374		if (*p == '#')
   3375			continue;
   3376
   3377		while (strlen(p)) {
   3378			p = strstr(p, "-e");
   3379			if (!p)
   3380				break;
   3381
   3382			p += 2;
   3383			p = skip_spaces(p);
   3384			len = strcspn(p, " \t");
   3385			if (!len)
   3386				break;
   3387
   3388			snprintf(evname, len + 1, "%s", p);
   3389
   3390			match = 0;
   3391			evlist__for_each_entry(session->evlist, pos) {
   3392				if (!strcmp(evsel__name(pos), evname)) {
   3393					match = 1;
   3394					break;
   3395				}
   3396			}
   3397
   3398			if (!match) {
   3399				fclose(fp);
   3400				return -1;
   3401			}
   3402		}
   3403	}
   3404
   3405	fclose(fp);
   3406	return 0;
   3407}
   3408
   3409/*
   3410 * Return -1 if none is found, otherwise the actual scripts number.
   3411 *
   3412 * Currently the only user of this function is the script browser, which
   3413 * will list all statically runnable scripts, select one, execute it and
   3414 * show the output in a perf browser.
   3415 */
   3416int find_scripts(char **scripts_array, char **scripts_path_array, int num,
   3417		 int pathlen)
   3418{
   3419	struct dirent *script_dirent, *lang_dirent;
   3420	char scripts_path[MAXPATHLEN], lang_path[MAXPATHLEN];
   3421	DIR *scripts_dir, *lang_dir;
   3422	struct perf_session *session;
   3423	struct perf_data data = {
   3424		.path = input_name,
   3425		.mode = PERF_DATA_MODE_READ,
   3426	};
   3427	char *temp;
   3428	int i = 0;
   3429
   3430	session = perf_session__new(&data, NULL);
   3431	if (IS_ERR(session))
   3432		return PTR_ERR(session);
   3433
   3434	snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
   3435
   3436	scripts_dir = opendir(scripts_path);
   3437	if (!scripts_dir) {
   3438		perf_session__delete(session);
   3439		return -1;
   3440	}
   3441
   3442	for_each_lang(scripts_path, scripts_dir, lang_dirent) {
   3443		scnprintf(lang_path, MAXPATHLEN, "%s/%s", scripts_path,
   3444			  lang_dirent->d_name);
   3445#ifndef HAVE_LIBPERL_SUPPORT
   3446		if (strstr(lang_path, "perl"))
   3447			continue;
   3448#endif
   3449#ifndef HAVE_LIBPYTHON_SUPPORT
   3450		if (strstr(lang_path, "python"))
   3451			continue;
   3452#endif
   3453
   3454		lang_dir = opendir(lang_path);
   3455		if (!lang_dir)
   3456			continue;
   3457
   3458		for_each_script(lang_path, lang_dir, script_dirent) {
   3459			/* Skip those real time scripts: xxxtop.p[yl] */
   3460			if (strstr(script_dirent->d_name, "top."))
   3461				continue;
   3462			if (i >= num)
   3463				break;
   3464			snprintf(scripts_path_array[i], pathlen, "%s/%s",
   3465				lang_path,
   3466				script_dirent->d_name);
   3467			temp = strchr(script_dirent->d_name, '.');
   3468			snprintf(scripts_array[i],
   3469				(temp - script_dirent->d_name) + 1,
   3470				"%s", script_dirent->d_name);
   3471
   3472			if (check_ev_match(lang_path,
   3473					scripts_array[i], session))
   3474				continue;
   3475
   3476			i++;
   3477		}
   3478		closedir(lang_dir);
   3479	}
   3480
   3481	closedir(scripts_dir);
   3482	perf_session__delete(session);
   3483	return i;
   3484}
   3485
   3486static char *get_script_path(const char *script_root, const char *suffix)
   3487{
   3488	struct dirent *script_dirent, *lang_dirent;
   3489	char scripts_path[MAXPATHLEN];
   3490	char script_path[MAXPATHLEN];
   3491	DIR *scripts_dir, *lang_dir;
   3492	char lang_path[MAXPATHLEN];
   3493	char *__script_root;
   3494
   3495	snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
   3496
   3497	scripts_dir = opendir(scripts_path);
   3498	if (!scripts_dir)
   3499		return NULL;
   3500
   3501	for_each_lang(scripts_path, scripts_dir, lang_dirent) {
   3502		scnprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
   3503			  lang_dirent->d_name);
   3504		lang_dir = opendir(lang_path);
   3505		if (!lang_dir)
   3506			continue;
   3507
   3508		for_each_script(lang_path, lang_dir, script_dirent) {
   3509			__script_root = get_script_root(script_dirent, suffix);
   3510			if (__script_root && !strcmp(script_root, __script_root)) {
   3511				free(__script_root);
   3512				closedir(scripts_dir);
   3513				scnprintf(script_path, MAXPATHLEN, "%s/%s",
   3514					  lang_path, script_dirent->d_name);
   3515				closedir(lang_dir);
   3516				return strdup(script_path);
   3517			}
   3518			free(__script_root);
   3519		}
   3520		closedir(lang_dir);
   3521	}
   3522	closedir(scripts_dir);
   3523
   3524	return NULL;
   3525}
   3526
   3527static bool is_top_script(const char *script_path)
   3528{
   3529	return ends_with(script_path, "top") != NULL;
   3530}
   3531
   3532static int has_required_arg(char *script_path)
   3533{
   3534	struct script_desc *desc;
   3535	int n_args = 0;
   3536	char *p;
   3537
   3538	desc = script_desc__new(NULL);
   3539
   3540	if (read_script_info(desc, script_path))
   3541		goto out;
   3542
   3543	if (!desc->args)
   3544		goto out;
   3545
   3546	for (p = desc->args; *p; p++)
   3547		if (*p == '<')
   3548			n_args++;
   3549out:
   3550	script_desc__delete(desc);
   3551
   3552	return n_args;
   3553}
   3554
   3555static int have_cmd(int argc, const char **argv)
   3556{
   3557	char **__argv = malloc(sizeof(const char *) * argc);
   3558
   3559	if (!__argv) {
   3560		pr_err("malloc failed\n");
   3561		return -1;
   3562	}
   3563
   3564	memcpy(__argv, argv, sizeof(const char *) * argc);
   3565	argc = parse_options(argc, (const char **)__argv, record_options,
   3566			     NULL, PARSE_OPT_STOP_AT_NON_OPTION);
   3567	free(__argv);
   3568
   3569	system_wide = (argc == 0);
   3570
   3571	return 0;
   3572}
   3573
   3574static void script__setup_sample_type(struct perf_script *script)
   3575{
   3576	struct perf_session *session = script->session;
   3577	u64 sample_type = evlist__combined_sample_type(session->evlist);
   3578
   3579	callchain_param_setup(sample_type, perf_env__arch(session->machines.host.env));
   3580
   3581	if (script->stitch_lbr && (callchain_param.record_mode != CALLCHAIN_LBR)) {
   3582		pr_warning("Can't find LBR callchain. Switch off --stitch-lbr.\n"
   3583			   "Please apply --call-graph lbr when recording.\n");
   3584		script->stitch_lbr = false;
   3585	}
   3586}
   3587
   3588static int process_stat_round_event(struct perf_session *session,
   3589				    union perf_event *event)
   3590{
   3591	struct perf_record_stat_round *round = &event->stat_round;
   3592	struct evsel *counter;
   3593
   3594	evlist__for_each_entry(session->evlist, counter) {
   3595		perf_stat_process_counter(&stat_config, counter);
   3596		process_stat(counter, round->time);
   3597	}
   3598
   3599	process_stat_interval(round->time);
   3600	return 0;
   3601}
   3602
   3603static int process_stat_config_event(struct perf_session *session __maybe_unused,
   3604				     union perf_event *event)
   3605{
   3606	perf_event__read_stat_config(&stat_config, &event->stat_config);
   3607	return 0;
   3608}
   3609
   3610static int set_maps(struct perf_script *script)
   3611{
   3612	struct evlist *evlist = script->session->evlist;
   3613
   3614	if (!script->cpus || !script->threads)
   3615		return 0;
   3616
   3617	if (WARN_ONCE(script->allocated, "stats double allocation\n"))
   3618		return -EINVAL;
   3619
   3620	perf_evlist__set_maps(&evlist->core, script->cpus, script->threads);
   3621
   3622	if (evlist__alloc_stats(evlist, true))
   3623		return -ENOMEM;
   3624
   3625	script->allocated = true;
   3626	return 0;
   3627}
   3628
   3629static
   3630int process_thread_map_event(struct perf_session *session,
   3631			     union perf_event *event)
   3632{
   3633	struct perf_tool *tool = session->tool;
   3634	struct perf_script *script = container_of(tool, struct perf_script, tool);
   3635
   3636	if (script->threads) {
   3637		pr_warning("Extra thread map event, ignoring.\n");
   3638		return 0;
   3639	}
   3640
   3641	script->threads = thread_map__new_event(&event->thread_map);
   3642	if (!script->threads)
   3643		return -ENOMEM;
   3644
   3645	return set_maps(script);
   3646}
   3647
   3648static
   3649int process_cpu_map_event(struct perf_session *session,
   3650			  union perf_event *event)
   3651{
   3652	struct perf_tool *tool = session->tool;
   3653	struct perf_script *script = container_of(tool, struct perf_script, tool);
   3654
   3655	if (script->cpus) {
   3656		pr_warning("Extra cpu map event, ignoring.\n");
   3657		return 0;
   3658	}
   3659
   3660	script->cpus = cpu_map__new_data(&event->cpu_map.data);
   3661	if (!script->cpus)
   3662		return -ENOMEM;
   3663
   3664	return set_maps(script);
   3665}
   3666
   3667static int process_feature_event(struct perf_session *session,
   3668				 union perf_event *event)
   3669{
   3670	if (event->feat.feat_id < HEADER_LAST_FEATURE)
   3671		return perf_event__process_feature(session, event);
   3672	return 0;
   3673}
   3674
   3675#ifdef HAVE_AUXTRACE_SUPPORT
   3676static int perf_script__process_auxtrace_info(struct perf_session *session,
   3677					      union perf_event *event)
   3678{
   3679	struct perf_tool *tool = session->tool;
   3680
   3681	int ret = perf_event__process_auxtrace_info(session, event);
   3682
   3683	if (ret == 0) {
   3684		struct perf_script *script = container_of(tool, struct perf_script, tool);
   3685
   3686		ret = perf_script__setup_per_event_dump(script);
   3687	}
   3688
   3689	return ret;
   3690}
   3691#else
   3692#define perf_script__process_auxtrace_info 0
   3693#endif
   3694
   3695static int parse_insn_trace(const struct option *opt __maybe_unused,
   3696			    const char *str __maybe_unused,
   3697			    int unset __maybe_unused)
   3698{
   3699	parse_output_fields(NULL, "+insn,-event,-period", 0);
   3700	itrace_parse_synth_opts(opt, "i0ns", 0);
   3701	symbol_conf.nanosecs = true;
   3702	return 0;
   3703}
   3704
   3705static int parse_xed(const struct option *opt __maybe_unused,
   3706		     const char *str __maybe_unused,
   3707		     int unset __maybe_unused)
   3708{
   3709	if (isatty(1))
   3710		force_pager("xed -F insn: -A -64 | less");
   3711	else
   3712		force_pager("xed -F insn: -A -64");
   3713	return 0;
   3714}
   3715
   3716static int parse_call_trace(const struct option *opt __maybe_unused,
   3717			    const char *str __maybe_unused,
   3718			    int unset __maybe_unused)
   3719{
   3720	parse_output_fields(NULL, "-ip,-addr,-event,-period,+callindent", 0);
   3721	itrace_parse_synth_opts(opt, "cewp", 0);
   3722	symbol_conf.nanosecs = true;
   3723	symbol_conf.pad_output_len_dso = 50;
   3724	return 0;
   3725}
   3726
   3727static int parse_callret_trace(const struct option *opt __maybe_unused,
   3728			    const char *str __maybe_unused,
   3729			    int unset __maybe_unused)
   3730{
   3731	parse_output_fields(NULL, "-ip,-addr,-event,-period,+callindent,+flags", 0);
   3732	itrace_parse_synth_opts(opt, "crewp", 0);
   3733	symbol_conf.nanosecs = true;
   3734	return 0;
   3735}
   3736
   3737int cmd_script(int argc, const char **argv)
   3738{
   3739	bool show_full_info = false;
   3740	bool header = false;
   3741	bool header_only = false;
   3742	bool script_started = false;
   3743	char *rec_script_path = NULL;
   3744	char *rep_script_path = NULL;
   3745	struct perf_session *session;
   3746	struct itrace_synth_opts itrace_synth_opts = {
   3747		.set = false,
   3748		.default_no_sample = true,
   3749	};
   3750	struct utsname uts;
   3751	char *script_path = NULL;
   3752	const char *dlfilter_file = NULL;
   3753	const char **__argv;
   3754	int i, j, err = 0;
   3755	struct perf_script script = {
   3756		.tool = {
   3757			.sample		 = process_sample_event,
   3758			.mmap		 = perf_event__process_mmap,
   3759			.mmap2		 = perf_event__process_mmap2,
   3760			.comm		 = perf_event__process_comm,
   3761			.namespaces	 = perf_event__process_namespaces,
   3762			.cgroup		 = perf_event__process_cgroup,
   3763			.exit		 = perf_event__process_exit,
   3764			.fork		 = perf_event__process_fork,
   3765			.attr		 = process_attr,
   3766			.event_update   = perf_event__process_event_update,
   3767			.tracing_data	 = perf_event__process_tracing_data,
   3768			.feature	 = process_feature_event,
   3769			.build_id	 = perf_event__process_build_id,
   3770			.id_index	 = perf_event__process_id_index,
   3771			.auxtrace_info	 = perf_script__process_auxtrace_info,
   3772			.auxtrace	 = perf_event__process_auxtrace,
   3773			.auxtrace_error	 = perf_event__process_auxtrace_error,
   3774			.stat		 = perf_event__process_stat_event,
   3775			.stat_round	 = process_stat_round_event,
   3776			.stat_config	 = process_stat_config_event,
   3777			.thread_map	 = process_thread_map_event,
   3778			.cpu_map	 = process_cpu_map_event,
   3779			.throttle	 = process_throttle_event,
   3780			.unthrottle	 = process_throttle_event,
   3781			.ordered_events	 = true,
   3782			.ordering_requires_timestamps = true,
   3783		},
   3784	};
   3785	struct perf_data data = {
   3786		.mode = PERF_DATA_MODE_READ,
   3787	};
   3788	const struct option options[] = {
   3789	OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
   3790		    "dump raw trace in ASCII"),
   3791	OPT_INCR('v', "verbose", &verbose,
   3792		 "be more verbose (show symbol address, etc)"),
   3793	OPT_BOOLEAN('L', "Latency", &latency_format,
   3794		    "show latency attributes (irqs/preemption disabled, etc)"),
   3795	OPT_CALLBACK_NOOPT('l', "list", NULL, NULL, "list available scripts",
   3796			   list_available_scripts),
   3797	OPT_CALLBACK_NOOPT(0, "list-dlfilters", NULL, NULL, "list available dlfilters",
   3798			   list_available_dlfilters),
   3799	OPT_CALLBACK('s', "script", NULL, "name",
   3800		     "script file name (lang:script name, script name, or *)",
   3801		     parse_scriptname),
   3802	OPT_STRING('g', "gen-script", &generate_script_lang, "lang",
   3803		   "generate perf-script.xx script in specified language"),
   3804	OPT_STRING(0, "dlfilter", &dlfilter_file, "file", "filter .so file name"),
   3805	OPT_CALLBACK(0, "dlarg", NULL, "argument", "filter argument",
   3806		     add_dlarg),
   3807	OPT_STRING('i', "input", &input_name, "file", "input file name"),
   3808	OPT_BOOLEAN('d', "debug-mode", &debug_mode,
   3809		   "do various checks like samples ordering and lost events"),
   3810	OPT_BOOLEAN(0, "header", &header, "Show data header."),
   3811	OPT_BOOLEAN(0, "header-only", &header_only, "Show only data header."),
   3812	OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
   3813		   "file", "vmlinux pathname"),
   3814	OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
   3815		   "file", "kallsyms pathname"),
   3816	OPT_BOOLEAN('G', "hide-call-graph", &no_callchain,
   3817		    "When printing symbols do not display call chain"),
   3818	OPT_CALLBACK(0, "symfs", NULL, "directory",
   3819		     "Look for files with symbols relative to this directory",
   3820		     symbol__config_symfs),
   3821	OPT_CALLBACK('F', "fields", NULL, "str",
   3822		     "comma separated output fields prepend with 'type:'. "
   3823		     "+field to add and -field to remove."
   3824		     "Valid types: hw,sw,trace,raw,synth. "
   3825		     "Fields: comm,tid,pid,time,cpu,event,trace,ip,sym,dso,"
   3826		     "addr,symoff,srcline,period,iregs,uregs,brstack,"
   3827		     "brstacksym,flags,bpf-output,brstackinsn,brstackinsnlen,brstackoff,"
   3828		     "callindent,insn,insnlen,synth,phys_addr,metric,misc,ipc,tod,"
   3829		     "data_page_size,code_page_size,ins_lat",
   3830		     parse_output_fields),
   3831	OPT_BOOLEAN('a', "all-cpus", &system_wide,
   3832		    "system-wide collection from all CPUs"),
   3833	OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
   3834		   "only consider symbols in these DSOs"),
   3835	OPT_STRING('S', "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
   3836		   "only consider these symbols"),
   3837	OPT_INTEGER(0, "addr-range", &symbol_conf.addr_range,
   3838		    "Use with -S to list traced records within address range"),
   3839	OPT_CALLBACK_OPTARG(0, "insn-trace", &itrace_synth_opts, NULL, NULL,
   3840			"Decode instructions from itrace", parse_insn_trace),
   3841	OPT_CALLBACK_OPTARG(0, "xed", NULL, NULL, NULL,
   3842			"Run xed disassembler on output", parse_xed),
   3843	OPT_CALLBACK_OPTARG(0, "call-trace", &itrace_synth_opts, NULL, NULL,
   3844			"Decode calls from from itrace", parse_call_trace),
   3845	OPT_CALLBACK_OPTARG(0, "call-ret-trace", &itrace_synth_opts, NULL, NULL,
   3846			"Decode calls and returns from itrace", parse_callret_trace),
   3847	OPT_STRING(0, "graph-function", &symbol_conf.graph_function, "symbol[,symbol...]",
   3848			"Only print symbols and callees with --call-trace/--call-ret-trace"),
   3849	OPT_STRING(0, "stop-bt", &symbol_conf.bt_stop_list_str, "symbol[,symbol...]",
   3850		   "Stop display of callgraph at these symbols"),
   3851	OPT_STRING('C', "cpu", &cpu_list, "cpu", "list of cpus to profile"),
   3852	OPT_STRING('c', "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
   3853		   "only display events for these comms"),
   3854	OPT_STRING(0, "pid", &symbol_conf.pid_list_str, "pid[,pid...]",
   3855		   "only consider symbols in these pids"),
   3856	OPT_STRING(0, "tid", &symbol_conf.tid_list_str, "tid[,tid...]",
   3857		   "only consider symbols in these tids"),
   3858	OPT_UINTEGER(0, "max-stack", &scripting_max_stack,
   3859		     "Set the maximum stack depth when parsing the callchain, "
   3860		     "anything beyond the specified depth will be ignored. "
   3861		     "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
   3862	OPT_BOOLEAN(0, "reltime", &reltime, "Show time stamps relative to start"),
   3863	OPT_BOOLEAN(0, "deltatime", &deltatime, "Show time stamps relative to previous event"),
   3864	OPT_BOOLEAN('I', "show-info", &show_full_info,
   3865		    "display extended information from perf.data file"),
   3866	OPT_BOOLEAN('\0', "show-kernel-path", &symbol_conf.show_kernel_path,
   3867		    "Show the path of [kernel.kallsyms]"),
   3868	OPT_BOOLEAN('\0', "show-task-events", &script.show_task_events,
   3869		    "Show the fork/comm/exit events"),
   3870	OPT_BOOLEAN('\0', "show-mmap-events", &script.show_mmap_events,
   3871		    "Show the mmap events"),
   3872	OPT_BOOLEAN('\0', "show-switch-events", &script.show_switch_events,
   3873		    "Show context switch events (if recorded)"),
   3874	OPT_BOOLEAN('\0', "show-namespace-events", &script.show_namespace_events,
   3875		    "Show namespace events (if recorded)"),
   3876	OPT_BOOLEAN('\0', "show-cgroup-events", &script.show_cgroup_events,
   3877		    "Show cgroup events (if recorded)"),
   3878	OPT_BOOLEAN('\0', "show-lost-events", &script.show_lost_events,
   3879		    "Show lost events (if recorded)"),
   3880	OPT_BOOLEAN('\0', "show-round-events", &script.show_round_events,
   3881		    "Show round events (if recorded)"),
   3882	OPT_BOOLEAN('\0', "show-bpf-events", &script.show_bpf_events,
   3883		    "Show bpf related events (if recorded)"),
   3884	OPT_BOOLEAN('\0', "show-text-poke-events", &script.show_text_poke_events,
   3885		    "Show text poke related events (if recorded)"),
   3886	OPT_BOOLEAN('\0', "per-event-dump", &script.per_event_dump,
   3887		    "Dump trace output to files named by the monitored events"),
   3888	OPT_BOOLEAN('f', "force", &symbol_conf.force, "don't complain, do it"),
   3889	OPT_INTEGER(0, "max-blocks", &max_blocks,
   3890		    "Maximum number of code blocks to dump with brstackinsn"),
   3891	OPT_BOOLEAN(0, "ns", &symbol_conf.nanosecs,
   3892		    "Use 9 decimal places when displaying time"),
   3893	OPT_CALLBACK_OPTARG(0, "itrace", &itrace_synth_opts, NULL, "opts",
   3894			    "Instruction Tracing options\n" ITRACE_HELP,
   3895			    itrace_parse_synth_opts),
   3896	OPT_BOOLEAN(0, "full-source-path", &srcline_full_filename,
   3897			"Show full source file name path for source lines"),
   3898	OPT_BOOLEAN(0, "demangle", &symbol_conf.demangle,
   3899			"Enable symbol demangling"),
   3900	OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
   3901			"Enable kernel symbol demangling"),
   3902	OPT_STRING(0, "time", &script.time_str, "str",
   3903		   "Time span of interest (start,stop)"),
   3904	OPT_BOOLEAN(0, "inline", &symbol_conf.inline_name,
   3905		    "Show inline function"),
   3906	OPT_STRING(0, "guestmount", &symbol_conf.guestmount, "directory",
   3907		   "guest mount directory under which every guest os"
   3908		   " instance has a subdir"),
   3909	OPT_STRING(0, "guestvmlinux", &symbol_conf.default_guest_vmlinux_name,
   3910		   "file", "file saving guest os vmlinux"),
   3911	OPT_STRING(0, "guestkallsyms", &symbol_conf.default_guest_kallsyms,
   3912		   "file", "file saving guest os /proc/kallsyms"),
   3913	OPT_STRING(0, "guestmodules", &symbol_conf.default_guest_modules,
   3914		   "file", "file saving guest os /proc/modules"),
   3915	OPT_BOOLEAN(0, "guest-code", &symbol_conf.guest_code,
   3916		    "Guest code can be found in hypervisor process"),
   3917	OPT_BOOLEAN('\0', "stitch-lbr", &script.stitch_lbr,
   3918		    "Enable LBR callgraph stitching approach"),
   3919	OPTS_EVSWITCH(&script.evswitch),
   3920	OPT_END()
   3921	};
   3922	const char * const script_subcommands[] = { "record", "report", NULL };
   3923	const char *script_usage[] = {
   3924		"perf script [<options>]",
   3925		"perf script [<options>] record <script> [<record-options>] <command>",
   3926		"perf script [<options>] report <script> [script-args]",
   3927		"perf script [<options>] <script> [<record-options>] <command>",
   3928		"perf script [<options>] <top-script> [script-args]",
   3929		NULL
   3930	};
   3931
   3932	perf_set_singlethreaded();
   3933
   3934	setup_scripting();
   3935
   3936	argc = parse_options_subcommand(argc, argv, options, script_subcommands, script_usage,
   3937			     PARSE_OPT_STOP_AT_NON_OPTION);
   3938
   3939	if (symbol_conf.guestmount ||
   3940	    symbol_conf.default_guest_vmlinux_name ||
   3941	    symbol_conf.default_guest_kallsyms ||
   3942	    symbol_conf.default_guest_modules ||
   3943	    symbol_conf.guest_code) {
   3944		/*
   3945		 * Enable guest sample processing.
   3946		 */
   3947		perf_guest = true;
   3948	}
   3949
   3950	data.path  = input_name;
   3951	data.force = symbol_conf.force;
   3952
   3953	if (symbol__validate_sym_arguments())
   3954		return -1;
   3955
   3956	if (argc > 1 && strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
   3957		rec_script_path = get_script_path(argv[1], RECORD_SUFFIX);
   3958		if (!rec_script_path)
   3959			return cmd_record(argc, argv);
   3960	}
   3961
   3962	if (argc > 1 && strlen(argv[0]) > 2 && strstarts("report", argv[0])) {
   3963		rep_script_path = get_script_path(argv[1], REPORT_SUFFIX);
   3964		if (!rep_script_path) {
   3965			fprintf(stderr,
   3966				"Please specify a valid report script"
   3967				"(see 'perf script -l' for listing)\n");
   3968			return -1;
   3969		}
   3970	}
   3971
   3972	if (reltime && deltatime) {
   3973		fprintf(stderr,
   3974			"reltime and deltatime - the two don't get along well. "
   3975			"Please limit to --reltime or --deltatime.\n");
   3976		return -1;
   3977	}
   3978
   3979	if ((itrace_synth_opts.callchain || itrace_synth_opts.add_callchain) &&
   3980	    itrace_synth_opts.callchain_sz > scripting_max_stack)
   3981		scripting_max_stack = itrace_synth_opts.callchain_sz;
   3982
   3983	/* make sure PERF_EXEC_PATH is set for scripts */
   3984	set_argv_exec_path(get_argv_exec_path());
   3985
   3986	if (argc && !script_name && !rec_script_path && !rep_script_path) {
   3987		int live_pipe[2];
   3988		int rep_args;
   3989		pid_t pid;
   3990
   3991		rec_script_path = get_script_path(argv[0], RECORD_SUFFIX);
   3992		rep_script_path = get_script_path(argv[0], REPORT_SUFFIX);
   3993
   3994		if (!rec_script_path && !rep_script_path) {
   3995			script_name = find_script(argv[0]);
   3996			if (script_name) {
   3997				argc -= 1;
   3998				argv += 1;
   3999				goto script_found;
   4000			}
   4001			usage_with_options_msg(script_usage, options,
   4002				"Couldn't find script `%s'\n\n See perf"
   4003				" script -l for available scripts.\n", argv[0]);
   4004		}
   4005
   4006		if (is_top_script(argv[0])) {
   4007			rep_args = argc - 1;
   4008		} else {
   4009			int rec_args;
   4010
   4011			rep_args = has_required_arg(rep_script_path);
   4012			rec_args = (argc - 1) - rep_args;
   4013			if (rec_args < 0) {
   4014				usage_with_options_msg(script_usage, options,
   4015					"`%s' script requires options."
   4016					"\n\n See perf script -l for available "
   4017					"scripts and options.\n", argv[0]);
   4018			}
   4019		}
   4020
   4021		if (pipe(live_pipe) < 0) {
   4022			perror("failed to create pipe");
   4023			return -1;
   4024		}
   4025
   4026		pid = fork();
   4027		if (pid < 0) {
   4028			perror("failed to fork");
   4029			return -1;
   4030		}
   4031
   4032		if (!pid) {
   4033			j = 0;
   4034
   4035			dup2(live_pipe[1], 1);
   4036			close(live_pipe[0]);
   4037
   4038			if (is_top_script(argv[0])) {
   4039				system_wide = true;
   4040			} else if (!system_wide) {
   4041				if (have_cmd(argc - rep_args, &argv[rep_args]) != 0) {
   4042					err = -1;
   4043					goto out;
   4044				}
   4045			}
   4046
   4047			__argv = malloc((argc + 6) * sizeof(const char *));
   4048			if (!__argv) {
   4049				pr_err("malloc failed\n");
   4050				err = -ENOMEM;
   4051				goto out;
   4052			}
   4053
   4054			__argv[j++] = "/bin/sh";
   4055			__argv[j++] = rec_script_path;
   4056			if (system_wide)
   4057				__argv[j++] = "-a";
   4058			__argv[j++] = "-q";
   4059			__argv[j++] = "-o";
   4060			__argv[j++] = "-";
   4061			for (i = rep_args + 1; i < argc; i++)
   4062				__argv[j++] = argv[i];
   4063			__argv[j++] = NULL;
   4064
   4065			execvp("/bin/sh", (char **)__argv);
   4066			free(__argv);
   4067			exit(-1);
   4068		}
   4069
   4070		dup2(live_pipe[0], 0);
   4071		close(live_pipe[1]);
   4072
   4073		__argv = malloc((argc + 4) * sizeof(const char *));
   4074		if (!__argv) {
   4075			pr_err("malloc failed\n");
   4076			err = -ENOMEM;
   4077			goto out;
   4078		}
   4079
   4080		j = 0;
   4081		__argv[j++] = "/bin/sh";
   4082		__argv[j++] = rep_script_path;
   4083		for (i = 1; i < rep_args + 1; i++)
   4084			__argv[j++] = argv[i];
   4085		__argv[j++] = "-i";
   4086		__argv[j++] = "-";
   4087		__argv[j++] = NULL;
   4088
   4089		execvp("/bin/sh", (char **)__argv);
   4090		free(__argv);
   4091		exit(-1);
   4092	}
   4093script_found:
   4094	if (rec_script_path)
   4095		script_path = rec_script_path;
   4096	if (rep_script_path)
   4097		script_path = rep_script_path;
   4098
   4099	if (script_path) {
   4100		j = 0;
   4101
   4102		if (!rec_script_path)
   4103			system_wide = false;
   4104		else if (!system_wide) {
   4105			if (have_cmd(argc - 1, &argv[1]) != 0) {
   4106				err = -1;
   4107				goto out;
   4108			}
   4109		}
   4110
   4111		__argv = malloc((argc + 2) * sizeof(const char *));
   4112		if (!__argv) {
   4113			pr_err("malloc failed\n");
   4114			err = -ENOMEM;
   4115			goto out;
   4116		}
   4117
   4118		__argv[j++] = "/bin/sh";
   4119		__argv[j++] = script_path;
   4120		if (system_wide)
   4121			__argv[j++] = "-a";
   4122		for (i = 2; i < argc; i++)
   4123			__argv[j++] = argv[i];
   4124		__argv[j++] = NULL;
   4125
   4126		execvp("/bin/sh", (char **)__argv);
   4127		free(__argv);
   4128		exit(-1);
   4129	}
   4130
   4131	if (dlfilter_file) {
   4132		dlfilter = dlfilter__new(dlfilter_file, dlargc, dlargv);
   4133		if (!dlfilter)
   4134			return -1;
   4135	}
   4136
   4137	if (!script_name) {
   4138		setup_pager();
   4139		use_browser = 0;
   4140	}
   4141
   4142	session = perf_session__new(&data, &script.tool);
   4143	if (IS_ERR(session))
   4144		return PTR_ERR(session);
   4145
   4146	if (header || header_only) {
   4147		script.tool.show_feat_hdr = SHOW_FEAT_HEADER;
   4148		perf_session__fprintf_info(session, stdout, show_full_info);
   4149		if (header_only)
   4150			goto out_delete;
   4151	}
   4152	if (show_full_info)
   4153		script.tool.show_feat_hdr = SHOW_FEAT_HEADER_FULL_INFO;
   4154
   4155	if (symbol__init(&session->header.env) < 0)
   4156		goto out_delete;
   4157
   4158	uname(&uts);
   4159	if (data.is_pipe) { /* Assume pipe_mode indicates native_arch */
   4160		native_arch = true;
   4161	} else if (session->header.env.arch) {
   4162		if (!strcmp(uts.machine, session->header.env.arch))
   4163			native_arch = true;
   4164		else if (!strcmp(uts.machine, "x86_64") &&
   4165			 !strcmp(session->header.env.arch, "i386"))
   4166			native_arch = true;
   4167	}
   4168
   4169	script.session = session;
   4170	script__setup_sample_type(&script);
   4171
   4172	if ((output[PERF_TYPE_HARDWARE].fields & PERF_OUTPUT_CALLINDENT) ||
   4173	    symbol_conf.graph_function)
   4174		itrace_synth_opts.thread_stack = true;
   4175
   4176	session->itrace_synth_opts = &itrace_synth_opts;
   4177
   4178	if (cpu_list) {
   4179		err = perf_session__cpu_bitmap(session, cpu_list, cpu_bitmap);
   4180		if (err < 0)
   4181			goto out_delete;
   4182		itrace_synth_opts.cpu_bitmap = cpu_bitmap;
   4183	}
   4184
   4185	if (!no_callchain)
   4186		symbol_conf.use_callchain = true;
   4187	else
   4188		symbol_conf.use_callchain = false;
   4189
   4190	if (session->tevent.pevent &&
   4191	    tep_set_function_resolver(session->tevent.pevent,
   4192				      machine__resolve_kernel_addr,
   4193				      &session->machines.host) < 0) {
   4194		pr_err("%s: failed to set libtraceevent function resolver\n", __func__);
   4195		err = -1;
   4196		goto out_delete;
   4197	}
   4198
   4199	if (generate_script_lang) {
   4200		struct stat perf_stat;
   4201		int input;
   4202
   4203		if (output_set_by_user()) {
   4204			fprintf(stderr,
   4205				"custom fields not supported for generated scripts");
   4206			err = -EINVAL;
   4207			goto out_delete;
   4208		}
   4209
   4210		input = open(data.path, O_RDONLY);	/* input_name */
   4211		if (input < 0) {
   4212			err = -errno;
   4213			perror("failed to open file");
   4214			goto out_delete;
   4215		}
   4216
   4217		err = fstat(input, &perf_stat);
   4218		if (err < 0) {
   4219			perror("failed to stat file");
   4220			goto out_delete;
   4221		}
   4222
   4223		if (!perf_stat.st_size) {
   4224			fprintf(stderr, "zero-sized file, nothing to do!\n");
   4225			goto out_delete;
   4226		}
   4227
   4228		scripting_ops = script_spec__lookup(generate_script_lang);
   4229		if (!scripting_ops) {
   4230			fprintf(stderr, "invalid language specifier");
   4231			err = -ENOENT;
   4232			goto out_delete;
   4233		}
   4234
   4235		err = scripting_ops->generate_script(session->tevent.pevent,
   4236						     "perf-script");
   4237		goto out_delete;
   4238	}
   4239
   4240	err = dlfilter__start(dlfilter, session);
   4241	if (err)
   4242		goto out_delete;
   4243
   4244	if (script_name) {
   4245		err = scripting_ops->start_script(script_name, argc, argv, session);
   4246		if (err)
   4247			goto out_delete;
   4248		pr_debug("perf script started with script %s\n\n", script_name);
   4249		script_started = true;
   4250	}
   4251
   4252
   4253	err = perf_session__check_output_opt(session);
   4254	if (err < 0)
   4255		goto out_delete;
   4256
   4257	if (script.time_str) {
   4258		err = perf_time__parse_for_ranges_reltime(script.time_str, session,
   4259						  &script.ptime_range,
   4260						  &script.range_size,
   4261						  &script.range_num,
   4262						  reltime);
   4263		if (err < 0)
   4264			goto out_delete;
   4265
   4266		itrace_synth_opts__set_time_range(&itrace_synth_opts,
   4267						  script.ptime_range,
   4268						  script.range_num);
   4269	}
   4270
   4271	err = evswitch__init(&script.evswitch, session->evlist, stderr);
   4272	if (err)
   4273		goto out_delete;
   4274
   4275	if (zstd_init(&(session->zstd_data), 0) < 0)
   4276		pr_warning("Decompression initialization failed. Reported data may be incomplete.\n");
   4277
   4278	err = __cmd_script(&script);
   4279
   4280	flush_scripting();
   4281
   4282out_delete:
   4283	if (script.ptime_range) {
   4284		itrace_synth_opts__clear_time_range(&itrace_synth_opts);
   4285		zfree(&script.ptime_range);
   4286	}
   4287
   4288	zstd_fini(&(session->zstd_data));
   4289	evlist__free_stats(session->evlist);
   4290	perf_session__delete(session);
   4291	perf_script__exit(&script);
   4292
   4293	if (script_started)
   4294		cleanup_scripting();
   4295	dlfilter__cleanup(dlfilter);
   4296	free_dlarg();
   4297out:
   4298	return err;
   4299}