xref: /linux/tools/perf/builtin-trace.c (revision 95d692f9aba7c13b5b3e8d842656c47bde7e551f)
1 /*
2  * builtin-trace.c
3  *
4  * Builtin 'trace' command:
5  *
6  * Display a continuously updated trace of any workload, CPU, specific PID,
7  * system wide, etc.  Default format is loosely strace like, but any other
8  * event may be specified using --event.
9  *
10  * Copyright (C) 2012, 2013, 2014, 2015 Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
11  *
12  * Initially based on the 'trace' prototype by Thomas Gleixner:
13  *
14  * http://lwn.net/Articles/415728/ ("Announcing a new utility: 'trace'")
15  */
16 
17 #include "util/record.h"
18 #include <api/fs/tracing_path.h>
19 #ifdef HAVE_LIBBPF_SUPPORT
20 #include <bpf/bpf.h>
21 #include <bpf/libbpf.h>
22 #include <bpf/btf.h>
23 #endif
24 #include "util/bpf_map.h"
25 #include "util/rlimit.h"
26 #include "builtin.h"
27 #include "util/cgroup.h"
28 #include "util/color.h"
29 #include "util/config.h"
30 #include "util/debug.h"
31 #include "util/dso.h"
32 #include "util/env.h"
33 #include "util/event.h"
34 #include "util/evsel.h"
35 #include "util/evsel_fprintf.h"
36 #include "util/synthetic-events.h"
37 #include "util/evlist.h"
38 #include "util/evswitch.h"
39 #include "util/hashmap.h"
40 #include "util/mmap.h"
41 #include <subcmd/pager.h>
42 #include <subcmd/exec-cmd.h>
43 #include "util/machine.h"
44 #include "util/map.h"
45 #include "util/symbol.h"
46 #include "util/path.h"
47 #include "util/session.h"
48 #include "util/thread.h"
49 #include <subcmd/parse-options.h>
50 #include "util/strlist.h"
51 #include "util/intlist.h"
52 #include "util/thread_map.h"
53 #include "util/stat.h"
54 #include "util/tool.h"
55 #include "util/trace.h"
56 #include "util/util.h"
57 #include "trace/beauty/beauty.h"
58 #include "trace-event.h"
59 #include "util/parse-events.h"
60 #include "util/tracepoint.h"
61 #include "callchain.h"
62 #include "print_binary.h"
63 #include "string2.h"
64 #include "syscalltbl.h"
65 #include "../perf.h"
66 #include "trace_augment.h"
67 #include "dwarf-regs.h"
68 
69 #include <errno.h>
70 #include <inttypes.h>
71 #include <poll.h>
72 #include <signal.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <linux/err.h>
76 #include <linux/filter.h>
77 #include <linux/kernel.h>
78 #include <linux/list_sort.h>
79 #include <linux/random.h>
80 #include <linux/stringify.h>
81 #include <linux/time64.h>
82 #include <linux/zalloc.h>
83 #include <fcntl.h>
84 #include <sys/sysmacros.h>
85 
86 #include <linux/ctype.h>
87 #include <perf/mmap.h>
88 #include <tools/libc_compat.h>
89 
90 #ifdef HAVE_LIBTRACEEVENT
91 #include <event-parse.h>
92 #endif
93 
94 #ifndef O_CLOEXEC
95 # define O_CLOEXEC		02000000
96 #endif
97 
98 #ifndef F_LINUX_SPECIFIC_BASE
99 # define F_LINUX_SPECIFIC_BASE	1024
100 #endif
101 
102 #define RAW_SYSCALL_ARGS_NUM	6
103 
104 /*
105  * strtoul: Go from a string to a value, i.e. for msr: MSR_FS_BASE to 0xc0000100
106  *
107  * We have to explicitely mark the direction of the flow of data, if from the
108  * kernel to user space or the other way around, since the BPF collector we
109  * have so far copies only from user to kernel space, mark the arguments that
110  * go that direction, so that we don´t end up collecting the previous contents
111  * for syscall args that goes from kernel to user space.
112  */
113 struct syscall_arg_fmt {
114 	size_t	   (*scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
115 	bool	   (*strtoul)(char *bf, size_t size, struct syscall_arg *arg, u64 *val);
116 	unsigned long (*mask_val)(struct syscall_arg *arg, unsigned long val);
117 	void	   *parm;
118 	const char *name;
119 	u16	   nr_entries; // for arrays
120 	bool	   from_user;
121 	bool	   show_zero;
122 #ifdef HAVE_LIBBPF_SUPPORT
123 	const struct btf_type *type;
124 	int	   type_id; /* used in btf_dump */
125 #endif
126 };
127 
128 struct syscall_fmt {
129 	const char *name;
130 	const char *alias;
131 	struct {
132 		const char *sys_enter,
133 			   *sys_exit;
134 	}	   bpf_prog_name;
135 	struct syscall_arg_fmt arg[RAW_SYSCALL_ARGS_NUM];
136 	u8	   nr_args;
137 	bool	   errpid;
138 	bool	   timeout;
139 	bool	   hexret;
140 };
141 
142 struct trace {
143 	struct perf_tool	tool;
144 	struct {
145 		/** Sorted sycall numbers used by the trace. */
146 		struct syscall  **table;
147 		/** Size of table. */
148 		size_t		table_size;
149 		struct {
150 			struct evsel *sys_enter,
151 				*sys_exit,
152 				*bpf_output;
153 		}		events;
154 	} syscalls;
155 #ifdef HAVE_LIBBPF_SUPPORT
156 	struct btf		*btf;
157 #endif
158 	struct record_opts	opts;
159 	struct evlist	*evlist;
160 	struct machine		*host;
161 	struct thread		*current;
162 	struct cgroup		*cgroup;
163 	u64			base_time;
164 	FILE			*output;
165 	unsigned long		nr_events;
166 	unsigned long		nr_events_printed;
167 	unsigned long		max_events;
168 	struct evswitch		evswitch;
169 	struct strlist		*ev_qualifier;
170 	struct {
171 		size_t		nr;
172 		int		*entries;
173 	}			ev_qualifier_ids;
174 	struct {
175 		size_t		nr;
176 		pid_t		*entries;
177 		struct bpf_map  *map;
178 	}			filter_pids;
179 	/*
180 	 * TODO: The map is from an ID (aka system call number) to struct
181 	 * syscall_stats. If there is >1 e_machine, such as i386 and x86-64
182 	 * processes, then the stats here will gather wrong the statistics for
183 	 * the non EM_HOST system calls. A fix would be to add the e_machine
184 	 * into the key, but this would make the code inconsistent with the
185 	 * per-thread version.
186 	 */
187 	struct hashmap		*syscall_stats;
188 	double			duration_filter;
189 	double			runtime_ms;
190 	unsigned long		pfmaj, pfmin;
191 	struct {
192 		u64		vfs_getname,
193 				proc_getname;
194 	} stats;
195 	unsigned int		max_stack;
196 	unsigned int		min_stack;
197 	enum trace_summary_mode	summary_mode;
198 	int			raw_augmented_syscalls_args_size;
199 	bool			raw_augmented_syscalls;
200 	bool			fd_path_disabled;
201 	bool			sort_events;
202 	bool			not_ev_qualifier;
203 	bool			live;
204 	bool			full_time;
205 	bool			sched;
206 	bool			multiple_threads;
207 	bool			summary;
208 	bool			summary_only;
209 	bool			errno_summary;
210 	bool			failure_only;
211 	bool			show_comm;
212 	bool			print_sample;
213 	bool			show_tool_stats;
214 	bool			trace_syscalls;
215 	bool			libtraceevent_print;
216 	bool			kernel_syscallchains;
217 	s16			args_alignment;
218 	bool			show_tstamp;
219 	bool			show_duration;
220 	bool			show_zeros;
221 	bool			show_arg_names;
222 	bool			show_string_prefix;
223 	bool			force;
224 	bool			vfs_getname;
225 	bool			force_btf;
226 	bool			summary_bpf;
227 	int			trace_pgfaults;
228 	char			*perfconfig_events;
229 	struct {
230 		struct ordered_events	data;
231 		u64			last;
232 	} oe;
233 	const char		*uid_str;
234 };
235 
236 static void trace__load_vmlinux_btf(struct trace *trace __maybe_unused)
237 {
238 #ifdef HAVE_LIBBPF_SUPPORT
239 	if (trace->btf != NULL)
240 		return;
241 
242 	trace->btf = btf__load_vmlinux_btf();
243 	if (verbose > 0) {
244 		fprintf(trace->output, trace->btf ? "vmlinux BTF loaded\n" :
245 						    "Failed to load vmlinux BTF\n");
246 	}
247 #endif
248 }
249 
250 struct tp_field {
251 	int offset;
252 	union {
253 		u64 (*integer)(struct tp_field *field, struct perf_sample *sample);
254 		void *(*pointer)(struct tp_field *field, struct perf_sample *sample);
255 	};
256 };
257 
258 #define TP_UINT_FIELD(bits) \
259 static u64 tp_field__u##bits(struct tp_field *field, struct perf_sample *sample) \
260 { \
261 	u##bits value; \
262 	memcpy(&value, sample->raw_data + field->offset, sizeof(value)); \
263 	return value;  \
264 }
265 
266 TP_UINT_FIELD(8);
267 TP_UINT_FIELD(16);
268 TP_UINT_FIELD(32);
269 TP_UINT_FIELD(64);
270 
271 #define TP_UINT_FIELD__SWAPPED(bits) \
272 static u64 tp_field__swapped_u##bits(struct tp_field *field, struct perf_sample *sample) \
273 { \
274 	u##bits value; \
275 	memcpy(&value, sample->raw_data + field->offset, sizeof(value)); \
276 	return bswap_##bits(value);\
277 }
278 
279 TP_UINT_FIELD__SWAPPED(16);
280 TP_UINT_FIELD__SWAPPED(32);
281 TP_UINT_FIELD__SWAPPED(64);
282 
283 static int __tp_field__init_uint(struct tp_field *field, int size, int offset, bool needs_swap)
284 {
285 	field->offset = offset;
286 
287 	switch (size) {
288 	case 1:
289 		field->integer = tp_field__u8;
290 		break;
291 	case 2:
292 		field->integer = needs_swap ? tp_field__swapped_u16 : tp_field__u16;
293 		break;
294 	case 4:
295 		field->integer = needs_swap ? tp_field__swapped_u32 : tp_field__u32;
296 		break;
297 	case 8:
298 		field->integer = needs_swap ? tp_field__swapped_u64 : tp_field__u64;
299 		break;
300 	default:
301 		return -1;
302 	}
303 
304 	return 0;
305 }
306 
307 static int tp_field__init_uint(struct tp_field *field, struct tep_format_field *format_field, bool needs_swap)
308 {
309 	return __tp_field__init_uint(field, format_field->size, format_field->offset, needs_swap);
310 }
311 
312 static void *tp_field__ptr(struct tp_field *field, struct perf_sample *sample)
313 {
314 	return sample->raw_data + field->offset;
315 }
316 
317 static int __tp_field__init_ptr(struct tp_field *field, int offset)
318 {
319 	field->offset = offset;
320 	field->pointer = tp_field__ptr;
321 	return 0;
322 }
323 
324 static int tp_field__init_ptr(struct tp_field *field, struct tep_format_field *format_field)
325 {
326 	return __tp_field__init_ptr(field, format_field->offset);
327 }
328 
329 struct syscall_tp {
330 	struct tp_field id;
331 	union {
332 		struct tp_field args, ret;
333 	};
334 };
335 
336 /*
337  * The evsel->priv as used by 'perf trace'
338  * sc:	for raw_syscalls:sys_{enter,exit} and syscalls:sys_{enter,exit}_SYSCALLNAME
339  * fmt: for all the other tracepoints
340  */
341 struct evsel_trace {
342 	struct syscall_tp	sc;
343 	struct syscall_arg_fmt  *fmt;
344 };
345 
346 static struct evsel_trace *evsel_trace__new(void)
347 {
348 	return zalloc(sizeof(struct evsel_trace));
349 }
350 
351 static void evsel_trace__delete(struct evsel_trace *et)
352 {
353 	if (et == NULL)
354 		return;
355 
356 	zfree(&et->fmt);
357 	free(et);
358 }
359 
360 /*
361  * Used with raw_syscalls:sys_{enter,exit} and with the
362  * syscalls:sys_{enter,exit}_SYSCALL tracepoints
363  */
364 static inline struct syscall_tp *__evsel__syscall_tp(struct evsel *evsel)
365 {
366 	struct evsel_trace *et = evsel->priv;
367 
368 	return &et->sc;
369 }
370 
371 static struct syscall_tp *evsel__syscall_tp(struct evsel *evsel)
372 {
373 	if (evsel->priv == NULL) {
374 		evsel->priv = evsel_trace__new();
375 		if (evsel->priv == NULL)
376 			return NULL;
377 	}
378 
379 	return __evsel__syscall_tp(evsel);
380 }
381 
382 /*
383  * Used with all the other tracepoints.
384  */
385 static inline struct syscall_arg_fmt *__evsel__syscall_arg_fmt(struct evsel *evsel)
386 {
387 	struct evsel_trace *et = evsel->priv;
388 
389 	return et->fmt;
390 }
391 
392 static struct syscall_arg_fmt *evsel__syscall_arg_fmt(struct evsel *evsel)
393 {
394 	struct evsel_trace *et = evsel->priv;
395 
396 	if (evsel->priv == NULL) {
397 		et = evsel->priv = evsel_trace__new();
398 
399 		if (et == NULL)
400 			return NULL;
401 	}
402 
403 	if (et->fmt == NULL) {
404 		const struct tep_event *tp_format = evsel__tp_format(evsel);
405 
406 		if (tp_format == NULL)
407 			goto out_delete;
408 
409 		et->fmt = calloc(tp_format->format.nr_fields, sizeof(struct syscall_arg_fmt));
410 		if (et->fmt == NULL)
411 			goto out_delete;
412 	}
413 
414 	return __evsel__syscall_arg_fmt(evsel);
415 
416 out_delete:
417 	evsel_trace__delete(evsel->priv);
418 	evsel->priv = NULL;
419 	return NULL;
420 }
421 
422 static int evsel__init_tp_uint_field(struct evsel *evsel, struct tp_field *field, const char *name)
423 {
424 	struct tep_format_field *format_field = evsel__field(evsel, name);
425 
426 	if (format_field == NULL)
427 		return -1;
428 
429 	return tp_field__init_uint(field, format_field, evsel->needs_swap);
430 }
431 
432 #define perf_evsel__init_sc_tp_uint_field(evsel, name) \
433 	({ struct syscall_tp *sc = __evsel__syscall_tp(evsel);\
434 	   evsel__init_tp_uint_field(evsel, &sc->name, #name); })
435 
436 static int evsel__init_tp_ptr_field(struct evsel *evsel, struct tp_field *field, const char *name)
437 {
438 	struct tep_format_field *format_field = evsel__field(evsel, name);
439 
440 	if (format_field == NULL)
441 		return -1;
442 
443 	return tp_field__init_ptr(field, format_field);
444 }
445 
446 #define perf_evsel__init_sc_tp_ptr_field(evsel, name) \
447 	({ struct syscall_tp *sc = __evsel__syscall_tp(evsel);\
448 	   evsel__init_tp_ptr_field(evsel, &sc->name, #name); })
449 
450 static void evsel__delete_priv(struct evsel *evsel)
451 {
452 	zfree(&evsel->priv);
453 	evsel__delete(evsel);
454 }
455 
456 static int evsel__init_syscall_tp(struct evsel *evsel)
457 {
458 	struct syscall_tp *sc = evsel__syscall_tp(evsel);
459 
460 	if (sc != NULL) {
461 		if (evsel__init_tp_uint_field(evsel, &sc->id, "__syscall_nr") &&
462 		    evsel__init_tp_uint_field(evsel, &sc->id, "nr"))
463 			return -ENOENT;
464 
465 		return 0;
466 	}
467 
468 	return -ENOMEM;
469 }
470 
471 static int evsel__init_augmented_syscall_tp(struct evsel *evsel, struct evsel *tp)
472 {
473 	struct syscall_tp *sc = evsel__syscall_tp(evsel);
474 
475 	if (sc != NULL) {
476 		struct tep_format_field *syscall_id = evsel__field(tp, "id");
477 		if (syscall_id == NULL)
478 			syscall_id = evsel__field(tp, "__syscall_nr");
479 		if (syscall_id == NULL ||
480 		    __tp_field__init_uint(&sc->id, syscall_id->size, syscall_id->offset, evsel->needs_swap))
481 			return -EINVAL;
482 
483 		return 0;
484 	}
485 
486 	return -ENOMEM;
487 }
488 
489 static int evsel__init_augmented_syscall_tp_args(struct evsel *evsel)
490 {
491 	struct syscall_tp *sc = __evsel__syscall_tp(evsel);
492 
493 	return __tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64));
494 }
495 
496 static int evsel__init_augmented_syscall_tp_ret(struct evsel *evsel)
497 {
498 	struct syscall_tp *sc = __evsel__syscall_tp(evsel);
499 
500 	return __tp_field__init_uint(&sc->ret, sizeof(u64), sc->id.offset + sizeof(u64), evsel->needs_swap);
501 }
502 
503 static int evsel__init_raw_syscall_tp(struct evsel *evsel, void *handler)
504 {
505 	if (evsel__syscall_tp(evsel) != NULL) {
506 		if (perf_evsel__init_sc_tp_uint_field(evsel, id))
507 			return -ENOENT;
508 
509 		evsel->handler = handler;
510 		return 0;
511 	}
512 
513 	return -ENOMEM;
514 }
515 
516 static struct evsel *perf_evsel__raw_syscall_newtp(const char *direction, void *handler)
517 {
518 	struct evsel *evsel = evsel__newtp("raw_syscalls", direction);
519 
520 	/* older kernel (e.g., RHEL6) use syscalls:{enter,exit} */
521 	if (IS_ERR(evsel))
522 		evsel = evsel__newtp("syscalls", direction);
523 
524 	if (IS_ERR(evsel))
525 		return NULL;
526 
527 	if (evsel__init_raw_syscall_tp(evsel, handler))
528 		goto out_delete;
529 
530 	return evsel;
531 
532 out_delete:
533 	evsel__delete_priv(evsel);
534 	return NULL;
535 }
536 
537 #define perf_evsel__sc_tp_uint(evsel, name, sample) \
538 	({ struct syscall_tp *fields = __evsel__syscall_tp(evsel); \
539 	   fields->name.integer(&fields->name, sample); })
540 
541 #define perf_evsel__sc_tp_ptr(evsel, name, sample) \
542 	({ struct syscall_tp *fields = __evsel__syscall_tp(evsel); \
543 	   fields->name.pointer(&fields->name, sample); })
544 
545 size_t strarray__scnprintf_suffix(struct strarray *sa, char *bf, size_t size, const char *intfmt, bool show_suffix, int val)
546 {
547 	int idx = val - sa->offset;
548 
549 	if (idx < 0 || idx >= sa->nr_entries || sa->entries[idx] == NULL) {
550 		size_t printed = scnprintf(bf, size, intfmt, val);
551 		if (show_suffix)
552 			printed += scnprintf(bf + printed, size - printed, " /* %s??? */", sa->prefix);
553 		return printed;
554 	}
555 
556 	return scnprintf(bf, size, "%s%s", sa->entries[idx], show_suffix ? sa->prefix : "");
557 }
558 
559 size_t strarray__scnprintf(struct strarray *sa, char *bf, size_t size, const char *intfmt, bool show_prefix, int val)
560 {
561 	int idx = val - sa->offset;
562 
563 	if (idx < 0 || idx >= sa->nr_entries || sa->entries[idx] == NULL) {
564 		size_t printed = scnprintf(bf, size, intfmt, val);
565 		if (show_prefix)
566 			printed += scnprintf(bf + printed, size - printed, " /* %s??? */", sa->prefix);
567 		return printed;
568 	}
569 
570 	return scnprintf(bf, size, "%s%s", show_prefix ? sa->prefix : "", sa->entries[idx]);
571 }
572 
573 static size_t __syscall_arg__scnprintf_strarray(char *bf, size_t size,
574 						const char *intfmt,
575 					        struct syscall_arg *arg)
576 {
577 	return strarray__scnprintf(arg->parm, bf, size, intfmt, arg->show_string_prefix, arg->val);
578 }
579 
580 static size_t syscall_arg__scnprintf_strarray(char *bf, size_t size,
581 					      struct syscall_arg *arg)
582 {
583 	return __syscall_arg__scnprintf_strarray(bf, size, "%d", arg);
584 }
585 
586 #define SCA_STRARRAY syscall_arg__scnprintf_strarray
587 
588 bool syscall_arg__strtoul_strarray(char *bf, size_t size, struct syscall_arg *arg, u64 *ret)
589 {
590 	return strarray__strtoul(arg->parm, bf, size, ret);
591 }
592 
593 bool syscall_arg__strtoul_strarray_flags(char *bf, size_t size, struct syscall_arg *arg, u64 *ret)
594 {
595 	return strarray__strtoul_flags(arg->parm, bf, size, ret);
596 }
597 
598 bool syscall_arg__strtoul_strarrays(char *bf, size_t size, struct syscall_arg *arg, u64 *ret)
599 {
600 	return strarrays__strtoul(arg->parm, bf, size, ret);
601 }
602 
603 size_t syscall_arg__scnprintf_strarray_flags(char *bf, size_t size, struct syscall_arg *arg)
604 {
605 	return strarray__scnprintf_flags(arg->parm, bf, size, arg->show_string_prefix, arg->val);
606 }
607 
608 size_t strarrays__scnprintf(struct strarrays *sas, char *bf, size_t size, const char *intfmt, bool show_prefix, int val)
609 {
610 	size_t printed;
611 	int i;
612 
613 	for (i = 0; i < sas->nr_entries; ++i) {
614 		struct strarray *sa = sas->entries[i];
615 		int idx = val - sa->offset;
616 
617 		if (idx >= 0 && idx < sa->nr_entries) {
618 			if (sa->entries[idx] == NULL)
619 				break;
620 			return scnprintf(bf, size, "%s%s", show_prefix ? sa->prefix : "", sa->entries[idx]);
621 		}
622 	}
623 
624 	printed = scnprintf(bf, size, intfmt, val);
625 	if (show_prefix)
626 		printed += scnprintf(bf + printed, size - printed, " /* %s??? */", sas->entries[0]->prefix);
627 	return printed;
628 }
629 
630 bool strarray__strtoul(struct strarray *sa, char *bf, size_t size, u64 *ret)
631 {
632 	int i;
633 
634 	for (i = 0; i < sa->nr_entries; ++i) {
635 		if (sa->entries[i] && strncmp(sa->entries[i], bf, size) == 0 && sa->entries[i][size] == '\0') {
636 			*ret = sa->offset + i;
637 			return true;
638 		}
639 	}
640 
641 	return false;
642 }
643 
644 bool strarray__strtoul_flags(struct strarray *sa, char *bf, size_t size, u64 *ret)
645 {
646 	u64 val = 0;
647 	char *tok = bf, *sep, *end;
648 
649 	*ret = 0;
650 
651 	while (size != 0) {
652 		int toklen = size;
653 
654 		sep = memchr(tok, '|', size);
655 		if (sep != NULL) {
656 			size -= sep - tok + 1;
657 
658 			end = sep - 1;
659 			while (end > tok && isspace(*end))
660 				--end;
661 
662 			toklen = end - tok + 1;
663 		}
664 
665 		while (isspace(*tok))
666 			++tok;
667 
668 		if (isalpha(*tok) || *tok == '_') {
669 			if (!strarray__strtoul(sa, tok, toklen, &val))
670 				return false;
671 		} else
672 			val = strtoul(tok, NULL, 0);
673 
674 		*ret |= (1 << (val - 1));
675 
676 		if (sep == NULL)
677 			break;
678 		tok = sep + 1;
679 	}
680 
681 	return true;
682 }
683 
684 bool strarrays__strtoul(struct strarrays *sas, char *bf, size_t size, u64 *ret)
685 {
686 	int i;
687 
688 	for (i = 0; i < sas->nr_entries; ++i) {
689 		struct strarray *sa = sas->entries[i];
690 
691 		if (strarray__strtoul(sa, bf, size, ret))
692 			return true;
693 	}
694 
695 	return false;
696 }
697 
698 size_t syscall_arg__scnprintf_strarrays(char *bf, size_t size,
699 					struct syscall_arg *arg)
700 {
701 	return strarrays__scnprintf(arg->parm, bf, size, "%d", arg->show_string_prefix, arg->val);
702 }
703 
704 #ifndef AT_FDCWD
705 #define AT_FDCWD	-100
706 #endif
707 
708 static size_t syscall_arg__scnprintf_fd_at(char *bf, size_t size,
709 					   struct syscall_arg *arg)
710 {
711 	int fd = arg->val;
712 	const char *prefix = "AT_FD";
713 
714 	if (fd == AT_FDCWD)
715 		return scnprintf(bf, size, "%s%s", arg->show_string_prefix ? prefix : "", "CWD");
716 
717 	return syscall_arg__scnprintf_fd(bf, size, arg);
718 }
719 
720 #define SCA_FDAT syscall_arg__scnprintf_fd_at
721 
722 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
723 					      struct syscall_arg *arg);
724 
725 #define SCA_CLOSE_FD syscall_arg__scnprintf_close_fd
726 
727 size_t syscall_arg__scnprintf_hex(char *bf, size_t size, struct syscall_arg *arg)
728 {
729 	return scnprintf(bf, size, "%#lx", arg->val);
730 }
731 
732 size_t syscall_arg__scnprintf_ptr(char *bf, size_t size, struct syscall_arg *arg)
733 {
734 	if (arg->val == 0)
735 		return scnprintf(bf, size, "NULL");
736 	return syscall_arg__scnprintf_hex(bf, size, arg);
737 }
738 
739 size_t syscall_arg__scnprintf_int(char *bf, size_t size, struct syscall_arg *arg)
740 {
741 	return scnprintf(bf, size, "%d", arg->val);
742 }
743 
744 size_t syscall_arg__scnprintf_long(char *bf, size_t size, struct syscall_arg *arg)
745 {
746 	return scnprintf(bf, size, "%ld", arg->val);
747 }
748 
749 static size_t syscall_arg__scnprintf_char_array(char *bf, size_t size, struct syscall_arg *arg)
750 {
751 	// XXX Hey, maybe for sched:sched_switch prev/next comm fields we can
752 	//     fill missing comms using thread__set_comm()...
753 	//     here or in a special syscall_arg__scnprintf_pid_sched_tp...
754 	return scnprintf(bf, size, "\"%-.*s\"", arg->fmt->nr_entries ?: arg->len, arg->val);
755 }
756 
757 #define SCA_CHAR_ARRAY syscall_arg__scnprintf_char_array
758 
759 static const char *bpf_cmd[] = {
760 	"MAP_CREATE", "MAP_LOOKUP_ELEM", "MAP_UPDATE_ELEM", "MAP_DELETE_ELEM",
761 	"MAP_GET_NEXT_KEY", "PROG_LOAD", "OBJ_PIN", "OBJ_GET", "PROG_ATTACH",
762 	"PROG_DETACH", "PROG_TEST_RUN", "PROG_GET_NEXT_ID", "MAP_GET_NEXT_ID",
763 	"PROG_GET_FD_BY_ID", "MAP_GET_FD_BY_ID", "OBJ_GET_INFO_BY_FD",
764 	"PROG_QUERY", "RAW_TRACEPOINT_OPEN", "BTF_LOAD", "BTF_GET_FD_BY_ID",
765 	"TASK_FD_QUERY", "MAP_LOOKUP_AND_DELETE_ELEM", "MAP_FREEZE",
766 	"BTF_GET_NEXT_ID", "MAP_LOOKUP_BATCH", "MAP_LOOKUP_AND_DELETE_BATCH",
767 	"MAP_UPDATE_BATCH", "MAP_DELETE_BATCH", "LINK_CREATE", "LINK_UPDATE",
768 	"LINK_GET_FD_BY_ID", "LINK_GET_NEXT_ID", "ENABLE_STATS", "ITER_CREATE",
769 	"LINK_DETACH", "PROG_BIND_MAP",
770 };
771 static DEFINE_STRARRAY(bpf_cmd, "BPF_");
772 
773 static const char *fsmount_flags[] = {
774 	[1] = "CLOEXEC",
775 };
776 static DEFINE_STRARRAY(fsmount_flags, "FSMOUNT_");
777 
778 #include "trace/beauty/generated/fsconfig_arrays.c"
779 
780 static DEFINE_STRARRAY(fsconfig_cmds, "FSCONFIG_");
781 
782 static const char *epoll_ctl_ops[] = { "ADD", "DEL", "MOD", };
783 static DEFINE_STRARRAY_OFFSET(epoll_ctl_ops, "EPOLL_CTL_", 1);
784 
785 static const char *itimers[] = { "REAL", "VIRTUAL", "PROF", };
786 static DEFINE_STRARRAY(itimers, "ITIMER_");
787 
788 static const char *keyctl_options[] = {
789 	"GET_KEYRING_ID", "JOIN_SESSION_KEYRING", "UPDATE", "REVOKE", "CHOWN",
790 	"SETPERM", "DESCRIBE", "CLEAR", "LINK", "UNLINK", "SEARCH", "READ",
791 	"INSTANTIATE", "NEGATE", "SET_REQKEY_KEYRING", "SET_TIMEOUT",
792 	"ASSUME_AUTHORITY", "GET_SECURITY", "SESSION_TO_PARENT", "REJECT",
793 	"INSTANTIATE_IOV", "INVALIDATE", "GET_PERSISTENT",
794 };
795 static DEFINE_STRARRAY(keyctl_options, "KEYCTL_");
796 
797 static const char *whences[] = { "SET", "CUR", "END",
798 #ifdef SEEK_DATA
799 "DATA",
800 #endif
801 #ifdef SEEK_HOLE
802 "HOLE",
803 #endif
804 };
805 static DEFINE_STRARRAY(whences, "SEEK_");
806 
807 static const char *fcntl_cmds[] = {
808 	"DUPFD", "GETFD", "SETFD", "GETFL", "SETFL", "GETLK", "SETLK",
809 	"SETLKW", "SETOWN", "GETOWN", "SETSIG", "GETSIG", "GETLK64",
810 	"SETLK64", "SETLKW64", "SETOWN_EX", "GETOWN_EX",
811 	"GETOWNER_UIDS",
812 };
813 static DEFINE_STRARRAY(fcntl_cmds, "F_");
814 
815 static const char *fcntl_linux_specific_cmds[] = {
816 	"SETLEASE", "GETLEASE", "NOTIFY", "DUPFD_QUERY", [5] = "CANCELLK", "DUPFD_CLOEXEC",
817 	"SETPIPE_SZ", "GETPIPE_SZ", "ADD_SEALS", "GET_SEALS",
818 	"GET_RW_HINT", "SET_RW_HINT", "GET_FILE_RW_HINT", "SET_FILE_RW_HINT",
819 };
820 
821 static DEFINE_STRARRAY_OFFSET(fcntl_linux_specific_cmds, "F_", F_LINUX_SPECIFIC_BASE);
822 
823 static struct strarray *fcntl_cmds_arrays[] = {
824 	&strarray__fcntl_cmds,
825 	&strarray__fcntl_linux_specific_cmds,
826 };
827 
828 static DEFINE_STRARRAYS(fcntl_cmds_arrays);
829 
830 static const char *rlimit_resources[] = {
831 	"CPU", "FSIZE", "DATA", "STACK", "CORE", "RSS", "NPROC", "NOFILE",
832 	"MEMLOCK", "AS", "LOCKS", "SIGPENDING", "MSGQUEUE", "NICE", "RTPRIO",
833 	"RTTIME",
834 };
835 static DEFINE_STRARRAY(rlimit_resources, "RLIMIT_");
836 
837 static const char *sighow[] = { "BLOCK", "UNBLOCK", "SETMASK", };
838 static DEFINE_STRARRAY(sighow, "SIG_");
839 
840 static const char *clockid[] = {
841 	"REALTIME", "MONOTONIC", "PROCESS_CPUTIME_ID", "THREAD_CPUTIME_ID",
842 	"MONOTONIC_RAW", "REALTIME_COARSE", "MONOTONIC_COARSE", "BOOTTIME",
843 	"REALTIME_ALARM", "BOOTTIME_ALARM", "SGI_CYCLE", "TAI"
844 };
845 static DEFINE_STRARRAY(clockid, "CLOCK_");
846 
847 static size_t syscall_arg__scnprintf_access_mode(char *bf, size_t size,
848 						 struct syscall_arg *arg)
849 {
850 	bool show_prefix = arg->show_string_prefix;
851 	const char *suffix = "_OK";
852 	size_t printed = 0;
853 	int mode = arg->val;
854 
855 	if (mode == F_OK) /* 0 */
856 		return scnprintf(bf, size, "F%s", show_prefix ? suffix : "");
857 #define	P_MODE(n) \
858 	if (mode & n##_OK) { \
859 		printed += scnprintf(bf + printed, size - printed, "%s%s", #n, show_prefix ? suffix : ""); \
860 		mode &= ~n##_OK; \
861 	}
862 
863 	P_MODE(R);
864 	P_MODE(W);
865 	P_MODE(X);
866 #undef P_MODE
867 
868 	if (mode)
869 		printed += scnprintf(bf + printed, size - printed, "|%#x", mode);
870 
871 	return printed;
872 }
873 
874 #define SCA_ACCMODE syscall_arg__scnprintf_access_mode
875 
876 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
877 					      struct syscall_arg *arg);
878 
879 #define SCA_FILENAME syscall_arg__scnprintf_filename
880 
881 // 'argname' is just documentational at this point, to remove the previous comment with that info
882 #define SCA_FILENAME_FROM_USER(argname) \
883 	  { .scnprintf	= SCA_FILENAME, \
884 	    .from_user	= true, }
885 
886 static size_t syscall_arg__scnprintf_buf(char *bf, size_t size, struct syscall_arg *arg);
887 
888 #define SCA_BUF syscall_arg__scnprintf_buf
889 
890 static size_t syscall_arg__scnprintf_pipe_flags(char *bf, size_t size,
891 						struct syscall_arg *arg)
892 {
893 	bool show_prefix = arg->show_string_prefix;
894 	const char *prefix = "O_";
895 	int printed = 0, flags = arg->val;
896 
897 #define	P_FLAG(n) \
898 	if (flags & O_##n) { \
899 		printed += scnprintf(bf + printed, size - printed, "%s%s%s", printed ? "|" : "", show_prefix ? prefix : "", #n); \
900 		flags &= ~O_##n; \
901 	}
902 
903 	P_FLAG(CLOEXEC);
904 	P_FLAG(NONBLOCK);
905 #undef P_FLAG
906 
907 	if (flags)
908 		printed += scnprintf(bf + printed, size - printed, "%s%#x", printed ? "|" : "", flags);
909 
910 	return printed;
911 }
912 
913 #define SCA_PIPE_FLAGS syscall_arg__scnprintf_pipe_flags
914 
915 #ifndef GRND_NONBLOCK
916 #define GRND_NONBLOCK	0x0001
917 #endif
918 #ifndef GRND_RANDOM
919 #define GRND_RANDOM	0x0002
920 #endif
921 
922 static size_t syscall_arg__scnprintf_getrandom_flags(char *bf, size_t size,
923 						   struct syscall_arg *arg)
924 {
925 	bool show_prefix = arg->show_string_prefix;
926 	const char *prefix = "GRND_";
927 	int printed = 0, flags = arg->val;
928 
929 #define	P_FLAG(n) \
930 	if (flags & GRND_##n) { \
931 		printed += scnprintf(bf + printed, size - printed, "%s%s%s", printed ? "|" : "", show_prefix ? prefix : "", #n); \
932 		flags &= ~GRND_##n; \
933 	}
934 
935 	P_FLAG(RANDOM);
936 	P_FLAG(NONBLOCK);
937 #undef P_FLAG
938 
939 	if (flags)
940 		printed += scnprintf(bf + printed, size - printed, "%s%#x", printed ? "|" : "", flags);
941 
942 	return printed;
943 }
944 
945 #define SCA_GETRANDOM_FLAGS syscall_arg__scnprintf_getrandom_flags
946 
947 #ifdef HAVE_LIBBPF_SUPPORT
948 static void syscall_arg_fmt__cache_btf_enum(struct syscall_arg_fmt *arg_fmt, struct btf *btf, char *type)
949 {
950 	int id;
951 
952 	type = strstr(type, "enum ");
953 	if (type == NULL)
954 		return;
955 
956 	type += 5; // skip "enum " to get the enumeration name
957 
958 	id = btf__find_by_name(btf, type);
959 	if (id < 0)
960 		return;
961 
962 	arg_fmt->type = btf__type_by_id(btf, id);
963 }
964 
965 static bool syscall_arg__strtoul_btf_enum(char *bf, size_t size, struct syscall_arg *arg, u64 *val)
966 {
967 	const struct btf_type *bt = arg->fmt->type;
968 	struct btf *btf = arg->trace->btf;
969 	struct btf_enum *be = btf_enum(bt);
970 
971 	for (int i = 0; i < btf_vlen(bt); ++i, ++be) {
972 		const char *name = btf__name_by_offset(btf, be->name_off);
973 		int max_len = max(size, strlen(name));
974 
975 		if (strncmp(name, bf, max_len) == 0) {
976 			*val = be->val;
977 			return true;
978 		}
979 	}
980 
981 	return false;
982 }
983 
984 static bool syscall_arg__strtoul_btf_type(char *bf, size_t size, struct syscall_arg *arg, u64 *val)
985 {
986 	const struct btf_type *bt;
987 	char *type = arg->type_name;
988 	struct btf *btf;
989 
990 	trace__load_vmlinux_btf(arg->trace);
991 
992 	btf = arg->trace->btf;
993 	if (btf == NULL)
994 		return false;
995 
996 	if (arg->fmt->type == NULL) {
997 		// See if this is an enum
998 		syscall_arg_fmt__cache_btf_enum(arg->fmt, btf, type);
999 	}
1000 
1001 	// Now let's see if we have a BTF type resolved
1002 	bt = arg->fmt->type;
1003 	if (bt == NULL)
1004 		return false;
1005 
1006 	// If it is an enum:
1007 	if (btf_is_enum(arg->fmt->type))
1008 		return syscall_arg__strtoul_btf_enum(bf, size, arg, val);
1009 
1010 	return false;
1011 }
1012 
1013 static size_t btf_enum_scnprintf(const struct btf_type *type, struct btf *btf, char *bf, size_t size, int val)
1014 {
1015 	struct btf_enum *be = btf_enum(type);
1016 	const int nr_entries = btf_vlen(type);
1017 
1018 	for (int i = 0; i < nr_entries; ++i, ++be) {
1019 		if (be->val == val) {
1020 			return scnprintf(bf, size, "%s",
1021 					 btf__name_by_offset(btf, be->name_off));
1022 		}
1023 	}
1024 
1025 	return 0;
1026 }
1027 
1028 struct trace_btf_dump_snprintf_ctx {
1029 	char   *bf;
1030 	size_t printed, size;
1031 };
1032 
1033 static void trace__btf_dump_snprintf(void *vctx, const char *fmt, va_list args)
1034 {
1035 	struct trace_btf_dump_snprintf_ctx *ctx = vctx;
1036 
1037 	ctx->printed += vscnprintf(ctx->bf + ctx->printed, ctx->size - ctx->printed, fmt, args);
1038 }
1039 
1040 static size_t btf_struct_scnprintf(const struct btf_type *type, struct btf *btf, char *bf, size_t size, struct syscall_arg *arg)
1041 {
1042 	struct trace_btf_dump_snprintf_ctx ctx = {
1043 		.bf   = bf,
1044 		.size = size,
1045 	};
1046 	struct augmented_arg *augmented_arg = arg->augmented.args;
1047 	int type_id = arg->fmt->type_id, consumed;
1048 	struct btf_dump *btf_dump;
1049 
1050 	LIBBPF_OPTS(btf_dump_opts, dump_opts);
1051 	LIBBPF_OPTS(btf_dump_type_data_opts, dump_data_opts);
1052 
1053 	if (arg == NULL || arg->augmented.args == NULL)
1054 		return 0;
1055 
1056 	dump_data_opts.compact	  = true;
1057 	dump_data_opts.skip_names = !arg->trace->show_arg_names;
1058 
1059 	btf_dump = btf_dump__new(btf, trace__btf_dump_snprintf, &ctx, &dump_opts);
1060 	if (btf_dump == NULL)
1061 		return 0;
1062 
1063 	/* pretty print the struct data here */
1064 	if (btf_dump__dump_type_data(btf_dump, type_id, arg->augmented.args->value, type->size, &dump_data_opts) == 0)
1065 		return 0;
1066 
1067 	consumed = sizeof(*augmented_arg) + augmented_arg->size;
1068 	arg->augmented.args = ((void *)arg->augmented.args) + consumed;
1069 	arg->augmented.size -= consumed;
1070 
1071 	btf_dump__free(btf_dump);
1072 
1073 	return ctx.printed;
1074 }
1075 
1076 static size_t trace__btf_scnprintf(struct trace *trace, struct syscall_arg *arg, char *bf,
1077 				   size_t size, int val, char *type)
1078 {
1079 	struct syscall_arg_fmt *arg_fmt = arg->fmt;
1080 
1081 	if (trace->btf == NULL)
1082 		return 0;
1083 
1084 	if (arg_fmt->type == NULL) {
1085 		// Check if this is an enum and if we have the BTF type for it.
1086 		syscall_arg_fmt__cache_btf_enum(arg_fmt, trace->btf, type);
1087 	}
1088 
1089 	// Did we manage to find a BTF type for the syscall/tracepoint argument?
1090 	if (arg_fmt->type == NULL)
1091 		return 0;
1092 
1093 	if (btf_is_enum(arg_fmt->type))
1094 		return btf_enum_scnprintf(arg_fmt->type, trace->btf, bf, size, val);
1095 	else if (btf_is_struct(arg_fmt->type) || btf_is_union(arg_fmt->type))
1096 		return btf_struct_scnprintf(arg_fmt->type, trace->btf, bf, size, arg);
1097 
1098 	return 0;
1099 }
1100 
1101 #else // HAVE_LIBBPF_SUPPORT
1102 static size_t trace__btf_scnprintf(struct trace *trace __maybe_unused, struct syscall_arg *arg __maybe_unused,
1103 				   char *bf __maybe_unused, size_t size __maybe_unused, int val __maybe_unused,
1104 				   char *type __maybe_unused)
1105 {
1106 	return 0;
1107 }
1108 
1109 static bool syscall_arg__strtoul_btf_type(char *bf __maybe_unused, size_t size __maybe_unused,
1110 					  struct syscall_arg *arg __maybe_unused, u64 *val __maybe_unused)
1111 {
1112 	return false;
1113 }
1114 #endif // HAVE_LIBBPF_SUPPORT
1115 
1116 #define STUL_BTF_TYPE syscall_arg__strtoul_btf_type
1117 
1118 #define STRARRAY(name, array) \
1119 	  { .scnprintf	= SCA_STRARRAY, \
1120 	    .strtoul	= STUL_STRARRAY, \
1121 	    .parm	= &strarray__##array, \
1122 	    .show_zero	= true, }
1123 
1124 #define STRARRAY_FLAGS(name, array) \
1125 	  { .scnprintf	= SCA_STRARRAY_FLAGS, \
1126 	    .strtoul	= STUL_STRARRAY_FLAGS, \
1127 	    .parm	= &strarray__##array, \
1128 	    .show_zero	= true, }
1129 
1130 #include "trace/beauty/eventfd.c"
1131 #include "trace/beauty/futex_op.c"
1132 #include "trace/beauty/futex_val3.c"
1133 #include "trace/beauty/mmap.c"
1134 #include "trace/beauty/mode_t.c"
1135 #include "trace/beauty/msg_flags.c"
1136 #include "trace/beauty/open_flags.c"
1137 #include "trace/beauty/perf_event_open.c"
1138 #include "trace/beauty/pid.c"
1139 #include "trace/beauty/sched_policy.c"
1140 #include "trace/beauty/seccomp.c"
1141 #include "trace/beauty/signum.c"
1142 #include "trace/beauty/socket_type.c"
1143 #include "trace/beauty/waitid_options.c"
1144 
1145 static const struct syscall_fmt syscall_fmts[] = {
1146 	{ .name	    = "access",
1147 	  .arg = { [1] = { .scnprintf = SCA_ACCMODE,  /* mode */ }, }, },
1148 	{ .name	    = "arch_prctl",
1149 	  .arg = { [0] = { .scnprintf = SCA_X86_ARCH_PRCTL_CODE, /* code */ },
1150 		   [1] = { .scnprintf = SCA_PTR, /* arg2 */ }, }, },
1151 	{ .name	    = "bind",
1152 	  .arg = { [0] = { .scnprintf = SCA_INT, /* fd */ },
1153 		   [1] = SCA_SOCKADDR_FROM_USER(umyaddr),
1154 		   [2] = { .scnprintf = SCA_INT, /* addrlen */ }, }, },
1155 	{ .name	    = "bpf",
1156 	  .arg = { [0] = STRARRAY(cmd, bpf_cmd),
1157 		   [1] = { .from_user = true /* attr */, }, } },
1158 	{ .name	    = "brk",	    .hexret = true,
1159 	  .arg = { [0] = { .scnprintf = SCA_PTR, /* brk */ }, }, },
1160 	{ .name     = "clock_gettime",
1161 	  .arg = { [0] = STRARRAY(clk_id, clockid), }, },
1162 	{ .name	    = "clock_nanosleep",
1163 	  .arg = { [2] = SCA_TIMESPEC_FROM_USER(req), }, },
1164 	{ .name	    = "clone",	    .errpid = true, .nr_args = 5,
1165 	  .arg = { [0] = { .name = "flags",	    .scnprintf = SCA_CLONE_FLAGS, },
1166 		   [1] = { .name = "child_stack",   .scnprintf = SCA_HEX, },
1167 		   [2] = { .name = "parent_tidptr", .scnprintf = SCA_HEX, },
1168 		   [3] = { .name = "child_tidptr",  .scnprintf = SCA_HEX, },
1169 		   [4] = { .name = "tls",	    .scnprintf = SCA_HEX, }, }, },
1170 	{ .name	    = "close",
1171 	  .arg = { [0] = { .scnprintf = SCA_CLOSE_FD, /* fd */ }, }, },
1172 	{ .name	    = "connect",
1173 	  .arg = { [0] = { .scnprintf = SCA_INT, /* fd */ },
1174 		   [1] = SCA_SOCKADDR_FROM_USER(servaddr),
1175 		   [2] = { .scnprintf = SCA_INT, /* addrlen */ }, }, },
1176 	{ .name	    = "epoll_ctl",
1177 	  .arg = { [1] = STRARRAY(op, epoll_ctl_ops), }, },
1178 	{ .name	    = "eventfd2",
1179 	  .arg = { [1] = { .scnprintf = SCA_EFD_FLAGS, /* flags */ }, }, },
1180 	{ .name     = "faccessat",
1181 	  .arg = { [0] = { .scnprintf = SCA_FDAT,	  /* dirfd */ },
1182 		   [1] = SCA_FILENAME_FROM_USER(pathname),
1183 		   [2] = { .scnprintf = SCA_ACCMODE,	  /* mode */ }, }, },
1184 	{ .name     = "faccessat2",
1185 	  .arg = { [0] = { .scnprintf = SCA_FDAT,	  /* dirfd */ },
1186 		   [1] = SCA_FILENAME_FROM_USER(pathname),
1187 		   [2] = { .scnprintf = SCA_ACCMODE,	  /* mode */ },
1188 		   [3] = { .scnprintf = SCA_FACCESSAT2_FLAGS, /* flags */ }, }, },
1189 	{ .name	    = "fchmodat",
1190 	  .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
1191 	{ .name	    = "fchownat",
1192 	  .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
1193 	{ .name	    = "fcntl",
1194 	  .arg = { [1] = { .scnprintf = SCA_FCNTL_CMD,  /* cmd */
1195 			   .strtoul   = STUL_STRARRAYS,
1196 			   .parm      = &strarrays__fcntl_cmds_arrays,
1197 			   .show_zero = true, },
1198 		   [2] = { .scnprintf =  SCA_FCNTL_ARG, /* arg */ }, }, },
1199 	{ .name	    = "flock",
1200 	  .arg = { [1] = { .scnprintf = SCA_FLOCK, /* cmd */ }, }, },
1201 	{ .name     = "fsconfig",
1202 	  .arg = { [1] = STRARRAY(cmd, fsconfig_cmds), }, },
1203 	{ .name     = "fsmount",
1204 	  .arg = { [1] = STRARRAY_FLAGS(flags, fsmount_flags),
1205 		   [2] = { .scnprintf = SCA_FSMOUNT_ATTR_FLAGS, /* attr_flags */ }, }, },
1206 	{ .name     = "fspick",
1207 	  .arg = { [0] = { .scnprintf = SCA_FDAT,	  /* dfd */ },
1208 		   [1] = SCA_FILENAME_FROM_USER(path),
1209 		   [2] = { .scnprintf = SCA_FSPICK_FLAGS, /* flags */ }, }, },
1210 	{ .name	    = "fstat", .alias = "newfstat", },
1211 	{ .name	    = "futex",
1212 	  .arg = { [1] = { .scnprintf = SCA_FUTEX_OP, /* op */ },
1213 		   [5] = { .scnprintf = SCA_FUTEX_VAL3, /* val3 */ }, }, },
1214 	{ .name	    = "futimesat",
1215 	  .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
1216 	{ .name	    = "getitimer",
1217 	  .arg = { [0] = STRARRAY(which, itimers), }, },
1218 	{ .name	    = "getpid",	    .errpid = true, },
1219 	{ .name	    = "getpgid",    .errpid = true, },
1220 	{ .name	    = "getppid",    .errpid = true, },
1221 	{ .name	    = "getrandom",
1222 	  .arg = { [2] = { .scnprintf = SCA_GETRANDOM_FLAGS, /* flags */ }, }, },
1223 	{ .name	    = "getrlimit",
1224 	  .arg = { [0] = STRARRAY(resource, rlimit_resources), }, },
1225 	{ .name	    = "getsockopt",
1226 	  .arg = { [1] = STRARRAY(level, socket_level), }, },
1227 	{ .name	    = "gettid",	    .errpid = true, },
1228 	{ .name	    = "ioctl",
1229 	  .arg = {
1230 #if defined(__i386__) || defined(__x86_64__)
1231 /*
1232  * FIXME: Make this available to all arches.
1233  */
1234 		   [1] = { .scnprintf = SCA_IOCTL_CMD, /* cmd */ },
1235 		   [2] = { .scnprintf = SCA_HEX, /* arg */ }, }, },
1236 #else
1237 		   [2] = { .scnprintf = SCA_HEX, /* arg */ }, }, },
1238 #endif
1239 	{ .name	    = "kcmp",	    .nr_args = 5,
1240 	  .arg = { [0] = { .name = "pid1",	.scnprintf = SCA_PID, },
1241 		   [1] = { .name = "pid2",	.scnprintf = SCA_PID, },
1242 		   [2] = { .name = "type",	.scnprintf = SCA_KCMP_TYPE, },
1243 		   [3] = { .name = "idx1",	.scnprintf = SCA_KCMP_IDX, },
1244 		   [4] = { .name = "idx2",	.scnprintf = SCA_KCMP_IDX, }, }, },
1245 	{ .name	    = "keyctl",
1246 	  .arg = { [0] = STRARRAY(option, keyctl_options), }, },
1247 	{ .name	    = "kill",
1248 	  .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
1249 	{ .name	    = "linkat",
1250 	  .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
1251 	{ .name	    = "lseek",
1252 	  .arg = { [2] = STRARRAY(whence, whences), }, },
1253 	{ .name	    = "lstat", .alias = "newlstat", },
1254 	{ .name     = "madvise",
1255 	  .arg = { [0] = { .scnprintf = SCA_HEX,      /* start */ },
1256 		   [2] = { .scnprintf = SCA_MADV_BHV, /* behavior */ }, }, },
1257 	{ .name	    = "mkdirat",
1258 	  .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
1259 	{ .name	    = "mknodat",
1260 	  .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
1261 	{ .name	    = "mmap",	    .hexret = true,
1262 /* The standard mmap maps to old_mmap on s390x */
1263 #if defined(__s390x__)
1264 	.alias = "old_mmap",
1265 #endif
1266 	  .arg = { [2] = { .scnprintf = SCA_MMAP_PROT, .show_zero = true, /* prot */ },
1267 		   [3] = { .scnprintf = SCA_MMAP_FLAGS,	/* flags */
1268 			   .strtoul   = STUL_STRARRAY_FLAGS,
1269 			   .parm      = &strarray__mmap_flags, },
1270 		   [5] = { .scnprintf = SCA_HEX,	/* offset */ }, }, },
1271 	{ .name	    = "mount",
1272 	  .arg = { [0] = SCA_FILENAME_FROM_USER(devname),
1273 		   [3] = { .scnprintf = SCA_MOUNT_FLAGS, /* flags */
1274 			   .mask_val  = SCAMV_MOUNT_FLAGS, /* flags */ }, }, },
1275 	{ .name	    = "move_mount",
1276 	  .arg = { [0] = { .scnprintf = SCA_FDAT,	/* from_dfd */ },
1277 		   [1] = SCA_FILENAME_FROM_USER(pathname),
1278 		   [2] = { .scnprintf = SCA_FDAT,	/* to_dfd */ },
1279 		   [3] = SCA_FILENAME_FROM_USER(pathname),
1280 		   [4] = { .scnprintf = SCA_MOVE_MOUNT_FLAGS, /* flags */ }, }, },
1281 	{ .name	    = "mprotect",
1282 	  .arg = { [0] = { .scnprintf = SCA_HEX,	/* start */ },
1283 		   [2] = { .scnprintf = SCA_MMAP_PROT, .show_zero = true, /* prot */ }, }, },
1284 	{ .name	    = "mq_unlink",
1285 	  .arg = { [0] = SCA_FILENAME_FROM_USER(u_name), }, },
1286 	{ .name	    = "mremap",	    .hexret = true,
1287 	  .arg = { [3] = { .scnprintf = SCA_MREMAP_FLAGS, /* flags */ }, }, },
1288 	{ .name	    = "name_to_handle_at",
1289 	  .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
1290 	{ .name	    = "nanosleep",
1291 	  .arg = { [0] = SCA_TIMESPEC_FROM_USER(req), }, },
1292 	{ .name	    = "newfstatat", .alias = "fstatat",
1293 	  .arg = { [0] = { .scnprintf = SCA_FDAT,	  /* dirfd */ },
1294 		   [1] = SCA_FILENAME_FROM_USER(pathname),
1295 		   [3] = { .scnprintf = SCA_FS_AT_FLAGS, /* flags */ }, }, },
1296 	{ .name	    = "open",
1297 	  .arg = { [1] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
1298 	{ .name	    = "open_by_handle_at",
1299 	  .arg = { [0] = { .scnprintf = SCA_FDAT,	/* dfd */ },
1300 		   [2] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
1301 	{ .name	    = "openat",
1302 	  .arg = { [0] = { .scnprintf = SCA_FDAT,	/* dfd */ },
1303 		   [2] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
1304 	{ .name	    = "perf_event_open",
1305 	  .arg = { [0] = SCA_PERF_ATTR_FROM_USER(attr),
1306 		   [2] = { .scnprintf = SCA_INT,	/* cpu */ },
1307 		   [3] = { .scnprintf = SCA_FD,		/* group_fd */ },
1308 		   [4] = { .scnprintf = SCA_PERF_FLAGS, /* flags */ }, }, },
1309 	{ .name	    = "pipe2",
1310 	  .arg = { [1] = { .scnprintf = SCA_PIPE_FLAGS, /* flags */ }, }, },
1311 	{ .name	    = "pkey_alloc",
1312 	  .arg = { [1] = { .scnprintf = SCA_PKEY_ALLOC_ACCESS_RIGHTS,	/* access_rights */ }, }, },
1313 	{ .name	    = "pkey_free",
1314 	  .arg = { [0] = { .scnprintf = SCA_INT,	/* key */ }, }, },
1315 	{ .name	    = "pkey_mprotect",
1316 	  .arg = { [0] = { .scnprintf = SCA_HEX,	/* start */ },
1317 		   [2] = { .scnprintf = SCA_MMAP_PROT, .show_zero = true, /* prot */ },
1318 		   [3] = { .scnprintf = SCA_INT,	/* pkey */ }, }, },
1319 	{ .name	    = "poll", .timeout = true, },
1320 	{ .name	    = "ppoll", .timeout = true, },
1321 	{ .name	    = "prctl",
1322 	  .arg = { [0] = { .scnprintf = SCA_PRCTL_OPTION, /* option */
1323 			   .strtoul   = STUL_STRARRAY,
1324 			   .parm      = &strarray__prctl_options, },
1325 		   [1] = { .scnprintf = SCA_PRCTL_ARG2, /* arg2 */ },
1326 		   [2] = { .scnprintf = SCA_PRCTL_ARG3, /* arg3 */ }, }, },
1327 	{ .name	    = "pread", .alias = "pread64", },
1328 	{ .name	    = "preadv", .alias = "pread", },
1329 	{ .name	    = "prlimit64",
1330 	  .arg = { [1] = STRARRAY(resource, rlimit_resources),
1331 		   [2] = { .from_user = true /* new_rlim */, }, }, },
1332 	{ .name	    = "pwrite", .alias = "pwrite64", },
1333 	{ .name	    = "readlinkat",
1334 	  .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
1335 	{ .name	    = "recvfrom",
1336 	  .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
1337 	{ .name	    = "recvmmsg",
1338 	  .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
1339 	{ .name	    = "recvmsg",
1340 	  .arg = { [2] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
1341 	{ .name	    = "renameat",
1342 	  .arg = { [0] = { .scnprintf = SCA_FDAT, /* olddirfd */ },
1343 		   [2] = { .scnprintf = SCA_FDAT, /* newdirfd */ }, }, },
1344 	{ .name	    = "renameat2",
1345 	  .arg = { [0] = { .scnprintf = SCA_FDAT, /* olddirfd */ },
1346 		   [2] = { .scnprintf = SCA_FDAT, /* newdirfd */ },
1347 		   [4] = { .scnprintf = SCA_RENAMEAT2_FLAGS, /* flags */ }, }, },
1348 	{ .name	    = "rseq",
1349 	  .arg = { [0] = { .from_user = true /* rseq */, }, }, },
1350 	{ .name	    = "rt_sigaction",
1351 	  .arg = { [0] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
1352 	{ .name	    = "rt_sigprocmask",
1353 	  .arg = { [0] = STRARRAY(how, sighow), }, },
1354 	{ .name	    = "rt_sigqueueinfo",
1355 	  .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
1356 	{ .name	    = "rt_tgsigqueueinfo",
1357 	  .arg = { [2] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
1358 	{ .name	    = "sched_setscheduler",
1359 	  .arg = { [1] = { .scnprintf = SCA_SCHED_POLICY, /* policy */ }, }, },
1360 	{ .name	    = "seccomp",
1361 	  .arg = { [0] = { .scnprintf = SCA_SECCOMP_OP,	   /* op */ },
1362 		   [1] = { .scnprintf = SCA_SECCOMP_FLAGS, /* flags */ }, }, },
1363 	{ .name	    = "select", .timeout = true, },
1364 	{ .name	    = "sendfile", .alias = "sendfile64", },
1365 	{ .name	    = "sendmmsg",
1366 	  .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
1367 	{ .name	    = "sendmsg",
1368 	  .arg = { [2] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
1369 	{ .name	    = "sendto",
1370 	  .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ },
1371 		   [4] = SCA_SOCKADDR_FROM_USER(addr), }, },
1372 	{ .name	    = "set_robust_list",
1373 	  .arg = { [0] = { .from_user = true /* head */, }, }, },
1374 	{ .name	    = "set_tid_address", .errpid = true, },
1375 	{ .name	    = "setitimer",
1376 	  .arg = { [0] = STRARRAY(which, itimers), }, },
1377 	{ .name	    = "setrlimit",
1378 	  .arg = { [0] = STRARRAY(resource, rlimit_resources),
1379 		   [1] = { .from_user = true /* rlim */, }, }, },
1380 	{ .name	    = "setsockopt",
1381 	  .arg = { [1] = STRARRAY(level, socket_level), }, },
1382 	{ .name	    = "socket",
1383 	  .arg = { [0] = STRARRAY(family, socket_families),
1384 		   [1] = { .scnprintf = SCA_SK_TYPE, /* type */ },
1385 		   [2] = { .scnprintf = SCA_SK_PROTO, /* protocol */ }, }, },
1386 	{ .name	    = "socketpair",
1387 	  .arg = { [0] = STRARRAY(family, socket_families),
1388 		   [1] = { .scnprintf = SCA_SK_TYPE, /* type */ },
1389 		   [2] = { .scnprintf = SCA_SK_PROTO, /* protocol */ }, }, },
1390 	{ .name	    = "stat", .alias = "newstat", },
1391 	{ .name	    = "statx",
1392 	  .arg = { [0] = { .scnprintf = SCA_FDAT,	 /* fdat */ },
1393 		   [2] = { .scnprintf = SCA_FS_AT_FLAGS, /* flags */ } ,
1394 		   [3] = { .scnprintf = SCA_STATX_MASK,	 /* mask */ }, }, },
1395 	{ .name	    = "swapoff",
1396 	  .arg = { [0] = SCA_FILENAME_FROM_USER(specialfile), }, },
1397 	{ .name	    = "swapon",
1398 	  .arg = { [0] = SCA_FILENAME_FROM_USER(specialfile), }, },
1399 	{ .name	    = "symlinkat",
1400 	  .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
1401 	{ .name	    = "sync_file_range",
1402 	  .arg = { [3] = { .scnprintf = SCA_SYNC_FILE_RANGE_FLAGS, /* flags */ }, }, },
1403 	{ .name	    = "tgkill",
1404 	  .arg = { [2] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
1405 	{ .name	    = "tkill",
1406 	  .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
1407 	{ .name     = "umount2", .alias = "umount",
1408 	  .arg = { [0] = SCA_FILENAME_FROM_USER(name), }, },
1409 	{ .name	    = "uname", .alias = "newuname", },
1410 	{ .name	    = "unlinkat",
1411 	  .arg = { [0] = { .scnprintf = SCA_FDAT,	  /* dfd */ },
1412 		   [1] = SCA_FILENAME_FROM_USER(pathname),
1413 		   [2] = { .scnprintf = SCA_FS_AT_FLAGS,  /* flags */ }, }, },
1414 	{ .name	    = "utimensat",
1415 	  .arg = { [0] = { .scnprintf = SCA_FDAT, /* dirfd */ }, }, },
1416 	{ .name	    = "wait4",	    .errpid = true,
1417 	  .arg = { [2] = { .scnprintf = SCA_WAITID_OPTIONS, /* options */ }, }, },
1418 	{ .name	    = "waitid",	    .errpid = true,
1419 	  .arg = { [3] = { .scnprintf = SCA_WAITID_OPTIONS, /* options */ }, }, },
1420 	{ .name	    = "write",
1421 	  .arg = { [1] = { .scnprintf = SCA_BUF /* buf */, .from_user = true, }, }, },
1422 };
1423 
1424 static int syscall_fmt__cmp(const void *name, const void *fmtp)
1425 {
1426 	const struct syscall_fmt *fmt = fmtp;
1427 	return strcmp(name, fmt->name);
1428 }
1429 
1430 static const struct syscall_fmt *__syscall_fmt__find(const struct syscall_fmt *fmts,
1431 						     const int nmemb,
1432 						     const char *name)
1433 {
1434 	return bsearch(name, fmts, nmemb, sizeof(struct syscall_fmt), syscall_fmt__cmp);
1435 }
1436 
1437 static const struct syscall_fmt *syscall_fmt__find(const char *name)
1438 {
1439 	const int nmemb = ARRAY_SIZE(syscall_fmts);
1440 	return __syscall_fmt__find(syscall_fmts, nmemb, name);
1441 }
1442 
1443 static const struct syscall_fmt *__syscall_fmt__find_by_alias(const struct syscall_fmt *fmts,
1444 							      const int nmemb, const char *alias)
1445 {
1446 	int i;
1447 
1448 	for (i = 0; i < nmemb; ++i) {
1449 		if (fmts[i].alias && strcmp(fmts[i].alias, alias) == 0)
1450 			return &fmts[i];
1451 	}
1452 
1453 	return NULL;
1454 }
1455 
1456 static const struct syscall_fmt *syscall_fmt__find_by_alias(const char *alias)
1457 {
1458 	const int nmemb = ARRAY_SIZE(syscall_fmts);
1459 	return __syscall_fmt__find_by_alias(syscall_fmts, nmemb, alias);
1460 }
1461 
1462 /**
1463  * struct syscall
1464  */
1465 struct syscall {
1466 	/** @e_machine: The ELF machine associated with the entry. */
1467 	int e_machine;
1468 	/** @id: id value from the tracepoint, the system call number. */
1469 	int id;
1470 	struct tep_event    *tp_format;
1471 	int		    nr_args;
1472 	/**
1473 	 * @args_size: sum of the sizes of the syscall arguments, anything
1474 	 * after that is augmented stuff: pathname for openat, etc.
1475 	 */
1476 
1477 	int		    args_size;
1478 	struct {
1479 		struct bpf_program *sys_enter,
1480 				   *sys_exit;
1481 	}		    bpf_prog;
1482 	/** @is_exit: is this "exit" or "exit_group"? */
1483 	bool		    is_exit;
1484 	/**
1485 	 * @is_open: is this "open" or "openat"? To associate the fd returned in
1486 	 * sys_exit with the pathname in sys_enter.
1487 	 */
1488 	bool		    is_open;
1489 	/**
1490 	 * @nonexistent: Name lookup failed. Just a hole in the syscall table,
1491 	 * syscall id not allocated.
1492 	 */
1493 	bool		    nonexistent;
1494 	bool		    use_btf;
1495 	struct tep_format_field *args;
1496 	const char	    *name;
1497 	const struct syscall_fmt  *fmt;
1498 	struct syscall_arg_fmt *arg_fmt;
1499 };
1500 
1501 /*
1502  * We need to have this 'calculated' boolean because in some cases we really
1503  * don't know what is the duration of a syscall, for instance, when we start
1504  * a session and some threads are waiting for a syscall to finish, say 'poll',
1505  * in which case all we can do is to print "( ? ) for duration and for the
1506  * start timestamp.
1507  */
1508 static size_t fprintf_duration(unsigned long t, bool calculated, FILE *fp)
1509 {
1510 	double duration = (double)t / NSEC_PER_MSEC;
1511 	size_t printed = fprintf(fp, "(");
1512 
1513 	if (!calculated)
1514 		printed += fprintf(fp, "         ");
1515 	else if (duration >= 1.0)
1516 		printed += color_fprintf(fp, PERF_COLOR_RED, "%6.3f ms", duration);
1517 	else if (duration >= 0.01)
1518 		printed += color_fprintf(fp, PERF_COLOR_YELLOW, "%6.3f ms", duration);
1519 	else
1520 		printed += color_fprintf(fp, PERF_COLOR_NORMAL, "%6.3f ms", duration);
1521 	return printed + fprintf(fp, "): ");
1522 }
1523 
1524 /**
1525  * filename.ptr: The filename char pointer that will be vfs_getname'd
1526  * filename.entry_str_pos: Where to insert the string translated from
1527  *                         filename.ptr by the vfs_getname tracepoint/kprobe.
1528  * ret_scnprintf: syscall args may set this to a different syscall return
1529  *                formatter, for instance, fcntl may return fds, file flags, etc.
1530  */
1531 struct thread_trace {
1532 	u64		  entry_time;
1533 	bool		  entry_pending;
1534 	unsigned long	  nr_events;
1535 	unsigned long	  pfmaj, pfmin;
1536 	char		  *entry_str;
1537 	double		  runtime_ms;
1538 	size_t		  (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
1539         struct {
1540 		unsigned long ptr;
1541 		short int     entry_str_pos;
1542 		bool	      pending_open;
1543 		unsigned int  namelen;
1544 		char	      *name;
1545 	} filename;
1546 	struct {
1547 		int	      max;
1548 		struct file   *table;
1549 	} files;
1550 
1551 	struct hashmap *syscall_stats;
1552 };
1553 
1554 static size_t syscall_id_hash(long key, void *ctx __maybe_unused)
1555 {
1556 	return key;
1557 }
1558 
1559 static bool syscall_id_equal(long key1, long key2, void *ctx __maybe_unused)
1560 {
1561 	return key1 == key2;
1562 }
1563 
1564 static struct hashmap *alloc_syscall_stats(void)
1565 {
1566 	return hashmap__new(syscall_id_hash, syscall_id_equal, NULL);
1567 }
1568 
1569 static void delete_syscall_stats(struct hashmap *syscall_stats)
1570 {
1571 	struct hashmap_entry *pos;
1572 	size_t bkt;
1573 
1574 	if (syscall_stats == NULL)
1575 		return;
1576 
1577 	hashmap__for_each_entry(syscall_stats, pos, bkt)
1578 		zfree(&pos->pvalue);
1579 	hashmap__free(syscall_stats);
1580 }
1581 
1582 static struct thread_trace *thread_trace__new(struct trace *trace)
1583 {
1584 	struct thread_trace *ttrace =  zalloc(sizeof(struct thread_trace));
1585 
1586 	if (ttrace) {
1587 		ttrace->files.max = -1;
1588 		if (trace->summary) {
1589 			ttrace->syscall_stats = alloc_syscall_stats();
1590 			if (IS_ERR(ttrace->syscall_stats))
1591 				zfree(&ttrace);
1592 		}
1593 	}
1594 
1595 	return ttrace;
1596 }
1597 
1598 static void thread_trace__free_files(struct thread_trace *ttrace);
1599 
1600 static void thread_trace__delete(void *pttrace)
1601 {
1602 	struct thread_trace *ttrace = pttrace;
1603 
1604 	if (!ttrace)
1605 		return;
1606 
1607 	delete_syscall_stats(ttrace->syscall_stats);
1608 	ttrace->syscall_stats = NULL;
1609 	thread_trace__free_files(ttrace);
1610 	zfree(&ttrace->entry_str);
1611 	free(ttrace);
1612 }
1613 
1614 static struct thread_trace *thread__trace(struct thread *thread, struct trace *trace)
1615 {
1616 	struct thread_trace *ttrace;
1617 
1618 	if (thread == NULL)
1619 		goto fail;
1620 
1621 	if (thread__priv(thread) == NULL)
1622 		thread__set_priv(thread, thread_trace__new(trace));
1623 
1624 	if (thread__priv(thread) == NULL)
1625 		goto fail;
1626 
1627 	ttrace = thread__priv(thread);
1628 	++ttrace->nr_events;
1629 
1630 	return ttrace;
1631 fail:
1632 	color_fprintf(trace->output, PERF_COLOR_RED,
1633 		      "WARNING: not enough memory, dropping samples!\n");
1634 	return NULL;
1635 }
1636 
1637 
1638 void syscall_arg__set_ret_scnprintf(struct syscall_arg *arg,
1639 				    size_t (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg))
1640 {
1641 	struct thread_trace *ttrace = thread__priv(arg->thread);
1642 
1643 	ttrace->ret_scnprintf = ret_scnprintf;
1644 }
1645 
1646 #define TRACE_PFMAJ		(1 << 0)
1647 #define TRACE_PFMIN		(1 << 1)
1648 
1649 static const size_t trace__entry_str_size = 2048;
1650 
1651 static void thread_trace__free_files(struct thread_trace *ttrace)
1652 {
1653 	for (int i = 0; i <= ttrace->files.max; ++i) {
1654 		struct file *file = ttrace->files.table + i;
1655 		zfree(&file->pathname);
1656 	}
1657 
1658 	zfree(&ttrace->files.table);
1659 	ttrace->files.max  = -1;
1660 }
1661 
1662 static struct file *thread_trace__files_entry(struct thread_trace *ttrace, int fd)
1663 {
1664 	if (fd < 0)
1665 		return NULL;
1666 
1667 	if (fd > ttrace->files.max) {
1668 		struct file *nfiles = realloc(ttrace->files.table, (fd + 1) * sizeof(struct file));
1669 
1670 		if (nfiles == NULL)
1671 			return NULL;
1672 
1673 		if (ttrace->files.max != -1) {
1674 			memset(nfiles + ttrace->files.max + 1, 0,
1675 			       (fd - ttrace->files.max) * sizeof(struct file));
1676 		} else {
1677 			memset(nfiles, 0, (fd + 1) * sizeof(struct file));
1678 		}
1679 
1680 		ttrace->files.table = nfiles;
1681 		ttrace->files.max   = fd;
1682 	}
1683 
1684 	return ttrace->files.table + fd;
1685 }
1686 
1687 struct file *thread__files_entry(struct thread *thread, int fd)
1688 {
1689 	return thread_trace__files_entry(thread__priv(thread), fd);
1690 }
1691 
1692 static int trace__set_fd_pathname(struct thread *thread, int fd, const char *pathname)
1693 {
1694 	struct thread_trace *ttrace = thread__priv(thread);
1695 	struct file *file = thread_trace__files_entry(ttrace, fd);
1696 
1697 	if (file != NULL) {
1698 		struct stat st;
1699 
1700 		if (stat(pathname, &st) == 0)
1701 			file->dev_maj = major(st.st_rdev);
1702 		file->pathname = strdup(pathname);
1703 		if (file->pathname)
1704 			return 0;
1705 	}
1706 
1707 	return -1;
1708 }
1709 
1710 static int thread__read_fd_path(struct thread *thread, int fd)
1711 {
1712 	char linkname[PATH_MAX], pathname[PATH_MAX];
1713 	struct stat st;
1714 	int ret;
1715 
1716 	if (thread__pid(thread) == thread__tid(thread)) {
1717 		scnprintf(linkname, sizeof(linkname),
1718 			  "/proc/%d/fd/%d", thread__pid(thread), fd);
1719 	} else {
1720 		scnprintf(linkname, sizeof(linkname),
1721 			  "/proc/%d/task/%d/fd/%d",
1722 			  thread__pid(thread), thread__tid(thread), fd);
1723 	}
1724 
1725 	if (lstat(linkname, &st) < 0 || st.st_size + 1 > (off_t)sizeof(pathname))
1726 		return -1;
1727 
1728 	ret = readlink(linkname, pathname, sizeof(pathname));
1729 
1730 	if (ret < 0 || ret > st.st_size)
1731 		return -1;
1732 
1733 	pathname[ret] = '\0';
1734 	return trace__set_fd_pathname(thread, fd, pathname);
1735 }
1736 
1737 static const char *thread__fd_path(struct thread *thread, int fd,
1738 				   struct trace *trace)
1739 {
1740 	struct thread_trace *ttrace = thread__priv(thread);
1741 
1742 	if (ttrace == NULL || trace->fd_path_disabled)
1743 		return NULL;
1744 
1745 	if (fd < 0)
1746 		return NULL;
1747 
1748 	if ((fd > ttrace->files.max || ttrace->files.table[fd].pathname == NULL)) {
1749 		if (!trace->live)
1750 			return NULL;
1751 		++trace->stats.proc_getname;
1752 		if (thread__read_fd_path(thread, fd))
1753 			return NULL;
1754 	}
1755 
1756 	return ttrace->files.table[fd].pathname;
1757 }
1758 
1759 size_t syscall_arg__scnprintf_fd(char *bf, size_t size, struct syscall_arg *arg)
1760 {
1761 	int fd = arg->val;
1762 	size_t printed = scnprintf(bf, size, "%d", fd);
1763 	const char *path = thread__fd_path(arg->thread, fd, arg->trace);
1764 
1765 	if (path)
1766 		printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1767 
1768 	return printed;
1769 }
1770 
1771 size_t pid__scnprintf_fd(struct trace *trace, pid_t pid, int fd, char *bf, size_t size)
1772 {
1773         size_t printed = scnprintf(bf, size, "%d", fd);
1774 	struct thread *thread = machine__find_thread(trace->host, pid, pid);
1775 
1776 	if (thread) {
1777 		const char *path = thread__fd_path(thread, fd, trace);
1778 
1779 		if (path)
1780 			printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1781 
1782 		thread__put(thread);
1783 	}
1784 
1785         return printed;
1786 }
1787 
1788 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
1789 					      struct syscall_arg *arg)
1790 {
1791 	int fd = arg->val;
1792 	size_t printed = syscall_arg__scnprintf_fd(bf, size, arg);
1793 	struct thread_trace *ttrace = thread__priv(arg->thread);
1794 
1795 	if (ttrace && fd >= 0 && fd <= ttrace->files.max)
1796 		zfree(&ttrace->files.table[fd].pathname);
1797 
1798 	return printed;
1799 }
1800 
1801 static void thread__set_filename_pos(struct thread *thread, const char *bf,
1802 				     unsigned long ptr)
1803 {
1804 	struct thread_trace *ttrace = thread__priv(thread);
1805 
1806 	ttrace->filename.ptr = ptr;
1807 	ttrace->filename.entry_str_pos = bf - ttrace->entry_str;
1808 }
1809 
1810 static size_t syscall_arg__scnprintf_augmented_string(struct syscall_arg *arg, char *bf, size_t size)
1811 {
1812 	struct augmented_arg *augmented_arg = arg->augmented.args;
1813 	size_t printed = scnprintf(bf, size, "\"%.*s\"", augmented_arg->size, augmented_arg->value);
1814 	/*
1815 	 * So that the next arg with a payload can consume its augmented arg, i.e. for rename* syscalls
1816 	 * we would have two strings, each prefixed by its size.
1817 	 */
1818 	int consumed = sizeof(*augmented_arg) + augmented_arg->size;
1819 
1820 	arg->augmented.args = ((void *)arg->augmented.args) + consumed;
1821 	arg->augmented.size -= consumed;
1822 
1823 	return printed;
1824 }
1825 
1826 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
1827 					      struct syscall_arg *arg)
1828 {
1829 	unsigned long ptr = arg->val;
1830 
1831 	if (arg->augmented.args)
1832 		return syscall_arg__scnprintf_augmented_string(arg, bf, size);
1833 
1834 	if (!arg->trace->vfs_getname)
1835 		return scnprintf(bf, size, "%#x", ptr);
1836 
1837 	thread__set_filename_pos(arg->thread, bf, ptr);
1838 	return 0;
1839 }
1840 
1841 #define MAX_CONTROL_CHAR 31
1842 #define MAX_ASCII 127
1843 
1844 static size_t syscall_arg__scnprintf_buf(char *bf, size_t size, struct syscall_arg *arg)
1845 {
1846 	struct augmented_arg *augmented_arg = arg->augmented.args;
1847 	unsigned char *orig = (unsigned char *)augmented_arg->value;
1848 	size_t printed = 0;
1849 	int consumed;
1850 
1851 	if (augmented_arg == NULL)
1852 		return 0;
1853 
1854 	for (int j = 0; j < augmented_arg->size; ++j) {
1855 		bool control_char = orig[j] <= MAX_CONTROL_CHAR || orig[j] >= MAX_ASCII;
1856 		/* print control characters (0~31 and 127), and non-ascii characters in \(digits) */
1857 		printed += scnprintf(bf + printed, size - printed, control_char ? "\\%d" : "%c", (int)orig[j]);
1858 	}
1859 
1860 	consumed = sizeof(*augmented_arg) + augmented_arg->size;
1861 	arg->augmented.args = ((void *)arg->augmented.args) + consumed;
1862 	arg->augmented.size -= consumed;
1863 
1864 	return printed;
1865 }
1866 
1867 static bool trace__filter_duration(struct trace *trace, double t)
1868 {
1869 	return t < (trace->duration_filter * NSEC_PER_MSEC);
1870 }
1871 
1872 static size_t __trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1873 {
1874 	double ts = (double)(tstamp - trace->base_time) / NSEC_PER_MSEC;
1875 
1876 	return fprintf(fp, "%10.3f ", ts);
1877 }
1878 
1879 /*
1880  * We're handling tstamp=0 as an undefined tstamp, i.e. like when we are
1881  * using ttrace->entry_time for a thread that receives a sys_exit without
1882  * first having received a sys_enter ("poll" issued before tracing session
1883  * starts, lost sys_enter exit due to ring buffer overflow).
1884  */
1885 static size_t trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1886 {
1887 	if (tstamp > 0)
1888 		return __trace__fprintf_tstamp(trace, tstamp, fp);
1889 
1890 	return fprintf(fp, "         ? ");
1891 }
1892 
1893 static pid_t workload_pid = -1;
1894 static volatile sig_atomic_t done = false;
1895 static volatile sig_atomic_t interrupted = false;
1896 
1897 static void sighandler_interrupt(int sig __maybe_unused)
1898 {
1899 	done = interrupted = true;
1900 }
1901 
1902 static void sighandler_chld(int sig __maybe_unused, siginfo_t *info,
1903 			    void *context __maybe_unused)
1904 {
1905 	if (info->si_pid == workload_pid)
1906 		done = true;
1907 }
1908 
1909 static size_t trace__fprintf_comm_tid(struct trace *trace, struct thread *thread, FILE *fp)
1910 {
1911 	size_t printed = 0;
1912 
1913 	if (trace->multiple_threads) {
1914 		if (trace->show_comm)
1915 			printed += fprintf(fp, "%.14s/", thread__comm_str(thread));
1916 		printed += fprintf(fp, "%d ", thread__tid(thread));
1917 	}
1918 
1919 	return printed;
1920 }
1921 
1922 static size_t trace__fprintf_entry_head(struct trace *trace, struct thread *thread,
1923 					u64 duration, bool duration_calculated, u64 tstamp, FILE *fp)
1924 {
1925 	size_t printed = 0;
1926 
1927 	if (trace->show_tstamp)
1928 		printed = trace__fprintf_tstamp(trace, tstamp, fp);
1929 	if (trace->show_duration)
1930 		printed += fprintf_duration(duration, duration_calculated, fp);
1931 	return printed + trace__fprintf_comm_tid(trace, thread, fp);
1932 }
1933 
1934 static int trace__process_event(struct trace *trace, struct machine *machine,
1935 				union perf_event *event, struct perf_sample *sample)
1936 {
1937 	int ret = 0;
1938 
1939 	switch (event->header.type) {
1940 	case PERF_RECORD_LOST:
1941 		color_fprintf(trace->output, PERF_COLOR_RED,
1942 			      "LOST %" PRIu64 " events!\n", (u64)event->lost.lost);
1943 		ret = machine__process_lost_event(machine, event, sample);
1944 		break;
1945 	default:
1946 		ret = machine__process_event(machine, event, sample);
1947 		break;
1948 	}
1949 
1950 	return ret;
1951 }
1952 
1953 static int trace__tool_process(const struct perf_tool *tool,
1954 			       union perf_event *event,
1955 			       struct perf_sample *sample,
1956 			       struct machine *machine)
1957 {
1958 	struct trace *trace = container_of(tool, struct trace, tool);
1959 	return trace__process_event(trace, machine, event, sample);
1960 }
1961 
1962 static char *trace__machine__resolve_kernel_addr(void *vmachine, unsigned long long *addrp, char **modp)
1963 {
1964 	struct machine *machine = vmachine;
1965 
1966 	if (machine->kptr_restrict_warned)
1967 		return NULL;
1968 
1969 	if (symbol_conf.kptr_restrict) {
1970 		pr_warning("Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
1971 			   "Check /proc/sys/kernel/kptr_restrict and /proc/sys/kernel/perf_event_paranoid.\n\n"
1972 			   "Kernel samples will not be resolved.\n");
1973 		machine->kptr_restrict_warned = true;
1974 		return NULL;
1975 	}
1976 
1977 	return machine__resolve_kernel_addr(vmachine, addrp, modp);
1978 }
1979 
1980 static int trace__symbols_init(struct trace *trace, struct evlist *evlist)
1981 {
1982 	int err = symbol__init(NULL);
1983 
1984 	if (err)
1985 		return err;
1986 
1987 	trace->host = machine__new_host();
1988 	if (trace->host == NULL)
1989 		return -ENOMEM;
1990 
1991 	thread__set_priv_destructor(thread_trace__delete);
1992 
1993 	err = trace_event__register_resolver(trace->host, trace__machine__resolve_kernel_addr);
1994 	if (err < 0)
1995 		goto out;
1996 
1997 	err = __machine__synthesize_threads(trace->host, &trace->tool, &trace->opts.target,
1998 					    evlist->core.threads, trace__tool_process,
1999 					    true, false, 1);
2000 out:
2001 	if (err)
2002 		symbol__exit();
2003 
2004 	return err;
2005 }
2006 
2007 static void trace__symbols__exit(struct trace *trace)
2008 {
2009 	machine__exit(trace->host);
2010 	trace->host = NULL;
2011 
2012 	symbol__exit();
2013 }
2014 
2015 static int syscall__alloc_arg_fmts(struct syscall *sc, int nr_args)
2016 {
2017 	int idx;
2018 
2019 	if (nr_args == RAW_SYSCALL_ARGS_NUM && sc->fmt && sc->fmt->nr_args != 0)
2020 		nr_args = sc->fmt->nr_args;
2021 
2022 	sc->arg_fmt = calloc(nr_args, sizeof(*sc->arg_fmt));
2023 	if (sc->arg_fmt == NULL)
2024 		return -1;
2025 
2026 	for (idx = 0; idx < nr_args; ++idx) {
2027 		if (sc->fmt)
2028 			sc->arg_fmt[idx] = sc->fmt->arg[idx];
2029 	}
2030 
2031 	sc->nr_args = nr_args;
2032 	return 0;
2033 }
2034 
2035 static const struct syscall_arg_fmt syscall_arg_fmts__by_name[] = {
2036 	{ .name = "msr",	.scnprintf = SCA_X86_MSR,	  .strtoul = STUL_X86_MSR,	   },
2037 	{ .name = "vector",	.scnprintf = SCA_X86_IRQ_VECTORS, .strtoul = STUL_X86_IRQ_VECTORS, },
2038 };
2039 
2040 static int syscall_arg_fmt__cmp(const void *name, const void *fmtp)
2041 {
2042        const struct syscall_arg_fmt *fmt = fmtp;
2043        return strcmp(name, fmt->name);
2044 }
2045 
2046 static const struct syscall_arg_fmt *
2047 __syscall_arg_fmt__find_by_name(const struct syscall_arg_fmt *fmts, const int nmemb,
2048 				const char *name)
2049 {
2050        return bsearch(name, fmts, nmemb, sizeof(struct syscall_arg_fmt), syscall_arg_fmt__cmp);
2051 }
2052 
2053 static const struct syscall_arg_fmt *syscall_arg_fmt__find_by_name(const char *name)
2054 {
2055        const int nmemb = ARRAY_SIZE(syscall_arg_fmts__by_name);
2056        return __syscall_arg_fmt__find_by_name(syscall_arg_fmts__by_name, nmemb, name);
2057 }
2058 
2059 static struct tep_format_field *
2060 syscall_arg_fmt__init_array(struct syscall_arg_fmt *arg, struct tep_format_field *field,
2061 			    bool *use_btf)
2062 {
2063 	struct tep_format_field *last_field = NULL;
2064 	int len;
2065 
2066 	for (; field; field = field->next, ++arg) {
2067 		last_field = field;
2068 
2069 		if (arg->scnprintf)
2070 			continue;
2071 
2072 		len = strlen(field->name);
2073 
2074 		// As far as heuristics (or intention) goes this seems to hold true, and makes sense!
2075 		if ((field->flags & TEP_FIELD_IS_POINTER) && strstarts(field->type, "const "))
2076 			arg->from_user = true;
2077 
2078 		if (strcmp(field->type, "const char *") == 0 &&
2079 		    ((len >= 4 && strcmp(field->name + len - 4, "name") == 0) ||
2080 		     strstr(field->name, "path") != NULL)) {
2081 			arg->scnprintf = SCA_FILENAME;
2082 		} else if ((field->flags & TEP_FIELD_IS_POINTER) || strstr(field->name, "addr"))
2083 			arg->scnprintf = SCA_PTR;
2084 		else if (strcmp(field->type, "pid_t") == 0)
2085 			arg->scnprintf = SCA_PID;
2086 		else if (strcmp(field->type, "umode_t") == 0)
2087 			arg->scnprintf = SCA_MODE_T;
2088 		else if ((field->flags & TEP_FIELD_IS_ARRAY) && strstr(field->type, "char")) {
2089 			arg->scnprintf = SCA_CHAR_ARRAY;
2090 			arg->nr_entries = field->arraylen;
2091 		} else if ((strcmp(field->type, "int") == 0 ||
2092 			  strcmp(field->type, "unsigned int") == 0 ||
2093 			  strcmp(field->type, "long") == 0) &&
2094 			 len >= 2 && strcmp(field->name + len - 2, "fd") == 0) {
2095 			/*
2096 			 * /sys/kernel/tracing/events/syscalls/sys_enter*
2097 			 * grep -E 'field:.*fd;' .../format|sed -r 's/.*field:([a-z ]+) [a-z_]*fd.+/\1/g'|sort|uniq -c
2098 			 * 65 int
2099 			 * 23 unsigned int
2100 			 * 7 unsigned long
2101 			 */
2102 			arg->scnprintf = SCA_FD;
2103 		} else if (strstr(field->type, "enum") && use_btf != NULL) {
2104 			*use_btf = true;
2105 			arg->strtoul = STUL_BTF_TYPE;
2106 		} else {
2107 			const struct syscall_arg_fmt *fmt =
2108 				syscall_arg_fmt__find_by_name(field->name);
2109 
2110 			if (fmt) {
2111 				arg->scnprintf = fmt->scnprintf;
2112 				arg->strtoul   = fmt->strtoul;
2113 			}
2114 		}
2115 	}
2116 
2117 	return last_field;
2118 }
2119 
2120 static int syscall__set_arg_fmts(struct syscall *sc)
2121 {
2122 	struct tep_format_field *last_field = syscall_arg_fmt__init_array(sc->arg_fmt, sc->args,
2123 									  &sc->use_btf);
2124 
2125 	if (last_field)
2126 		sc->args_size = last_field->offset + last_field->size;
2127 
2128 	return 0;
2129 }
2130 
2131 static int syscall__read_info(struct syscall *sc, struct trace *trace)
2132 {
2133 	char tp_name[128];
2134 	const char *name;
2135 	int err;
2136 
2137 	if (sc->nonexistent)
2138 		return -EEXIST;
2139 
2140 	if (sc->name) {
2141 		/* Info already read. */
2142 		return 0;
2143 	}
2144 
2145 	name = syscalltbl__name(sc->e_machine, sc->id);
2146 	if (name == NULL) {
2147 		sc->nonexistent = true;
2148 		return -EEXIST;
2149 	}
2150 
2151 	sc->name = name;
2152 	sc->fmt  = syscall_fmt__find(sc->name);
2153 
2154 	snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->name);
2155 	sc->tp_format = trace_event__tp_format("syscalls", tp_name);
2156 
2157 	if (IS_ERR(sc->tp_format) && sc->fmt && sc->fmt->alias) {
2158 		snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->fmt->alias);
2159 		sc->tp_format = trace_event__tp_format("syscalls", tp_name);
2160 	}
2161 
2162 	/*
2163 	 * Fails to read trace point format via sysfs node, so the trace point
2164 	 * doesn't exist.  Set the 'nonexistent' flag as true.
2165 	 */
2166 	if (IS_ERR(sc->tp_format)) {
2167 		sc->nonexistent = true;
2168 		err = PTR_ERR(sc->tp_format);
2169 		sc->tp_format = NULL;
2170 		return err;
2171 	}
2172 
2173 	/*
2174 	 * The tracepoint format contains __syscall_nr field, so it's one more
2175 	 * than the actual number of syscall arguments.
2176 	 */
2177 	if (syscall__alloc_arg_fmts(sc, sc->tp_format->format.nr_fields - 1))
2178 		return -ENOMEM;
2179 
2180 	sc->args = sc->tp_format->format.fields;
2181 	/*
2182 	 * We need to check and discard the first variable '__syscall_nr'
2183 	 * or 'nr' that mean the syscall number. It is needless here.
2184 	 * So drop '__syscall_nr' or 'nr' field but does not exist on older kernels.
2185 	 */
2186 	if (sc->args && (!strcmp(sc->args->name, "__syscall_nr") || !strcmp(sc->args->name, "nr"))) {
2187 		sc->args = sc->args->next;
2188 		--sc->nr_args;
2189 	}
2190 
2191 	sc->is_exit = !strcmp(name, "exit_group") || !strcmp(name, "exit");
2192 	sc->is_open = !strcmp(name, "open") || !strcmp(name, "openat");
2193 
2194 	err = syscall__set_arg_fmts(sc);
2195 
2196 	/* after calling syscall__set_arg_fmts() we'll know whether use_btf is true */
2197 	if (sc->use_btf)
2198 		trace__load_vmlinux_btf(trace);
2199 
2200 	return err;
2201 }
2202 
2203 static int evsel__init_tp_arg_scnprintf(struct evsel *evsel, bool *use_btf)
2204 {
2205 	struct syscall_arg_fmt *fmt = evsel__syscall_arg_fmt(evsel);
2206 
2207 	if (fmt != NULL) {
2208 		const struct tep_event *tp_format = evsel__tp_format(evsel);
2209 
2210 		if (tp_format) {
2211 			syscall_arg_fmt__init_array(fmt, tp_format->format.fields, use_btf);
2212 			return 0;
2213 		}
2214 	}
2215 
2216 	return -ENOMEM;
2217 }
2218 
2219 static int intcmp(const void *a, const void *b)
2220 {
2221 	const int *one = a, *another = b;
2222 
2223 	return *one - *another;
2224 }
2225 
2226 static int trace__validate_ev_qualifier(struct trace *trace)
2227 {
2228 	int err = 0;
2229 	bool printed_invalid_prefix = false;
2230 	struct str_node *pos;
2231 	size_t nr_used = 0, nr_allocated = strlist__nr_entries(trace->ev_qualifier);
2232 
2233 	trace->ev_qualifier_ids.entries = malloc(nr_allocated *
2234 						 sizeof(trace->ev_qualifier_ids.entries[0]));
2235 
2236 	if (trace->ev_qualifier_ids.entries == NULL) {
2237 		fputs("Error:\tNot enough memory for allocating events qualifier ids\n",
2238 		       trace->output);
2239 		err = -EINVAL;
2240 		goto out;
2241 	}
2242 
2243 	strlist__for_each_entry(pos, trace->ev_qualifier) {
2244 		const char *sc = pos->s;
2245 		/*
2246 		 * TODO: Assume more than the validation/warnings are all for
2247 		 * the same binary type as perf.
2248 		 */
2249 		int id = syscalltbl__id(EM_HOST, sc), match_next = -1;
2250 
2251 		if (id < 0) {
2252 			id = syscalltbl__strglobmatch_first(EM_HOST, sc, &match_next);
2253 			if (id >= 0)
2254 				goto matches;
2255 
2256 			if (!printed_invalid_prefix) {
2257 				pr_debug("Skipping unknown syscalls: ");
2258 				printed_invalid_prefix = true;
2259 			} else {
2260 				pr_debug(", ");
2261 			}
2262 
2263 			pr_debug("%s", sc);
2264 			continue;
2265 		}
2266 matches:
2267 		trace->ev_qualifier_ids.entries[nr_used++] = id;
2268 		if (match_next == -1)
2269 			continue;
2270 
2271 		while (1) {
2272 			id = syscalltbl__strglobmatch_next(EM_HOST, sc, &match_next);
2273 			if (id < 0)
2274 				break;
2275 			if (nr_allocated == nr_used) {
2276 				void *entries;
2277 
2278 				nr_allocated += 8;
2279 				entries = realloc(trace->ev_qualifier_ids.entries,
2280 						  nr_allocated * sizeof(trace->ev_qualifier_ids.entries[0]));
2281 				if (entries == NULL) {
2282 					err = -ENOMEM;
2283 					fputs("\nError:\t Not enough memory for parsing\n", trace->output);
2284 					goto out_free;
2285 				}
2286 				trace->ev_qualifier_ids.entries = entries;
2287 			}
2288 			trace->ev_qualifier_ids.entries[nr_used++] = id;
2289 		}
2290 	}
2291 
2292 	trace->ev_qualifier_ids.nr = nr_used;
2293 	qsort(trace->ev_qualifier_ids.entries, nr_used, sizeof(int), intcmp);
2294 out:
2295 	if (printed_invalid_prefix)
2296 		pr_debug("\n");
2297 	return err;
2298 out_free:
2299 	zfree(&trace->ev_qualifier_ids.entries);
2300 	trace->ev_qualifier_ids.nr = 0;
2301 	goto out;
2302 }
2303 
2304 static __maybe_unused bool trace__syscall_enabled(struct trace *trace, int id)
2305 {
2306 	bool in_ev_qualifier;
2307 
2308 	if (trace->ev_qualifier_ids.nr == 0)
2309 		return true;
2310 
2311 	in_ev_qualifier = bsearch(&id, trace->ev_qualifier_ids.entries,
2312 				  trace->ev_qualifier_ids.nr, sizeof(int), intcmp) != NULL;
2313 
2314 	if (in_ev_qualifier)
2315 	       return !trace->not_ev_qualifier;
2316 
2317 	return trace->not_ev_qualifier;
2318 }
2319 
2320 /*
2321  * args is to be interpreted as a series of longs but we need to handle
2322  * 8-byte unaligned accesses. args points to raw_data within the event
2323  * and raw_data is guaranteed to be 8-byte unaligned because it is
2324  * preceded by raw_size which is a u32. So we need to copy args to a temp
2325  * variable to read it. Most notably this avoids extended load instructions
2326  * on unaligned addresses
2327  */
2328 unsigned long syscall_arg__val(struct syscall_arg *arg, u8 idx)
2329 {
2330 	unsigned long val;
2331 	unsigned char *p = arg->args + sizeof(unsigned long) * idx;
2332 
2333 	memcpy(&val, p, sizeof(val));
2334 	return val;
2335 }
2336 
2337 static size_t syscall__scnprintf_name(struct syscall *sc, char *bf, size_t size,
2338 				      struct syscall_arg *arg)
2339 {
2340 	if (sc->arg_fmt && sc->arg_fmt[arg->idx].name)
2341 		return scnprintf(bf, size, "%s: ", sc->arg_fmt[arg->idx].name);
2342 
2343 	return scnprintf(bf, size, "arg%d: ", arg->idx);
2344 }
2345 
2346 /*
2347  * Check if the value is in fact zero, i.e. mask whatever needs masking, such
2348  * as mount 'flags' argument that needs ignoring some magic flag, see comment
2349  * in tools/perf/trace/beauty/mount_flags.c
2350  */
2351 static unsigned long syscall_arg_fmt__mask_val(struct syscall_arg_fmt *fmt, struct syscall_arg *arg, unsigned long val)
2352 {
2353 	if (fmt && fmt->mask_val)
2354 		return fmt->mask_val(arg, val);
2355 
2356 	return val;
2357 }
2358 
2359 static size_t syscall_arg_fmt__scnprintf_val(struct syscall_arg_fmt *fmt, char *bf, size_t size,
2360 					     struct syscall_arg *arg, unsigned long val)
2361 {
2362 	if (fmt && fmt->scnprintf) {
2363 		arg->val = val;
2364 		if (fmt->parm)
2365 			arg->parm = fmt->parm;
2366 		return fmt->scnprintf(bf, size, arg);
2367 	}
2368 	return scnprintf(bf, size, "%ld", val);
2369 }
2370 
2371 static size_t syscall__scnprintf_args(struct syscall *sc, char *bf, size_t size,
2372 				      unsigned char *args, void *augmented_args, int augmented_args_size,
2373 				      struct trace *trace, struct thread *thread)
2374 {
2375 	size_t printed = 0, btf_printed;
2376 	unsigned long val;
2377 	u8 bit = 1;
2378 	struct syscall_arg arg = {
2379 		.args	= args,
2380 		.augmented = {
2381 			.size = augmented_args_size,
2382 			.args = augmented_args,
2383 		},
2384 		.idx	= 0,
2385 		.mask	= 0,
2386 		.trace  = trace,
2387 		.thread = thread,
2388 		.show_string_prefix = trace->show_string_prefix,
2389 	};
2390 	struct thread_trace *ttrace = thread__priv(thread);
2391 	void *default_scnprintf;
2392 
2393 	/*
2394 	 * Things like fcntl will set this in its 'cmd' formatter to pick the
2395 	 * right formatter for the return value (an fd? file flags?), which is
2396 	 * not needed for syscalls that always return a given type, say an fd.
2397 	 */
2398 	ttrace->ret_scnprintf = NULL;
2399 
2400 	if (sc->args != NULL) {
2401 		struct tep_format_field *field;
2402 
2403 		for (field = sc->args; field;
2404 		     field = field->next, ++arg.idx, bit <<= 1) {
2405 			if (arg.mask & bit)
2406 				continue;
2407 
2408 			arg.fmt = &sc->arg_fmt[arg.idx];
2409 			val = syscall_arg__val(&arg, arg.idx);
2410 			/*
2411 			 * Some syscall args need some mask, most don't and
2412 			 * return val untouched.
2413 			 */
2414 			val = syscall_arg_fmt__mask_val(&sc->arg_fmt[arg.idx], &arg, val);
2415 
2416 			/*
2417 			 * Suppress this argument if its value is zero and show_zero
2418 			 * property isn't set.
2419 			 *
2420 			 * If it has a BTF type, then override the zero suppression knob
2421 			 * as the common case is for zero in an enum to have an associated entry.
2422 			 */
2423 			if (val == 0 && !trace->show_zeros &&
2424 			    !(sc->arg_fmt && sc->arg_fmt[arg.idx].show_zero) &&
2425 			    !(sc->arg_fmt && sc->arg_fmt[arg.idx].strtoul == STUL_BTF_TYPE))
2426 				continue;
2427 
2428 			printed += scnprintf(bf + printed, size - printed, "%s", printed ? ", " : "");
2429 
2430 			if (trace->show_arg_names)
2431 				printed += scnprintf(bf + printed, size - printed, "%s: ", field->name);
2432 
2433 			default_scnprintf = sc->arg_fmt[arg.idx].scnprintf;
2434 
2435 			if (trace->force_btf || default_scnprintf == NULL || default_scnprintf == SCA_PTR) {
2436 				btf_printed = trace__btf_scnprintf(trace, &arg, bf + printed,
2437 								   size - printed, val, field->type);
2438 				if (btf_printed) {
2439 					printed += btf_printed;
2440 					continue;
2441 				}
2442 			}
2443 
2444 			printed += syscall_arg_fmt__scnprintf_val(&sc->arg_fmt[arg.idx],
2445 								  bf + printed, size - printed, &arg, val);
2446 		}
2447 	} else if (IS_ERR(sc->tp_format)) {
2448 		/*
2449 		 * If we managed to read the tracepoint /format file, then we
2450 		 * may end up not having any args, like with gettid(), so only
2451 		 * print the raw args when we didn't manage to read it.
2452 		 */
2453 		while (arg.idx < sc->nr_args) {
2454 			if (arg.mask & bit)
2455 				goto next_arg;
2456 			val = syscall_arg__val(&arg, arg.idx);
2457 			if (printed)
2458 				printed += scnprintf(bf + printed, size - printed, ", ");
2459 			printed += syscall__scnprintf_name(sc, bf + printed, size - printed, &arg);
2460 			printed += syscall_arg_fmt__scnprintf_val(&sc->arg_fmt[arg.idx], bf + printed, size - printed, &arg, val);
2461 next_arg:
2462 			++arg.idx;
2463 			bit <<= 1;
2464 		}
2465 	}
2466 
2467 	return printed;
2468 }
2469 
2470 static struct syscall *syscall__new(int e_machine, int id)
2471 {
2472 	struct syscall *sc = zalloc(sizeof(*sc));
2473 
2474 	if (!sc)
2475 		return NULL;
2476 
2477 	sc->e_machine = e_machine;
2478 	sc->id = id;
2479 	return sc;
2480 }
2481 
2482 static void syscall__delete(struct syscall *sc)
2483 {
2484 	if (!sc)
2485 		return;
2486 
2487 	free(sc->arg_fmt);
2488 	free(sc);
2489 }
2490 
2491 static int syscall__bsearch_cmp(const void *key, const void *entry)
2492 {
2493 	const struct syscall *a = key, *b = *((const struct syscall **)entry);
2494 
2495 	if (a->e_machine != b->e_machine)
2496 		return a->e_machine - b->e_machine;
2497 
2498 	return a->id - b->id;
2499 }
2500 
2501 static int syscall__cmp(const void *va, const void *vb)
2502 {
2503 	const struct syscall *a = *((const struct syscall **)va);
2504 	const struct syscall *b = *((const struct syscall **)vb);
2505 
2506 	if (a->e_machine != b->e_machine)
2507 		return a->e_machine - b->e_machine;
2508 
2509 	return a->id - b->id;
2510 }
2511 
2512 static struct syscall *trace__find_syscall(struct trace *trace, int e_machine, int id)
2513 {
2514 	struct syscall key = {
2515 		.e_machine = e_machine,
2516 		.id = id,
2517 	};
2518 	struct syscall *sc, **tmp;
2519 
2520 	if (trace->syscalls.table) {
2521 		struct syscall **sc_entry = bsearch(&key, trace->syscalls.table,
2522 						    trace->syscalls.table_size,
2523 						    sizeof(trace->syscalls.table[0]),
2524 						    syscall__bsearch_cmp);
2525 
2526 		if (sc_entry)
2527 			return *sc_entry;
2528 	}
2529 
2530 	sc = syscall__new(e_machine, id);
2531 	if (!sc)
2532 		return NULL;
2533 
2534 	tmp = reallocarray(trace->syscalls.table, trace->syscalls.table_size + 1,
2535 			   sizeof(trace->syscalls.table[0]));
2536 	if (!tmp) {
2537 		syscall__delete(sc);
2538 		return NULL;
2539 	}
2540 
2541 	trace->syscalls.table = tmp;
2542 	trace->syscalls.table[trace->syscalls.table_size++] = sc;
2543 	qsort(trace->syscalls.table, trace->syscalls.table_size, sizeof(trace->syscalls.table[0]),
2544 	      syscall__cmp);
2545 	return sc;
2546 }
2547 
2548 typedef int (*tracepoint_handler)(struct trace *trace, struct evsel *evsel,
2549 				  union perf_event *event,
2550 				  struct perf_sample *sample);
2551 
2552 static struct syscall *trace__syscall_info(struct trace *trace, struct evsel *evsel,
2553 					   int e_machine, int id)
2554 {
2555 	struct syscall *sc;
2556 	int err = 0;
2557 
2558 	if (id < 0) {
2559 
2560 		/*
2561 		 * XXX: Noticed on x86_64, reproduced as far back as 3.0.36, haven't tried
2562 		 * before that, leaving at a higher verbosity level till that is
2563 		 * explained. Reproduced with plain ftrace with:
2564 		 *
2565 		 * echo 1 > /t/events/raw_syscalls/sys_exit/enable
2566 		 * grep "NR -1 " /t/trace_pipe
2567 		 *
2568 		 * After generating some load on the machine.
2569  		 */
2570 		if (verbose > 1) {
2571 			static u64 n;
2572 			fprintf(trace->output, "Invalid syscall %d id, skipping (%s, %" PRIu64 ") ...\n",
2573 				id, evsel__name(evsel), ++n);
2574 		}
2575 		return NULL;
2576 	}
2577 
2578 	err = -EINVAL;
2579 
2580 	sc = trace__find_syscall(trace, e_machine, id);
2581 	if (sc)
2582 		err = syscall__read_info(sc, trace);
2583 
2584 	if (err && verbose > 0) {
2585 		char sbuf[STRERR_BUFSIZE];
2586 
2587 		fprintf(trace->output, "Problems reading syscall %d: %d (%s)", id, -err,
2588 			str_error_r(-err, sbuf, sizeof(sbuf)));
2589 		if (sc && sc->name)
2590 			fprintf(trace->output, "(%s)", sc->name);
2591 		fputs(" information\n", trace->output);
2592 	}
2593 	return err ? NULL : sc;
2594 }
2595 
2596 struct syscall_stats {
2597 	struct stats stats;
2598 	u64	     nr_failures;
2599 	int	     max_errno;
2600 	u32	     *errnos;
2601 };
2602 
2603 static void thread__update_stats(struct thread *thread, struct thread_trace *ttrace,
2604 				 int id, struct perf_sample *sample, long err,
2605 				 struct trace *trace)
2606 {
2607 	struct hashmap *syscall_stats = ttrace->syscall_stats;
2608 	struct syscall_stats *stats = NULL;
2609 	u64 duration = 0;
2610 
2611 	if (trace->summary_bpf)
2612 		return;
2613 
2614 	if (trace->summary_mode == SUMMARY__BY_TOTAL)
2615 		syscall_stats = trace->syscall_stats;
2616 
2617 	if (!hashmap__find(syscall_stats, id, &stats)) {
2618 		stats = zalloc(sizeof(*stats));
2619 		if (stats == NULL)
2620 			return;
2621 
2622 		init_stats(&stats->stats);
2623 		if (hashmap__add(syscall_stats, id, stats) < 0) {
2624 			free(stats);
2625 			return;
2626 		}
2627 	}
2628 
2629 	if (ttrace->entry_time && sample->time > ttrace->entry_time)
2630 		duration = sample->time - ttrace->entry_time;
2631 
2632 	update_stats(&stats->stats, duration);
2633 
2634 	if (err < 0) {
2635 		++stats->nr_failures;
2636 
2637 		if (!trace->errno_summary)
2638 			return;
2639 
2640 		err = -err;
2641 		if (err > stats->max_errno) {
2642 			u32 *new_errnos = realloc(stats->errnos, err * sizeof(u32));
2643 
2644 			if (new_errnos) {
2645 				memset(new_errnos + stats->max_errno, 0, (err - stats->max_errno) * sizeof(u32));
2646 			} else {
2647 				pr_debug("Not enough memory for errno stats for thread \"%s\"(%d/%d), results will be incomplete\n",
2648 					 thread__comm_str(thread), thread__pid(thread),
2649 					 thread__tid(thread));
2650 				return;
2651 			}
2652 
2653 			stats->errnos = new_errnos;
2654 			stats->max_errno = err;
2655 		}
2656 
2657 		++stats->errnos[err - 1];
2658 	}
2659 }
2660 
2661 static int trace__printf_interrupted_entry(struct trace *trace)
2662 {
2663 	struct thread_trace *ttrace;
2664 	size_t printed;
2665 	int len;
2666 
2667 	if (trace->failure_only || trace->current == NULL)
2668 		return 0;
2669 
2670 	ttrace = thread__priv(trace->current);
2671 
2672 	if (!ttrace->entry_pending)
2673 		return 0;
2674 
2675 	printed  = trace__fprintf_entry_head(trace, trace->current, 0, false, ttrace->entry_time, trace->output);
2676 	printed += len = fprintf(trace->output, "%s)", ttrace->entry_str);
2677 
2678 	if (len < trace->args_alignment - 4)
2679 		printed += fprintf(trace->output, "%-*s", trace->args_alignment - 4 - len, " ");
2680 
2681 	printed += fprintf(trace->output, " ...\n");
2682 
2683 	ttrace->entry_pending = false;
2684 	++trace->nr_events_printed;
2685 
2686 	return printed;
2687 }
2688 
2689 static int trace__fprintf_sample(struct trace *trace, struct evsel *evsel,
2690 				 struct perf_sample *sample, struct thread *thread)
2691 {
2692 	int printed = 0;
2693 
2694 	if (trace->print_sample) {
2695 		double ts = (double)sample->time / NSEC_PER_MSEC;
2696 
2697 		printed += fprintf(trace->output, "%22s %10.3f %s %d/%d [%d]\n",
2698 				   evsel__name(evsel), ts,
2699 				   thread__comm_str(thread),
2700 				   sample->pid, sample->tid, sample->cpu);
2701 	}
2702 
2703 	return printed;
2704 }
2705 
2706 static void *syscall__augmented_args(struct syscall *sc, struct perf_sample *sample, int *augmented_args_size, int raw_augmented_args_size)
2707 {
2708 	/*
2709 	 * For now with BPF raw_augmented we hook into raw_syscalls:sys_enter
2710 	 * and there we get all 6 syscall args plus the tracepoint common fields
2711 	 * that gets calculated at the start and the syscall_nr (another long).
2712 	 * So we check if that is the case and if so don't look after the
2713 	 * sc->args_size but always after the full raw_syscalls:sys_enter payload,
2714 	 * which is fixed.
2715 	 *
2716 	 * We'll revisit this later to pass s->args_size to the BPF augmenter
2717 	 * (now tools/perf/examples/bpf/augmented_raw_syscalls.c, so that it
2718 	 * copies only what we need for each syscall, like what happens when we
2719 	 * use syscalls:sys_enter_NAME, so that we reduce the kernel/userspace
2720 	 * traffic to just what is needed for each syscall.
2721 	 */
2722 	int args_size = raw_augmented_args_size ?: sc->args_size;
2723 
2724 	*augmented_args_size = sample->raw_size - args_size;
2725 	if (*augmented_args_size > 0) {
2726 		static uintptr_t argbuf[1024]; /* assuming single-threaded */
2727 
2728 		if ((size_t)(*augmented_args_size) > sizeof(argbuf))
2729 			return NULL;
2730 
2731 		/*
2732 		 * The perf ring-buffer is 8-byte aligned but sample->raw_data
2733 		 * is not because it's preceded by u32 size.  Later, beautifier
2734 		 * will use the augmented args with stricter alignments like in
2735 		 * some struct.  To make sure it's aligned, let's copy the args
2736 		 * into a static buffer as it's single-threaded for now.
2737 		 */
2738 		memcpy(argbuf, sample->raw_data + args_size, *augmented_args_size);
2739 
2740 		return argbuf;
2741 	}
2742 	return NULL;
2743 }
2744 
2745 static int trace__sys_enter(struct trace *trace, struct evsel *evsel,
2746 			    union perf_event *event __maybe_unused,
2747 			    struct perf_sample *sample)
2748 {
2749 	char *msg;
2750 	void *args;
2751 	int printed = 0;
2752 	struct thread *thread;
2753 	int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
2754 	int augmented_args_size = 0, e_machine;
2755 	void *augmented_args = NULL;
2756 	struct syscall *sc;
2757 	struct thread_trace *ttrace;
2758 
2759 	thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2760 	e_machine = thread__e_machine(thread, trace->host);
2761 	sc = trace__syscall_info(trace, evsel, e_machine, id);
2762 	if (sc == NULL)
2763 		goto out_put;
2764 	ttrace = thread__trace(thread, trace);
2765 	if (ttrace == NULL)
2766 		goto out_put;
2767 
2768 	trace__fprintf_sample(trace, evsel, sample, thread);
2769 
2770 	args = perf_evsel__sc_tp_ptr(evsel, args, sample);
2771 
2772 	if (ttrace->entry_str == NULL) {
2773 		ttrace->entry_str = malloc(trace__entry_str_size);
2774 		if (!ttrace->entry_str)
2775 			goto out_put;
2776 	}
2777 
2778 	if (!(trace->duration_filter || trace->summary_only || trace->min_stack))
2779 		trace__printf_interrupted_entry(trace);
2780 	/*
2781 	 * If this is raw_syscalls.sys_enter, then it always comes with the 6 possible
2782 	 * arguments, even if the syscall being handled, say "openat", uses only 4 arguments
2783 	 * this breaks syscall__augmented_args() check for augmented args, as we calculate
2784 	 * syscall->args_size using each syscalls:sys_enter_NAME tracefs format file,
2785 	 * so when handling, say the openat syscall, we end up getting 6 args for the
2786 	 * raw_syscalls:sys_enter event, when we expected just 4, we end up mistakenly
2787 	 * thinking that the extra 2 u64 args are the augmented filename, so just check
2788 	 * here and avoid using augmented syscalls when the evsel is the raw_syscalls one.
2789 	 */
2790 	if (evsel != trace->syscalls.events.sys_enter)
2791 		augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size, trace->raw_augmented_syscalls_args_size);
2792 	ttrace->entry_time = sample->time;
2793 	msg = ttrace->entry_str;
2794 	printed += scnprintf(msg + printed, trace__entry_str_size - printed, "%s(", sc->name);
2795 
2796 	printed += syscall__scnprintf_args(sc, msg + printed, trace__entry_str_size - printed,
2797 					   args, augmented_args, augmented_args_size, trace, thread);
2798 
2799 	if (sc->is_exit) {
2800 		if (!(trace->duration_filter || trace->summary_only || trace->failure_only || trace->min_stack)) {
2801 			int alignment = 0;
2802 
2803 			trace__fprintf_entry_head(trace, thread, 0, false, ttrace->entry_time, trace->output);
2804 			printed = fprintf(trace->output, "%s)", ttrace->entry_str);
2805 			if (trace->args_alignment > printed)
2806 				alignment = trace->args_alignment - printed;
2807 			fprintf(trace->output, "%*s= ?\n", alignment, " ");
2808 		}
2809 	} else {
2810 		ttrace->entry_pending = true;
2811 		/* See trace__vfs_getname & trace__sys_exit */
2812 		ttrace->filename.pending_open = false;
2813 	}
2814 
2815 	if (trace->current != thread) {
2816 		thread__put(trace->current);
2817 		trace->current = thread__get(thread);
2818 	}
2819 	err = 0;
2820 out_put:
2821 	thread__put(thread);
2822 	return err;
2823 }
2824 
2825 static int trace__fprintf_sys_enter(struct trace *trace, struct evsel *evsel,
2826 				    struct perf_sample *sample)
2827 {
2828 	struct thread_trace *ttrace;
2829 	struct thread *thread;
2830 	int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
2831 	struct syscall *sc;
2832 	char msg[1024];
2833 	void *args, *augmented_args = NULL;
2834 	int augmented_args_size, e_machine;
2835 	size_t printed = 0;
2836 
2837 
2838 	thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2839 	e_machine = thread__e_machine(thread, trace->host);
2840 	sc = trace__syscall_info(trace, evsel, e_machine, id);
2841 	if (sc == NULL)
2842 		goto out_put;
2843 	ttrace = thread__trace(thread, trace);
2844 	/*
2845 	 * We need to get ttrace just to make sure it is there when syscall__scnprintf_args()
2846 	 * and the rest of the beautifiers accessing it via struct syscall_arg touches it.
2847 	 */
2848 	if (ttrace == NULL)
2849 		goto out_put;
2850 
2851 	args = perf_evsel__sc_tp_ptr(evsel, args, sample);
2852 	augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size, trace->raw_augmented_syscalls_args_size);
2853 	printed += syscall__scnprintf_args(sc, msg, sizeof(msg), args, augmented_args, augmented_args_size, trace, thread);
2854 	fprintf(trace->output, "%.*s", (int)printed, msg);
2855 	err = 0;
2856 out_put:
2857 	thread__put(thread);
2858 	return err;
2859 }
2860 
2861 static int trace__resolve_callchain(struct trace *trace, struct evsel *evsel,
2862 				    struct perf_sample *sample,
2863 				    struct callchain_cursor *cursor)
2864 {
2865 	struct addr_location al;
2866 	int max_stack = evsel->core.attr.sample_max_stack ?
2867 			evsel->core.attr.sample_max_stack :
2868 			trace->max_stack;
2869 	int err = -1;
2870 
2871 	addr_location__init(&al);
2872 	if (machine__resolve(trace->host, &al, sample) < 0)
2873 		goto out;
2874 
2875 	err = thread__resolve_callchain(al.thread, cursor, evsel, sample, NULL, NULL, max_stack);
2876 out:
2877 	addr_location__exit(&al);
2878 	return err;
2879 }
2880 
2881 static int trace__fprintf_callchain(struct trace *trace, struct perf_sample *sample)
2882 {
2883 	/* TODO: user-configurable print_opts */
2884 	const unsigned int print_opts = EVSEL__PRINT_SYM |
2885 				        EVSEL__PRINT_DSO |
2886 				        EVSEL__PRINT_UNKNOWN_AS_ADDR;
2887 
2888 	return sample__fprintf_callchain(sample, 38, print_opts, get_tls_callchain_cursor(), symbol_conf.bt_stop_list, trace->output);
2889 }
2890 
2891 static const char *errno_to_name(struct evsel *evsel, int err)
2892 {
2893 	struct perf_env *env = evsel__env(evsel);
2894 
2895 	return perf_env__arch_strerrno(env, err);
2896 }
2897 
2898 static int trace__sys_exit(struct trace *trace, struct evsel *evsel,
2899 			   union perf_event *event __maybe_unused,
2900 			   struct perf_sample *sample)
2901 {
2902 	long ret;
2903 	u64 duration = 0;
2904 	bool duration_calculated = false;
2905 	struct thread *thread;
2906 	int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1, callchain_ret = 0, printed = 0;
2907 	int alignment = trace->args_alignment, e_machine;
2908 	struct syscall *sc;
2909 	struct thread_trace *ttrace;
2910 
2911 	thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2912 	e_machine = thread__e_machine(thread, trace->host);
2913 	sc = trace__syscall_info(trace, evsel, e_machine, id);
2914 	if (sc == NULL)
2915 		goto out_put;
2916 	ttrace = thread__trace(thread, trace);
2917 	if (ttrace == NULL)
2918 		goto out_put;
2919 
2920 	trace__fprintf_sample(trace, evsel, sample, thread);
2921 
2922 	ret = perf_evsel__sc_tp_uint(evsel, ret, sample);
2923 
2924 	if (trace->summary)
2925 		thread__update_stats(thread, ttrace, id, sample, ret, trace);
2926 
2927 	if (!trace->fd_path_disabled && sc->is_open && ret >= 0 && ttrace->filename.pending_open) {
2928 		trace__set_fd_pathname(thread, ret, ttrace->filename.name);
2929 		ttrace->filename.pending_open = false;
2930 		++trace->stats.vfs_getname;
2931 	}
2932 
2933 	if (ttrace->entry_time) {
2934 		duration = sample->time - ttrace->entry_time;
2935 		if (trace__filter_duration(trace, duration))
2936 			goto out;
2937 		duration_calculated = true;
2938 	} else if (trace->duration_filter)
2939 		goto out;
2940 
2941 	if (sample->callchain) {
2942 		struct callchain_cursor *cursor = get_tls_callchain_cursor();
2943 
2944 		callchain_ret = trace__resolve_callchain(trace, evsel, sample, cursor);
2945 		if (callchain_ret == 0) {
2946 			if (cursor->nr < trace->min_stack)
2947 				goto out;
2948 			callchain_ret = 1;
2949 		}
2950 	}
2951 
2952 	if (trace->summary_only || (ret >= 0 && trace->failure_only))
2953 		goto out;
2954 
2955 	trace__fprintf_entry_head(trace, thread, duration, duration_calculated, ttrace->entry_time, trace->output);
2956 
2957 	if (ttrace->entry_pending) {
2958 		printed = fprintf(trace->output, "%s", ttrace->entry_str);
2959 	} else {
2960 		printed += fprintf(trace->output, " ... [");
2961 		color_fprintf(trace->output, PERF_COLOR_YELLOW, "continued");
2962 		printed += 9;
2963 		printed += fprintf(trace->output, "]: %s()", sc->name);
2964 	}
2965 
2966 	printed++; /* the closing ')' */
2967 
2968 	if (alignment > printed)
2969 		alignment -= printed;
2970 	else
2971 		alignment = 0;
2972 
2973 	fprintf(trace->output, ")%*s= ", alignment, " ");
2974 
2975 	if (sc->fmt == NULL) {
2976 		if (ret < 0)
2977 			goto errno_print;
2978 signed_print:
2979 		fprintf(trace->output, "%ld", ret);
2980 	} else if (ret < 0) {
2981 errno_print: {
2982 		char bf[STRERR_BUFSIZE];
2983 		const char *emsg = str_error_r(-ret, bf, sizeof(bf)),
2984 			   *e = errno_to_name(evsel, -ret);
2985 
2986 		fprintf(trace->output, "-1 %s (%s)", e, emsg);
2987 	}
2988 	} else if (ret == 0 && sc->fmt->timeout)
2989 		fprintf(trace->output, "0 (Timeout)");
2990 	else if (ttrace->ret_scnprintf) {
2991 		char bf[1024];
2992 		struct syscall_arg arg = {
2993 			.val	= ret,
2994 			.thread	= thread,
2995 			.trace	= trace,
2996 		};
2997 		ttrace->ret_scnprintf(bf, sizeof(bf), &arg);
2998 		ttrace->ret_scnprintf = NULL;
2999 		fprintf(trace->output, "%s", bf);
3000 	} else if (sc->fmt->hexret)
3001 		fprintf(trace->output, "%#lx", ret);
3002 	else if (sc->fmt->errpid) {
3003 		struct thread *child = machine__find_thread(trace->host, ret, ret);
3004 
3005 		fprintf(trace->output, "%ld", ret);
3006 		if (child != NULL) {
3007 			if (thread__comm_set(child))
3008 				fprintf(trace->output, " (%s)", thread__comm_str(child));
3009 			thread__put(child);
3010 		}
3011 	} else
3012 		goto signed_print;
3013 
3014 	fputc('\n', trace->output);
3015 
3016 	/*
3017 	 * We only consider an 'event' for the sake of --max-events a non-filtered
3018 	 * sys_enter + sys_exit and other tracepoint events.
3019 	 */
3020 	if (++trace->nr_events_printed == trace->max_events && trace->max_events != ULONG_MAX)
3021 		interrupted = true;
3022 
3023 	if (callchain_ret > 0)
3024 		trace__fprintf_callchain(trace, sample);
3025 	else if (callchain_ret < 0)
3026 		pr_err("Problem processing %s callchain, skipping...\n", evsel__name(evsel));
3027 out:
3028 	ttrace->entry_pending = false;
3029 	err = 0;
3030 out_put:
3031 	thread__put(thread);
3032 	return err;
3033 }
3034 
3035 static int trace__vfs_getname(struct trace *trace, struct evsel *evsel,
3036 			      union perf_event *event __maybe_unused,
3037 			      struct perf_sample *sample)
3038 {
3039 	struct thread *thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
3040 	struct thread_trace *ttrace;
3041 	size_t filename_len, entry_str_len, to_move;
3042 	ssize_t remaining_space;
3043 	char *pos;
3044 	const char *filename = evsel__rawptr(evsel, sample, "pathname");
3045 
3046 	if (!thread)
3047 		goto out;
3048 
3049 	ttrace = thread__priv(thread);
3050 	if (!ttrace)
3051 		goto out_put;
3052 
3053 	filename_len = strlen(filename);
3054 	if (filename_len == 0)
3055 		goto out_put;
3056 
3057 	if (ttrace->filename.namelen < filename_len) {
3058 		char *f = realloc(ttrace->filename.name, filename_len + 1);
3059 
3060 		if (f == NULL)
3061 			goto out_put;
3062 
3063 		ttrace->filename.namelen = filename_len;
3064 		ttrace->filename.name = f;
3065 	}
3066 
3067 	strcpy(ttrace->filename.name, filename);
3068 	ttrace->filename.pending_open = true;
3069 
3070 	if (!ttrace->filename.ptr)
3071 		goto out_put;
3072 
3073 	entry_str_len = strlen(ttrace->entry_str);
3074 	remaining_space = trace__entry_str_size - entry_str_len - 1; /* \0 */
3075 	if (remaining_space <= 0)
3076 		goto out_put;
3077 
3078 	if (filename_len > (size_t)remaining_space) {
3079 		filename += filename_len - remaining_space;
3080 		filename_len = remaining_space;
3081 	}
3082 
3083 	to_move = entry_str_len - ttrace->filename.entry_str_pos + 1; /* \0 */
3084 	pos = ttrace->entry_str + ttrace->filename.entry_str_pos;
3085 	memmove(pos + filename_len, pos, to_move);
3086 	memcpy(pos, filename, filename_len);
3087 
3088 	ttrace->filename.ptr = 0;
3089 	ttrace->filename.entry_str_pos = 0;
3090 out_put:
3091 	thread__put(thread);
3092 out:
3093 	return 0;
3094 }
3095 
3096 static int trace__sched_stat_runtime(struct trace *trace, struct evsel *evsel,
3097 				     union perf_event *event __maybe_unused,
3098 				     struct perf_sample *sample)
3099 {
3100         u64 runtime = evsel__intval(evsel, sample, "runtime");
3101 	double runtime_ms = (double)runtime / NSEC_PER_MSEC;
3102 	struct thread *thread = machine__findnew_thread(trace->host,
3103 							sample->pid,
3104 							sample->tid);
3105 	struct thread_trace *ttrace = thread__trace(thread, trace);
3106 
3107 	if (ttrace == NULL)
3108 		goto out_dump;
3109 
3110 	ttrace->runtime_ms += runtime_ms;
3111 	trace->runtime_ms += runtime_ms;
3112 out_put:
3113 	thread__put(thread);
3114 	return 0;
3115 
3116 out_dump:
3117 	fprintf(trace->output, "%s: comm=%s,pid=%u,runtime=%" PRIu64 ",vruntime=%" PRIu64 ")\n",
3118 	       evsel->name,
3119 	       evsel__strval(evsel, sample, "comm"),
3120 	       (pid_t)evsel__intval(evsel, sample, "pid"),
3121 	       runtime,
3122 	       evsel__intval(evsel, sample, "vruntime"));
3123 	goto out_put;
3124 }
3125 
3126 static int bpf_output__printer(enum binary_printer_ops op,
3127 			       unsigned int val, void *extra __maybe_unused, FILE *fp)
3128 {
3129 	unsigned char ch = (unsigned char)val;
3130 
3131 	switch (op) {
3132 	case BINARY_PRINT_CHAR_DATA:
3133 		return fprintf(fp, "%c", isprint(ch) ? ch : '.');
3134 	case BINARY_PRINT_DATA_BEGIN:
3135 	case BINARY_PRINT_LINE_BEGIN:
3136 	case BINARY_PRINT_ADDR:
3137 	case BINARY_PRINT_NUM_DATA:
3138 	case BINARY_PRINT_NUM_PAD:
3139 	case BINARY_PRINT_SEP:
3140 	case BINARY_PRINT_CHAR_PAD:
3141 	case BINARY_PRINT_LINE_END:
3142 	case BINARY_PRINT_DATA_END:
3143 	default:
3144 		break;
3145 	}
3146 
3147 	return 0;
3148 }
3149 
3150 static void bpf_output__fprintf(struct trace *trace,
3151 				struct perf_sample *sample)
3152 {
3153 	binary__fprintf(sample->raw_data, sample->raw_size, 8,
3154 			bpf_output__printer, NULL, trace->output);
3155 	++trace->nr_events_printed;
3156 }
3157 
3158 static size_t trace__fprintf_tp_fields(struct trace *trace, struct evsel *evsel, struct perf_sample *sample,
3159 				       struct thread *thread, void *augmented_args, int augmented_args_size)
3160 {
3161 	char bf[2048];
3162 	size_t size = sizeof(bf);
3163 	const struct tep_event *tp_format = evsel__tp_format(evsel);
3164 	struct tep_format_field *field = tp_format ? tp_format->format.fields : NULL;
3165 	struct syscall_arg_fmt *arg = __evsel__syscall_arg_fmt(evsel);
3166 	size_t printed = 0, btf_printed;
3167 	unsigned long val;
3168 	u8 bit = 1;
3169 	struct syscall_arg syscall_arg = {
3170 		.augmented = {
3171 			.size = augmented_args_size,
3172 			.args = augmented_args,
3173 		},
3174 		.idx	= 0,
3175 		.mask	= 0,
3176 		.trace  = trace,
3177 		.thread = thread,
3178 		.show_string_prefix = trace->show_string_prefix,
3179 	};
3180 
3181 	for (; field && arg; field = field->next, ++syscall_arg.idx, bit <<= 1, ++arg) {
3182 		if (syscall_arg.mask & bit)
3183 			continue;
3184 
3185 		syscall_arg.len = 0;
3186 		syscall_arg.fmt = arg;
3187 		if (field->flags & TEP_FIELD_IS_ARRAY) {
3188 			int offset = field->offset;
3189 
3190 			if (field->flags & TEP_FIELD_IS_DYNAMIC) {
3191 				offset = format_field__intval(field, sample, evsel->needs_swap);
3192 				syscall_arg.len = offset >> 16;
3193 				offset &= 0xffff;
3194 				if (tep_field_is_relative(field->flags))
3195 					offset += field->offset + field->size;
3196 			}
3197 
3198 			val = (uintptr_t)(sample->raw_data + offset);
3199 		} else
3200 			val = format_field__intval(field, sample, evsel->needs_swap);
3201 		/*
3202 		 * Some syscall args need some mask, most don't and
3203 		 * return val untouched.
3204 		 */
3205 		val = syscall_arg_fmt__mask_val(arg, &syscall_arg, val);
3206 
3207 		/* Suppress this argument if its value is zero and show_zero property isn't set. */
3208 		if (val == 0 && !trace->show_zeros && !arg->show_zero && arg->strtoul != STUL_BTF_TYPE)
3209 			continue;
3210 
3211 		printed += scnprintf(bf + printed, size - printed, "%s", printed ? ", " : "");
3212 
3213 		if (trace->show_arg_names)
3214 			printed += scnprintf(bf + printed, size - printed, "%s: ", field->name);
3215 
3216 		btf_printed = trace__btf_scnprintf(trace, &syscall_arg, bf + printed, size - printed, val, field->type);
3217 		if (btf_printed) {
3218 			printed += btf_printed;
3219 			continue;
3220 		}
3221 
3222 		printed += syscall_arg_fmt__scnprintf_val(arg, bf + printed, size - printed, &syscall_arg, val);
3223 	}
3224 
3225 	return fprintf(trace->output, "%.*s", (int)printed, bf);
3226 }
3227 
3228 static int trace__event_handler(struct trace *trace, struct evsel *evsel,
3229 				union perf_event *event __maybe_unused,
3230 				struct perf_sample *sample)
3231 {
3232 	struct thread *thread;
3233 	int callchain_ret = 0;
3234 
3235 	if (evsel->nr_events_printed >= evsel->max_events)
3236 		return 0;
3237 
3238 	thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
3239 
3240 	if (sample->callchain) {
3241 		struct callchain_cursor *cursor = get_tls_callchain_cursor();
3242 
3243 		callchain_ret = trace__resolve_callchain(trace, evsel, sample, cursor);
3244 		if (callchain_ret == 0) {
3245 			if (cursor->nr < trace->min_stack)
3246 				goto out;
3247 			callchain_ret = 1;
3248 		}
3249 	}
3250 
3251 	trace__printf_interrupted_entry(trace);
3252 	trace__fprintf_tstamp(trace, sample->time, trace->output);
3253 
3254 	if (trace->trace_syscalls && trace->show_duration)
3255 		fprintf(trace->output, "(         ): ");
3256 
3257 	if (thread)
3258 		trace__fprintf_comm_tid(trace, thread, trace->output);
3259 
3260 	if (evsel == trace->syscalls.events.bpf_output) {
3261 		int id = perf_evsel__sc_tp_uint(evsel, id, sample);
3262 		int e_machine = thread ? thread__e_machine(thread, trace->host) : EM_HOST;
3263 		struct syscall *sc = trace__syscall_info(trace, evsel, e_machine, id);
3264 
3265 		if (sc) {
3266 			fprintf(trace->output, "%s(", sc->name);
3267 			trace__fprintf_sys_enter(trace, evsel, sample);
3268 			fputc(')', trace->output);
3269 			goto newline;
3270 		}
3271 
3272 		/*
3273 		 * XXX: Not having the associated syscall info or not finding/adding
3274 		 * 	the thread should never happen, but if it does...
3275 		 * 	fall thru and print it as a bpf_output event.
3276 		 */
3277 	}
3278 
3279 	fprintf(trace->output, "%s(", evsel->name);
3280 
3281 	if (evsel__is_bpf_output(evsel)) {
3282 		bpf_output__fprintf(trace, sample);
3283 	} else {
3284 		const struct tep_event *tp_format = evsel__tp_format(evsel);
3285 
3286 		if (tp_format && (strncmp(tp_format->name, "sys_enter_", 10) ||
3287 				  trace__fprintf_sys_enter(trace, evsel, sample))) {
3288 			if (trace->libtraceevent_print) {
3289 				event_format__fprintf(tp_format, sample->cpu,
3290 						      sample->raw_data, sample->raw_size,
3291 						      trace->output);
3292 			} else {
3293 				trace__fprintf_tp_fields(trace, evsel, sample, thread, NULL, 0);
3294 			}
3295 		}
3296 	}
3297 
3298 newline:
3299 	fprintf(trace->output, ")\n");
3300 
3301 	if (callchain_ret > 0)
3302 		trace__fprintf_callchain(trace, sample);
3303 	else if (callchain_ret < 0)
3304 		pr_err("Problem processing %s callchain, skipping...\n", evsel__name(evsel));
3305 
3306 	++trace->nr_events_printed;
3307 
3308 	if (evsel->max_events != ULONG_MAX && ++evsel->nr_events_printed == evsel->max_events) {
3309 		evsel__disable(evsel);
3310 		evsel__close(evsel);
3311 	}
3312 out:
3313 	thread__put(thread);
3314 	return 0;
3315 }
3316 
3317 static void print_location(FILE *f, struct perf_sample *sample,
3318 			   struct addr_location *al,
3319 			   bool print_dso, bool print_sym)
3320 {
3321 
3322 	if ((verbose > 0 || print_dso) && al->map)
3323 		fprintf(f, "%s@", dso__long_name(map__dso(al->map)));
3324 
3325 	if ((verbose > 0 || print_sym) && al->sym)
3326 		fprintf(f, "%s+0x%" PRIx64, al->sym->name,
3327 			al->addr - al->sym->start);
3328 	else if (al->map)
3329 		fprintf(f, "0x%" PRIx64, al->addr);
3330 	else
3331 		fprintf(f, "0x%" PRIx64, sample->addr);
3332 }
3333 
3334 static int trace__pgfault(struct trace *trace,
3335 			  struct evsel *evsel,
3336 			  union perf_event *event __maybe_unused,
3337 			  struct perf_sample *sample)
3338 {
3339 	struct thread *thread;
3340 	struct addr_location al;
3341 	char map_type = 'd';
3342 	struct thread_trace *ttrace;
3343 	int err = -1;
3344 	int callchain_ret = 0;
3345 
3346 	addr_location__init(&al);
3347 	thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
3348 
3349 	if (sample->callchain) {
3350 		struct callchain_cursor *cursor = get_tls_callchain_cursor();
3351 
3352 		callchain_ret = trace__resolve_callchain(trace, evsel, sample, cursor);
3353 		if (callchain_ret == 0) {
3354 			if (cursor->nr < trace->min_stack)
3355 				goto out_put;
3356 			callchain_ret = 1;
3357 		}
3358 	}
3359 
3360 	ttrace = thread__trace(thread, trace);
3361 	if (ttrace == NULL)
3362 		goto out_put;
3363 
3364 	if (evsel->core.attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ) {
3365 		ttrace->pfmaj++;
3366 		trace->pfmaj++;
3367 	} else {
3368 		ttrace->pfmin++;
3369 		trace->pfmin++;
3370 	}
3371 
3372 	if (trace->summary_only)
3373 		goto out;
3374 
3375 	thread__find_symbol(thread, sample->cpumode, sample->ip, &al);
3376 
3377 	trace__fprintf_entry_head(trace, thread, 0, true, sample->time, trace->output);
3378 
3379 	fprintf(trace->output, "%sfault [",
3380 		evsel->core.attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ?
3381 		"maj" : "min");
3382 
3383 	print_location(trace->output, sample, &al, false, true);
3384 
3385 	fprintf(trace->output, "] => ");
3386 
3387 	thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
3388 
3389 	if (!al.map) {
3390 		thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
3391 
3392 		if (al.map)
3393 			map_type = 'x';
3394 		else
3395 			map_type = '?';
3396 	}
3397 
3398 	print_location(trace->output, sample, &al, true, false);
3399 
3400 	fprintf(trace->output, " (%c%c)\n", map_type, al.level);
3401 
3402 	if (callchain_ret > 0)
3403 		trace__fprintf_callchain(trace, sample);
3404 	else if (callchain_ret < 0)
3405 		pr_err("Problem processing %s callchain, skipping...\n", evsel__name(evsel));
3406 
3407 	++trace->nr_events_printed;
3408 out:
3409 	err = 0;
3410 out_put:
3411 	thread__put(thread);
3412 	addr_location__exit(&al);
3413 	return err;
3414 }
3415 
3416 static void trace__set_base_time(struct trace *trace,
3417 				 struct evsel *evsel,
3418 				 struct perf_sample *sample)
3419 {
3420 	/*
3421 	 * BPF events were not setting PERF_SAMPLE_TIME, so be more robust
3422 	 * and don't use sample->time unconditionally, we may end up having
3423 	 * some other event in the future without PERF_SAMPLE_TIME for good
3424 	 * reason, i.e. we may not be interested in its timestamps, just in
3425 	 * it taking place, picking some piece of information when it
3426 	 * appears in our event stream (vfs_getname comes to mind).
3427 	 */
3428 	if (trace->base_time == 0 && !trace->full_time &&
3429 	    (evsel->core.attr.sample_type & PERF_SAMPLE_TIME))
3430 		trace->base_time = sample->time;
3431 }
3432 
3433 static int trace__process_sample(const struct perf_tool *tool,
3434 				 union perf_event *event,
3435 				 struct perf_sample *sample,
3436 				 struct evsel *evsel,
3437 				 struct machine *machine __maybe_unused)
3438 {
3439 	struct trace *trace = container_of(tool, struct trace, tool);
3440 	struct thread *thread;
3441 	int err = 0;
3442 
3443 	tracepoint_handler handler = evsel->handler;
3444 
3445 	thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
3446 	if (thread && thread__is_filtered(thread))
3447 		goto out;
3448 
3449 	trace__set_base_time(trace, evsel, sample);
3450 
3451 	if (handler) {
3452 		++trace->nr_events;
3453 		handler(trace, evsel, event, sample);
3454 	}
3455 out:
3456 	thread__put(thread);
3457 	return err;
3458 }
3459 
3460 static int trace__record(struct trace *trace, int argc, const char **argv)
3461 {
3462 	unsigned int rec_argc, i, j;
3463 	const char **rec_argv;
3464 	const char * const record_args[] = {
3465 		"record",
3466 		"-R",
3467 		"-m", "1024",
3468 		"-c", "1",
3469 	};
3470 	pid_t pid = getpid();
3471 	char *filter = asprintf__tp_filter_pids(1, &pid);
3472 	const char * const sc_args[] = { "-e", };
3473 	unsigned int sc_args_nr = ARRAY_SIZE(sc_args);
3474 	const char * const majpf_args[] = { "-e", "major-faults" };
3475 	unsigned int majpf_args_nr = ARRAY_SIZE(majpf_args);
3476 	const char * const minpf_args[] = { "-e", "minor-faults" };
3477 	unsigned int minpf_args_nr = ARRAY_SIZE(minpf_args);
3478 	int err = -1;
3479 
3480 	/* +3 is for the event string below and the pid filter */
3481 	rec_argc = ARRAY_SIZE(record_args) + sc_args_nr + 3 +
3482 		majpf_args_nr + minpf_args_nr + argc;
3483 	rec_argv = calloc(rec_argc + 1, sizeof(char *));
3484 
3485 	if (rec_argv == NULL || filter == NULL)
3486 		goto out_free;
3487 
3488 	j = 0;
3489 	for (i = 0; i < ARRAY_SIZE(record_args); i++)
3490 		rec_argv[j++] = record_args[i];
3491 
3492 	if (trace->trace_syscalls) {
3493 		for (i = 0; i < sc_args_nr; i++)
3494 			rec_argv[j++] = sc_args[i];
3495 
3496 		/* event string may be different for older kernels - e.g., RHEL6 */
3497 		if (is_valid_tracepoint("raw_syscalls:sys_enter"))
3498 			rec_argv[j++] = "raw_syscalls:sys_enter,raw_syscalls:sys_exit";
3499 		else if (is_valid_tracepoint("syscalls:sys_enter"))
3500 			rec_argv[j++] = "syscalls:sys_enter,syscalls:sys_exit";
3501 		else {
3502 			pr_err("Neither raw_syscalls nor syscalls events exist.\n");
3503 			goto out_free;
3504 		}
3505 	}
3506 
3507 	rec_argv[j++] = "--filter";
3508 	rec_argv[j++] = filter;
3509 
3510 	if (trace->trace_pgfaults & TRACE_PFMAJ)
3511 		for (i = 0; i < majpf_args_nr; i++)
3512 			rec_argv[j++] = majpf_args[i];
3513 
3514 	if (trace->trace_pgfaults & TRACE_PFMIN)
3515 		for (i = 0; i < minpf_args_nr; i++)
3516 			rec_argv[j++] = minpf_args[i];
3517 
3518 	for (i = 0; i < (unsigned int)argc; i++)
3519 		rec_argv[j++] = argv[i];
3520 
3521 	err = cmd_record(j, rec_argv);
3522 out_free:
3523 	free(filter);
3524 	free(rec_argv);
3525 	return err;
3526 }
3527 
3528 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp);
3529 static size_t trace__fprintf_total_summary(struct trace *trace, FILE *fp);
3530 
3531 static bool evlist__add_vfs_getname(struct evlist *evlist)
3532 {
3533 	bool found = false;
3534 	struct evsel *evsel, *tmp;
3535 	struct parse_events_error err;
3536 	int ret;
3537 
3538 	parse_events_error__init(&err);
3539 	ret = parse_events(evlist, "probe:vfs_getname*", &err);
3540 	parse_events_error__exit(&err);
3541 	if (ret)
3542 		return false;
3543 
3544 	evlist__for_each_entry_safe(evlist, evsel, tmp) {
3545 		if (!strstarts(evsel__name(evsel), "probe:vfs_getname"))
3546 			continue;
3547 
3548 		if (evsel__field(evsel, "pathname")) {
3549 			evsel->handler = trace__vfs_getname;
3550 			found = true;
3551 			continue;
3552 		}
3553 
3554 		list_del_init(&evsel->core.node);
3555 		evsel->evlist = NULL;
3556 		evsel__delete(evsel);
3557 	}
3558 
3559 	return found;
3560 }
3561 
3562 static struct evsel *evsel__new_pgfault(u64 config)
3563 {
3564 	struct evsel *evsel;
3565 	struct perf_event_attr attr = {
3566 		.type = PERF_TYPE_SOFTWARE,
3567 		.mmap_data = 1,
3568 	};
3569 
3570 	attr.config = config;
3571 	attr.sample_period = 1;
3572 
3573 	event_attr_init(&attr);
3574 
3575 	evsel = evsel__new(&attr);
3576 	if (evsel)
3577 		evsel->handler = trace__pgfault;
3578 
3579 	return evsel;
3580 }
3581 
3582 static void evlist__free_syscall_tp_fields(struct evlist *evlist)
3583 {
3584 	struct evsel *evsel;
3585 
3586 	evlist__for_each_entry(evlist, evsel) {
3587 		evsel_trace__delete(evsel->priv);
3588 		evsel->priv = NULL;
3589 	}
3590 }
3591 
3592 static void trace__handle_event(struct trace *trace, union perf_event *event, struct perf_sample *sample)
3593 {
3594 	const u32 type = event->header.type;
3595 	struct evsel *evsel;
3596 
3597 	if (type != PERF_RECORD_SAMPLE) {
3598 		trace__process_event(trace, trace->host, event, sample);
3599 		return;
3600 	}
3601 
3602 	evsel = evlist__id2evsel(trace->evlist, sample->id);
3603 	if (evsel == NULL) {
3604 		fprintf(trace->output, "Unknown tp ID %" PRIu64 ", skipping...\n", sample->id);
3605 		return;
3606 	}
3607 
3608 	if (evswitch__discard(&trace->evswitch, evsel))
3609 		return;
3610 
3611 	trace__set_base_time(trace, evsel, sample);
3612 
3613 	if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT &&
3614 	    sample->raw_data == NULL) {
3615 		fprintf(trace->output, "%s sample with no payload for tid: %d, cpu %d, raw_size=%d, skipping...\n",
3616 		       evsel__name(evsel), sample->tid,
3617 		       sample->cpu, sample->raw_size);
3618 	} else {
3619 		tracepoint_handler handler = evsel->handler;
3620 		handler(trace, evsel, event, sample);
3621 	}
3622 
3623 	if (trace->nr_events_printed >= trace->max_events && trace->max_events != ULONG_MAX)
3624 		interrupted = true;
3625 }
3626 
3627 static int trace__add_syscall_newtp(struct trace *trace)
3628 {
3629 	int ret = -1;
3630 	struct evlist *evlist = trace->evlist;
3631 	struct evsel *sys_enter, *sys_exit;
3632 
3633 	sys_enter = perf_evsel__raw_syscall_newtp("sys_enter", trace__sys_enter);
3634 	if (sys_enter == NULL)
3635 		goto out;
3636 
3637 	if (perf_evsel__init_sc_tp_ptr_field(sys_enter, args))
3638 		goto out_delete_sys_enter;
3639 
3640 	sys_exit = perf_evsel__raw_syscall_newtp("sys_exit", trace__sys_exit);
3641 	if (sys_exit == NULL)
3642 		goto out_delete_sys_enter;
3643 
3644 	if (perf_evsel__init_sc_tp_uint_field(sys_exit, ret))
3645 		goto out_delete_sys_exit;
3646 
3647 	evsel__config_callchain(sys_enter, &trace->opts, &callchain_param);
3648 	evsel__config_callchain(sys_exit, &trace->opts, &callchain_param);
3649 
3650 	evlist__add(evlist, sys_enter);
3651 	evlist__add(evlist, sys_exit);
3652 
3653 	if (callchain_param.enabled && !trace->kernel_syscallchains) {
3654 		/*
3655 		 * We're interested only in the user space callchain
3656 		 * leading to the syscall, allow overriding that for
3657 		 * debugging reasons using --kernel_syscall_callchains
3658 		 */
3659 		sys_exit->core.attr.exclude_callchain_kernel = 1;
3660 	}
3661 
3662 	trace->syscalls.events.sys_enter = sys_enter;
3663 	trace->syscalls.events.sys_exit  = sys_exit;
3664 
3665 	ret = 0;
3666 out:
3667 	return ret;
3668 
3669 out_delete_sys_exit:
3670 	evsel__delete_priv(sys_exit);
3671 out_delete_sys_enter:
3672 	evsel__delete_priv(sys_enter);
3673 	goto out;
3674 }
3675 
3676 static int trace__set_ev_qualifier_tp_filter(struct trace *trace)
3677 {
3678 	int err = -1;
3679 	struct evsel *sys_exit;
3680 	char *filter = asprintf_expr_inout_ints("id", !trace->not_ev_qualifier,
3681 						trace->ev_qualifier_ids.nr,
3682 						trace->ev_qualifier_ids.entries);
3683 
3684 	if (filter == NULL)
3685 		goto out_enomem;
3686 
3687 	if (!evsel__append_tp_filter(trace->syscalls.events.sys_enter, filter)) {
3688 		sys_exit = trace->syscalls.events.sys_exit;
3689 		err = evsel__append_tp_filter(sys_exit, filter);
3690 	}
3691 
3692 	free(filter);
3693 out:
3694 	return err;
3695 out_enomem:
3696 	errno = ENOMEM;
3697 	goto out;
3698 }
3699 
3700 #ifdef HAVE_LIBBPF_SUPPORT
3701 
3702 static struct bpf_program *unaugmented_prog;
3703 
3704 static int syscall_arg_fmt__cache_btf_struct(struct syscall_arg_fmt *arg_fmt, struct btf *btf, char *type)
3705 {
3706        int id;
3707 
3708 	if (arg_fmt->type != NULL)
3709 		return -1;
3710 
3711        id = btf__find_by_name(btf, type);
3712        if (id < 0)
3713 		return -1;
3714 
3715        arg_fmt->type    = btf__type_by_id(btf, id);
3716        arg_fmt->type_id = id;
3717 
3718        return 0;
3719 }
3720 
3721 static struct bpf_program *trace__find_syscall_bpf_prog(struct trace *trace __maybe_unused,
3722 							struct syscall *sc,
3723 							const char *prog_name, const char *type)
3724 {
3725 	struct bpf_program *prog;
3726 
3727 	if (prog_name == NULL) {
3728 		char default_prog_name[256];
3729 		scnprintf(default_prog_name, sizeof(default_prog_name), "tp/syscalls/sys_%s_%s", type, sc->name);
3730 		prog = augmented_syscalls__find_by_title(default_prog_name);
3731 		if (prog != NULL)
3732 			goto out_found;
3733 		if (sc->fmt && sc->fmt->alias) {
3734 			scnprintf(default_prog_name, sizeof(default_prog_name), "tp/syscalls/sys_%s_%s", type, sc->fmt->alias);
3735 			prog = augmented_syscalls__find_by_title(default_prog_name);
3736 			if (prog != NULL)
3737 				goto out_found;
3738 		}
3739 		goto out_unaugmented;
3740 	}
3741 
3742 	prog = augmented_syscalls__find_by_title(prog_name);
3743 
3744 	if (prog != NULL) {
3745 out_found:
3746 		return prog;
3747 	}
3748 
3749 	pr_debug("Couldn't find BPF prog \"%s\" to associate with syscalls:sys_%s_%s, not augmenting it\n",
3750 		 prog_name, type, sc->name);
3751 out_unaugmented:
3752 	return unaugmented_prog;
3753 }
3754 
3755 static void trace__init_syscall_bpf_progs(struct trace *trace, int e_machine, int id)
3756 {
3757 	struct syscall *sc = trace__syscall_info(trace, NULL, e_machine, id);
3758 
3759 	if (sc == NULL)
3760 		return;
3761 
3762 	sc->bpf_prog.sys_enter = trace__find_syscall_bpf_prog(trace, sc, sc->fmt ? sc->fmt->bpf_prog_name.sys_enter : NULL, "enter");
3763 	sc->bpf_prog.sys_exit  = trace__find_syscall_bpf_prog(trace, sc, sc->fmt ? sc->fmt->bpf_prog_name.sys_exit  : NULL,  "exit");
3764 }
3765 
3766 static int trace__bpf_prog_sys_enter_fd(struct trace *trace, int e_machine, int id)
3767 {
3768 	struct syscall *sc = trace__syscall_info(trace, NULL, e_machine, id);
3769 	return sc ? bpf_program__fd(sc->bpf_prog.sys_enter) : bpf_program__fd(unaugmented_prog);
3770 }
3771 
3772 static int trace__bpf_prog_sys_exit_fd(struct trace *trace, int e_machine, int id)
3773 {
3774 	struct syscall *sc = trace__syscall_info(trace, NULL, e_machine, id);
3775 	return sc ? bpf_program__fd(sc->bpf_prog.sys_exit) : bpf_program__fd(unaugmented_prog);
3776 }
3777 
3778 static int trace__bpf_sys_enter_beauty_map(struct trace *trace, int e_machine, int key, unsigned int *beauty_array)
3779 {
3780 	struct tep_format_field *field;
3781 	struct syscall *sc = trace__syscall_info(trace, NULL, e_machine, key);
3782 	const struct btf_type *bt;
3783 	char *struct_offset, *tmp, name[32];
3784 	bool can_augment = false;
3785 	int i, cnt;
3786 
3787 	if (sc == NULL)
3788 		return -1;
3789 
3790 	trace__load_vmlinux_btf(trace);
3791 	if (trace->btf == NULL)
3792 		return -1;
3793 
3794 	for (i = 0, field = sc->args; field; ++i, field = field->next) {
3795 		// XXX We're only collecting pointer payloads _from_ user space
3796 		if (!sc->arg_fmt[i].from_user)
3797 			continue;
3798 
3799 		struct_offset = strstr(field->type, "struct ");
3800 		if (struct_offset == NULL)
3801 			struct_offset = strstr(field->type, "union ");
3802 		else
3803 			struct_offset++; // "union" is shorter
3804 
3805 		if (field->flags & TEP_FIELD_IS_POINTER && struct_offset) { /* struct or union (think BPF's attr arg) */
3806 			struct_offset += 6;
3807 
3808 			/* for 'struct foo *', we only want 'foo' */
3809 			for (tmp = struct_offset, cnt = 0; *tmp != ' ' && *tmp != '\0'; ++tmp, ++cnt) {
3810 			}
3811 
3812 			strncpy(name, struct_offset, cnt);
3813 			name[cnt] = '\0';
3814 
3815 			/* cache struct's btf_type and type_id */
3816 			if (syscall_arg_fmt__cache_btf_struct(&sc->arg_fmt[i], trace->btf, name))
3817 				continue;
3818 
3819 			bt = sc->arg_fmt[i].type;
3820 			beauty_array[i] = bt->size;
3821 			can_augment = true;
3822 		} else if (field->flags & TEP_FIELD_IS_POINTER && /* string */
3823 			   strcmp(field->type, "const char *") == 0 &&
3824 			   (strstr(field->name, "name") ||
3825 			    strstr(field->name, "path") ||
3826 			    strstr(field->name, "file") ||
3827 			    strstr(field->name, "root") ||
3828 			    strstr(field->name, "key") ||
3829 			    strstr(field->name, "special") ||
3830 			    strstr(field->name, "type") ||
3831 			    strstr(field->name, "description"))) {
3832 			beauty_array[i] = 1;
3833 			can_augment = true;
3834 		} else if (field->flags & TEP_FIELD_IS_POINTER && /* buffer */
3835 			   strstr(field->type, "char *") &&
3836 			   (strstr(field->name, "buf") ||
3837 			    strstr(field->name, "val") ||
3838 			    strstr(field->name, "msg"))) {
3839 			int j;
3840 			struct tep_format_field *field_tmp;
3841 
3842 			/* find the size of the buffer that appears in pairs with buf */
3843 			for (j = 0, field_tmp = sc->args; field_tmp; ++j, field_tmp = field_tmp->next) {
3844 				if (!(field_tmp->flags & TEP_FIELD_IS_POINTER) && /* only integers */
3845 				    (strstr(field_tmp->name, "count") ||
3846 				     strstr(field_tmp->name, "siz") ||  /* size, bufsiz */
3847 				     (strstr(field_tmp->name, "len") && strcmp(field_tmp->name, "filename")))) {
3848 					 /* filename's got 'len' in it, we don't want that */
3849 					beauty_array[i] = -(j + 1);
3850 					can_augment = true;
3851 					break;
3852 				}
3853 			}
3854 		}
3855 	}
3856 
3857 	if (can_augment)
3858 		return 0;
3859 
3860 	return -1;
3861 }
3862 
3863 static struct bpf_program *trace__find_usable_bpf_prog_entry(struct trace *trace,
3864 							     struct syscall *sc)
3865 {
3866 	struct tep_format_field *field, *candidate_field;
3867 	/*
3868 	 * We're only interested in syscalls that have a pointer:
3869 	 */
3870 	for (field = sc->args; field; field = field->next) {
3871 		if (field->flags & TEP_FIELD_IS_POINTER)
3872 			goto try_to_find_pair;
3873 	}
3874 
3875 	return NULL;
3876 
3877 try_to_find_pair:
3878 	for (int i = 0, num_idx = syscalltbl__num_idx(sc->e_machine); i < num_idx; ++i) {
3879 		int id = syscalltbl__id_at_idx(sc->e_machine, i);
3880 		struct syscall *pair = trace__syscall_info(trace, NULL, sc->e_machine, id);
3881 		struct bpf_program *pair_prog;
3882 		bool is_candidate = false;
3883 
3884 		if (pair == NULL || pair->id == sc->id ||
3885 		    pair->bpf_prog.sys_enter == unaugmented_prog)
3886 			continue;
3887 
3888 		for (field = sc->args, candidate_field = pair->args;
3889 		     field && candidate_field; field = field->next, candidate_field = candidate_field->next) {
3890 			bool is_pointer = field->flags & TEP_FIELD_IS_POINTER,
3891 			     candidate_is_pointer = candidate_field->flags & TEP_FIELD_IS_POINTER;
3892 
3893 			if (is_pointer) {
3894 			       if (!candidate_is_pointer) {
3895 					// The candidate just doesn't copies our pointer arg, might copy other pointers we want.
3896 					continue;
3897 			       }
3898 			} else {
3899 				if (candidate_is_pointer) {
3900 					// The candidate might copy a pointer we don't have, skip it.
3901 					goto next_candidate;
3902 				}
3903 				continue;
3904 			}
3905 
3906 			if (strcmp(field->type, candidate_field->type))
3907 				goto next_candidate;
3908 
3909 			/*
3910 			 * This is limited in the BPF program but sys_write
3911 			 * uses "const char *" for its "buf" arg so we need to
3912 			 * use some heuristic that is kinda future proof...
3913 			 */
3914 			if (strcmp(field->type, "const char *") == 0 &&
3915 			    !(strstr(field->name, "name") ||
3916 			      strstr(field->name, "path") ||
3917 			      strstr(field->name, "file") ||
3918 			      strstr(field->name, "root") ||
3919 			      strstr(field->name, "description")))
3920 				goto next_candidate;
3921 
3922 			is_candidate = true;
3923 		}
3924 
3925 		if (!is_candidate)
3926 			goto next_candidate;
3927 
3928 		/*
3929 		 * Check if the tentative pair syscall augmenter has more pointers, if it has,
3930 		 * then it may be collecting that and we then can't use it, as it would collect
3931 		 * more than what is common to the two syscalls.
3932 		 */
3933 		if (candidate_field) {
3934 			for (candidate_field = candidate_field->next; candidate_field; candidate_field = candidate_field->next)
3935 				if (candidate_field->flags & TEP_FIELD_IS_POINTER)
3936 					goto next_candidate;
3937 		}
3938 
3939 		pair_prog = pair->bpf_prog.sys_enter;
3940 		/*
3941 		 * If the pair isn't enabled, then its bpf_prog.sys_enter will not
3942 		 * have been searched for, so search it here and if it returns the
3943 		 * unaugmented one, then ignore it, otherwise we'll reuse that BPF
3944 		 * program for a filtered syscall on a non-filtered one.
3945 		 *
3946 		 * For instance, we have "!syscalls:sys_enter_renameat" and that is
3947 		 * useful for "renameat2".
3948 		 */
3949 		if (pair_prog == NULL) {
3950 			pair_prog = trace__find_syscall_bpf_prog(trace, pair, pair->fmt ? pair->fmt->bpf_prog_name.sys_enter : NULL, "enter");
3951 			if (pair_prog == unaugmented_prog)
3952 				goto next_candidate;
3953 		}
3954 
3955 		pr_debug("Reusing \"%s\" BPF sys_enter augmenter for \"%s\"\n", pair->name,
3956 			 sc->name);
3957 		return pair_prog;
3958 	next_candidate:
3959 		continue;
3960 	}
3961 
3962 	return NULL;
3963 }
3964 
3965 static int trace__init_syscalls_bpf_prog_array_maps(struct trace *trace, int e_machine)
3966 {
3967 	int map_enter_fd;
3968 	int map_exit_fd;
3969 	int beauty_map_fd;
3970 	int err = 0;
3971 	unsigned int beauty_array[6];
3972 
3973 	if (augmented_syscalls__get_map_fds(&map_enter_fd, &map_exit_fd, &beauty_map_fd) < 0)
3974 		return -1;
3975 
3976 	unaugmented_prog = augmented_syscalls__unaugmented();
3977 
3978 	for (int i = 0, num_idx = syscalltbl__num_idx(e_machine); i < num_idx; ++i) {
3979 		int prog_fd, key = syscalltbl__id_at_idx(e_machine, i);
3980 
3981 		if (!trace__syscall_enabled(trace, key))
3982 			continue;
3983 
3984 		trace__init_syscall_bpf_progs(trace, e_machine, key);
3985 
3986 		// It'll get at least the "!raw_syscalls:unaugmented"
3987 		prog_fd = trace__bpf_prog_sys_enter_fd(trace, e_machine, key);
3988 		err = bpf_map_update_elem(map_enter_fd, &key, &prog_fd, BPF_ANY);
3989 		if (err)
3990 			break;
3991 		prog_fd = trace__bpf_prog_sys_exit_fd(trace, e_machine, key);
3992 		err = bpf_map_update_elem(map_exit_fd, &key, &prog_fd, BPF_ANY);
3993 		if (err)
3994 			break;
3995 
3996 		/* use beauty_map to tell BPF how many bytes to collect, set beauty_map's value here */
3997 		memset(beauty_array, 0, sizeof(beauty_array));
3998 		err = trace__bpf_sys_enter_beauty_map(trace, e_machine, key, (unsigned int *)beauty_array);
3999 		if (err)
4000 			continue;
4001 		err = bpf_map_update_elem(beauty_map_fd, &key, beauty_array, BPF_ANY);
4002 		if (err)
4003 			break;
4004 	}
4005 
4006 	/*
4007 	 * Now lets do a second pass looking for enabled syscalls without
4008 	 * an augmenter that have a signature that is a superset of another
4009 	 * syscall with an augmenter so that we can auto-reuse it.
4010 	 *
4011 	 * I.e. if we have an augmenter for the "open" syscall that has
4012 	 * this signature:
4013 	 *
4014 	 *   int open(const char *pathname, int flags, mode_t mode);
4015 	 *
4016 	 * I.e. that will collect just the first string argument, then we
4017 	 * can reuse it for the 'creat' syscall, that has this signature:
4018 	 *
4019 	 *   int creat(const char *pathname, mode_t mode);
4020 	 *
4021 	 * and for:
4022 	 *
4023 	 *   int stat(const char *pathname, struct stat *statbuf);
4024 	 *   int lstat(const char *pathname, struct stat *statbuf);
4025 	 *
4026 	 * Because the 'open' augmenter will collect the first arg as a string,
4027 	 * and leave alone all the other args, which already helps with
4028 	 * beautifying 'stat' and 'lstat''s pathname arg.
4029 	 *
4030 	 * Then, in time, when 'stat' gets an augmenter that collects both
4031 	 * first and second arg (this one on the raw_syscalls:sys_exit prog
4032 	 * array tail call, then that one will be used.
4033 	 */
4034 	for (int i = 0, num_idx = syscalltbl__num_idx(e_machine); i < num_idx; ++i) {
4035 		int key = syscalltbl__id_at_idx(e_machine, i);
4036 		struct syscall *sc = trace__syscall_info(trace, NULL, e_machine, key);
4037 		struct bpf_program *pair_prog;
4038 		int prog_fd;
4039 
4040 		if (sc == NULL || sc->bpf_prog.sys_enter == NULL)
4041 			continue;
4042 
4043 		/*
4044 		 * For now we're just reusing the sys_enter prog, and if it
4045 		 * already has an augmenter, we don't need to find one.
4046 		 */
4047 		if (sc->bpf_prog.sys_enter != unaugmented_prog)
4048 			continue;
4049 
4050 		/*
4051 		 * Look at all the other syscalls for one that has a signature
4052 		 * that is close enough that we can share:
4053 		 */
4054 		pair_prog = trace__find_usable_bpf_prog_entry(trace, sc);
4055 		if (pair_prog == NULL)
4056 			continue;
4057 
4058 		sc->bpf_prog.sys_enter = pair_prog;
4059 
4060 		/*
4061 		 * Update the BPF_MAP_TYPE_PROG_SHARED for raw_syscalls:sys_enter
4062 		 * with the fd for the program we're reusing:
4063 		 */
4064 		prog_fd = bpf_program__fd(sc->bpf_prog.sys_enter);
4065 		err = bpf_map_update_elem(map_enter_fd, &key, &prog_fd, BPF_ANY);
4066 		if (err)
4067 			break;
4068 	}
4069 
4070 	return err;
4071 }
4072 #else // !HAVE_LIBBPF_SUPPORT
4073 static int trace__init_syscalls_bpf_prog_array_maps(struct trace *trace __maybe_unused,
4074 						    int e_machine __maybe_unused)
4075 {
4076 	return -1;
4077 }
4078 #endif // HAVE_LIBBPF_SUPPORT
4079 
4080 static int trace__set_ev_qualifier_filter(struct trace *trace)
4081 {
4082 	if (trace->syscalls.events.sys_enter)
4083 		return trace__set_ev_qualifier_tp_filter(trace);
4084 	return 0;
4085 }
4086 
4087 static int trace__set_filter_loop_pids(struct trace *trace)
4088 {
4089 	unsigned int nr = 1, err;
4090 	pid_t pids[32] = {
4091 		getpid(),
4092 	};
4093 	struct thread *thread = machine__find_thread(trace->host, pids[0], pids[0]);
4094 
4095 	while (thread && nr < ARRAY_SIZE(pids)) {
4096 		struct thread *parent = machine__find_thread(trace->host,
4097 							     thread__ppid(thread),
4098 							     thread__ppid(thread));
4099 
4100 		if (parent == NULL)
4101 			break;
4102 
4103 		if (!strcmp(thread__comm_str(parent), "sshd") ||
4104 		    strstarts(thread__comm_str(parent), "gnome-terminal")) {
4105 			pids[nr++] = thread__tid(parent);
4106 			thread__put(parent);
4107 			break;
4108 		}
4109 		thread__put(thread);
4110 		thread = parent;
4111 	}
4112 	thread__put(thread);
4113 
4114 	err = evlist__append_tp_filter_pids(trace->evlist, nr, pids);
4115 	if (!err)
4116 		err = augmented_syscalls__set_filter_pids(nr, pids);
4117 
4118 	return err;
4119 }
4120 
4121 static int trace__set_filter_pids(struct trace *trace)
4122 {
4123 	int err = 0;
4124 	/*
4125 	 * Better not use !target__has_task() here because we need to cover the
4126 	 * case where no threads were specified in the command line, but a
4127 	 * workload was, and in that case we will fill in the thread_map when
4128 	 * we fork the workload in evlist__prepare_workload.
4129 	 */
4130 	if (trace->filter_pids.nr > 0) {
4131 		err = evlist__append_tp_filter_pids(trace->evlist, trace->filter_pids.nr,
4132 						    trace->filter_pids.entries);
4133 		if (!err) {
4134 			err = augmented_syscalls__set_filter_pids(trace->filter_pids.nr,
4135 						       trace->filter_pids.entries);
4136 		}
4137 	} else if (perf_thread_map__pid(trace->evlist->core.threads, 0) == -1) {
4138 		err = trace__set_filter_loop_pids(trace);
4139 	}
4140 
4141 	return err;
4142 }
4143 
4144 static int __trace__deliver_event(struct trace *trace, union perf_event *event)
4145 {
4146 	struct evlist *evlist = trace->evlist;
4147 	struct perf_sample sample;
4148 	int err;
4149 
4150 	perf_sample__init(&sample, /*all=*/false);
4151 	err = evlist__parse_sample(evlist, event, &sample);
4152 	if (err)
4153 		fprintf(trace->output, "Can't parse sample, err = %d, skipping...\n", err);
4154 	else
4155 		trace__handle_event(trace, event, &sample);
4156 
4157 	perf_sample__exit(&sample);
4158 	return 0;
4159 }
4160 
4161 static int __trace__flush_events(struct trace *trace)
4162 {
4163 	u64 first = ordered_events__first_time(&trace->oe.data);
4164 	u64 flush = trace->oe.last - NSEC_PER_SEC;
4165 
4166 	/* Is there some thing to flush.. */
4167 	if (first && first < flush)
4168 		return ordered_events__flush_time(&trace->oe.data, flush);
4169 
4170 	return 0;
4171 }
4172 
4173 static int trace__flush_events(struct trace *trace)
4174 {
4175 	return !trace->sort_events ? 0 : __trace__flush_events(trace);
4176 }
4177 
4178 static int trace__deliver_event(struct trace *trace, union perf_event *event)
4179 {
4180 	int err;
4181 
4182 	if (!trace->sort_events)
4183 		return __trace__deliver_event(trace, event);
4184 
4185 	err = evlist__parse_sample_timestamp(trace->evlist, event, &trace->oe.last);
4186 	if (err && err != -1)
4187 		return err;
4188 
4189 	err = ordered_events__queue(&trace->oe.data, event, trace->oe.last, 0, NULL);
4190 	if (err)
4191 		return err;
4192 
4193 	return trace__flush_events(trace);
4194 }
4195 
4196 static int ordered_events__deliver_event(struct ordered_events *oe,
4197 					 struct ordered_event *event)
4198 {
4199 	struct trace *trace = container_of(oe, struct trace, oe.data);
4200 
4201 	return __trace__deliver_event(trace, event->event);
4202 }
4203 
4204 static struct syscall_arg_fmt *evsel__find_syscall_arg_fmt_by_name(struct evsel *evsel, char *arg,
4205 								   char **type)
4206 {
4207 	struct syscall_arg_fmt *fmt = __evsel__syscall_arg_fmt(evsel);
4208 	const struct tep_event *tp_format;
4209 
4210 	if (!fmt)
4211 		return NULL;
4212 
4213 	tp_format = evsel__tp_format(evsel);
4214 	if (!tp_format)
4215 		return NULL;
4216 
4217 	for (const struct tep_format_field *field = tp_format->format.fields; field;
4218 	     field = field->next, ++fmt) {
4219 		if (strcmp(field->name, arg) == 0) {
4220 			*type = field->type;
4221 			return fmt;
4222 		}
4223 	}
4224 
4225 	return NULL;
4226 }
4227 
4228 static int trace__expand_filter(struct trace *trace, struct evsel *evsel)
4229 {
4230 	char *tok, *left = evsel->filter, *new_filter = evsel->filter;
4231 
4232 	while ((tok = strpbrk(left, "=<>!")) != NULL) {
4233 		char *right = tok + 1, *right_end;
4234 
4235 		if (*right == '=')
4236 			++right;
4237 
4238 		while (isspace(*right))
4239 			++right;
4240 
4241 		if (*right == '\0')
4242 			break;
4243 
4244 		while (!isalpha(*left))
4245 			if (++left == tok) {
4246 				/*
4247 				 * Bail out, can't find the name of the argument that is being
4248 				 * used in the filter, let it try to set this filter, will fail later.
4249 				 */
4250 				return 0;
4251 			}
4252 
4253 		right_end = right + 1;
4254 		while (isalnum(*right_end) || *right_end == '_' || *right_end == '|')
4255 			++right_end;
4256 
4257 		if (isalpha(*right)) {
4258 			struct syscall_arg_fmt *fmt;
4259 			int left_size = tok - left,
4260 			    right_size = right_end - right;
4261 			char arg[128], *type;
4262 
4263 			while (isspace(left[left_size - 1]))
4264 				--left_size;
4265 
4266 			scnprintf(arg, sizeof(arg), "%.*s", left_size, left);
4267 
4268 			fmt = evsel__find_syscall_arg_fmt_by_name(evsel, arg, &type);
4269 			if (fmt == NULL) {
4270 				pr_err("\"%s\" not found in \"%s\", can't set filter \"%s\"\n",
4271 				       arg, evsel->name, evsel->filter);
4272 				return -1;
4273 			}
4274 
4275 			pr_debug2("trying to expand \"%s\" \"%.*s\" \"%.*s\" -> ",
4276 				 arg, (int)(right - tok), tok, right_size, right);
4277 
4278 			if (fmt->strtoul) {
4279 				u64 val;
4280 				struct syscall_arg syscall_arg = {
4281 					.trace = trace,
4282 					.fmt   = fmt,
4283 					.type_name = type,
4284 					.parm = fmt->parm,
4285 				};
4286 
4287 				if (fmt->strtoul(right, right_size, &syscall_arg, &val)) {
4288 					char *n, expansion[19];
4289 					int expansion_lenght = scnprintf(expansion, sizeof(expansion), "%#" PRIx64, val);
4290 					int expansion_offset = right - new_filter;
4291 
4292 					pr_debug("%s", expansion);
4293 
4294 					if (asprintf(&n, "%.*s%s%s", expansion_offset, new_filter, expansion, right_end) < 0) {
4295 						pr_debug(" out of memory!\n");
4296 						free(new_filter);
4297 						return -1;
4298 					}
4299 					if (new_filter != evsel->filter)
4300 						free(new_filter);
4301 					left = n + expansion_offset + expansion_lenght;
4302 					new_filter = n;
4303 				} else {
4304 					pr_err("\"%.*s\" not found for \"%s\" in \"%s\", can't set filter \"%s\"\n",
4305 					       right_size, right, arg, evsel->name, evsel->filter);
4306 					return -1;
4307 				}
4308 			} else {
4309 				pr_err("No resolver (strtoul) for \"%s\" in \"%s\", can't set filter \"%s\"\n",
4310 				       arg, evsel->name, evsel->filter);
4311 				return -1;
4312 			}
4313 
4314 			pr_debug("\n");
4315 		} else {
4316 			left = right_end;
4317 		}
4318 	}
4319 
4320 	if (new_filter != evsel->filter) {
4321 		pr_debug("New filter for %s: %s\n", evsel->name, new_filter);
4322 		evsel__set_filter(evsel, new_filter);
4323 		free(new_filter);
4324 	}
4325 
4326 	return 0;
4327 }
4328 
4329 static int trace__expand_filters(struct trace *trace, struct evsel **err_evsel)
4330 {
4331 	struct evlist *evlist = trace->evlist;
4332 	struct evsel *evsel;
4333 
4334 	evlist__for_each_entry(evlist, evsel) {
4335 		if (evsel->filter == NULL)
4336 			continue;
4337 
4338 		if (trace__expand_filter(trace, evsel)) {
4339 			*err_evsel = evsel;
4340 			return -1;
4341 		}
4342 	}
4343 
4344 	return 0;
4345 }
4346 
4347 static int trace__run(struct trace *trace, int argc, const char **argv)
4348 {
4349 	struct evlist *evlist = trace->evlist;
4350 	struct evsel *evsel, *pgfault_maj = NULL, *pgfault_min = NULL;
4351 	int err = -1, i;
4352 	unsigned long before;
4353 	const bool forks = argc > 0;
4354 	bool draining = false;
4355 
4356 	trace->live = true;
4357 
4358 	if (trace->summary_bpf) {
4359 		if (trace_prepare_bpf_summary(trace->summary_mode) < 0)
4360 			goto out_delete_evlist;
4361 
4362 		if (trace->summary_only)
4363 			goto create_maps;
4364 	}
4365 
4366 	if (!trace->raw_augmented_syscalls) {
4367 		if (trace->trace_syscalls && trace__add_syscall_newtp(trace))
4368 			goto out_error_raw_syscalls;
4369 
4370 		if (trace->trace_syscalls)
4371 			trace->vfs_getname = evlist__add_vfs_getname(evlist);
4372 	}
4373 
4374 	if ((trace->trace_pgfaults & TRACE_PFMAJ)) {
4375 		pgfault_maj = evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MAJ);
4376 		if (pgfault_maj == NULL)
4377 			goto out_error_mem;
4378 		evsel__config_callchain(pgfault_maj, &trace->opts, &callchain_param);
4379 		evlist__add(evlist, pgfault_maj);
4380 	}
4381 
4382 	if ((trace->trace_pgfaults & TRACE_PFMIN)) {
4383 		pgfault_min = evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MIN);
4384 		if (pgfault_min == NULL)
4385 			goto out_error_mem;
4386 		evsel__config_callchain(pgfault_min, &trace->opts, &callchain_param);
4387 		evlist__add(evlist, pgfault_min);
4388 	}
4389 
4390 	/* Enable ignoring missing threads when -p option is defined. */
4391 	trace->opts.ignore_missing_thread = trace->opts.target.pid;
4392 
4393 	if (trace->sched &&
4394 	    evlist__add_newtp(evlist, "sched", "sched_stat_runtime", trace__sched_stat_runtime))
4395 		goto out_error_sched_stat_runtime;
4396 	/*
4397 	 * If a global cgroup was set, apply it to all the events without an
4398 	 * explicit cgroup. I.e.:
4399 	 *
4400 	 * 	trace -G A -e sched:*switch
4401 	 *
4402 	 * Will set all raw_syscalls:sys_{enter,exit}, pgfault, vfs_getname, etc
4403 	 * _and_ sched:sched_switch to the 'A' cgroup, while:
4404 	 *
4405 	 * trace -e sched:*switch -G A
4406 	 *
4407 	 * will only set the sched:sched_switch event to the 'A' cgroup, all the
4408 	 * other events (raw_syscalls:sys_{enter,exit}, etc are left "without"
4409 	 * a cgroup (on the root cgroup, sys wide, etc).
4410 	 *
4411 	 * Multiple cgroups:
4412 	 *
4413 	 * trace -G A -e sched:*switch -G B
4414 	 *
4415 	 * the syscall ones go to the 'A' cgroup, the sched:sched_switch goes
4416 	 * to the 'B' cgroup.
4417 	 *
4418 	 * evlist__set_default_cgroup() grabs a reference of the passed cgroup
4419 	 * only for the evsels still without a cgroup, i.e. evsel->cgroup == NULL.
4420 	 */
4421 	if (trace->cgroup)
4422 		evlist__set_default_cgroup(trace->evlist, trace->cgroup);
4423 
4424 create_maps:
4425 	err = evlist__create_maps(evlist, &trace->opts.target);
4426 	if (err < 0) {
4427 		fprintf(trace->output, "Problems parsing the target to trace, check your options!\n");
4428 		goto out_delete_evlist;
4429 	}
4430 
4431 	err = trace__symbols_init(trace, evlist);
4432 	if (err < 0) {
4433 		fprintf(trace->output, "Problems initializing symbol libraries!\n");
4434 		goto out_delete_evlist;
4435 	}
4436 
4437 	if (trace->summary_mode == SUMMARY__BY_TOTAL && !trace->summary_bpf) {
4438 		trace->syscall_stats = alloc_syscall_stats();
4439 		if (trace->syscall_stats == NULL)
4440 			goto out_delete_evlist;
4441 	}
4442 
4443 	evlist__config(evlist, &trace->opts, &callchain_param);
4444 
4445 	if (forks) {
4446 		err = evlist__prepare_workload(evlist, &trace->opts.target, argv, false, NULL);
4447 		if (err < 0) {
4448 			fprintf(trace->output, "Couldn't run the workload!\n");
4449 			goto out_delete_evlist;
4450 		}
4451 		workload_pid = evlist->workload.pid;
4452 	}
4453 
4454 	err = evlist__open(evlist);
4455 	if (err < 0)
4456 		goto out_error_open;
4457 
4458 	augmented_syscalls__setup_bpf_output();
4459 
4460 	err = trace__set_filter_pids(trace);
4461 	if (err < 0)
4462 		goto out_error_mem;
4463 
4464 	/*
4465 	 * TODO: Initialize for all host binary machine types, not just
4466 	 * those matching the perf binary.
4467 	 */
4468 	trace__init_syscalls_bpf_prog_array_maps(trace, EM_HOST);
4469 
4470 	if (trace->ev_qualifier_ids.nr > 0) {
4471 		err = trace__set_ev_qualifier_filter(trace);
4472 		if (err < 0)
4473 			goto out_errno;
4474 
4475 		if (trace->syscalls.events.sys_exit) {
4476 			pr_debug("event qualifier tracepoint filter: %s\n",
4477 				 trace->syscalls.events.sys_exit->filter);
4478 		}
4479 	}
4480 
4481 	/*
4482 	 * If the "close" syscall is not traced, then we will not have the
4483 	 * opportunity to, in syscall_arg__scnprintf_close_fd() invalidate the
4484 	 * fd->pathname table and were ending up showing the last value set by
4485 	 * syscalls opening a pathname and associating it with a descriptor or
4486 	 * reading it from /proc/pid/fd/ in cases where that doesn't make
4487 	 * sense.
4488 	 *
4489 	 *  So just disable this beautifier (SCA_FD, SCA_FDAT) when 'close' is
4490 	 *  not in use.
4491 	 */
4492 	/* TODO: support for more than just perf binary machine type close. */
4493 	trace->fd_path_disabled = !trace__syscall_enabled(trace, syscalltbl__id(EM_HOST, "close"));
4494 
4495 	err = trace__expand_filters(trace, &evsel);
4496 	if (err)
4497 		goto out_delete_evlist;
4498 	err = evlist__apply_filters(evlist, &evsel, &trace->opts.target);
4499 	if (err < 0)
4500 		goto out_error_apply_filters;
4501 
4502 	if (!trace->summary_only || !trace->summary_bpf) {
4503 		err = evlist__mmap(evlist, trace->opts.mmap_pages);
4504 		if (err < 0)
4505 			goto out_error_mmap;
4506 	}
4507 
4508 	if (!target__none(&trace->opts.target) && !trace->opts.target.initial_delay)
4509 		evlist__enable(evlist);
4510 
4511 	if (forks)
4512 		evlist__start_workload(evlist);
4513 
4514 	if (trace->opts.target.initial_delay) {
4515 		usleep(trace->opts.target.initial_delay * 1000);
4516 		evlist__enable(evlist);
4517 	}
4518 
4519 	if (trace->summary_bpf)
4520 		trace_start_bpf_summary();
4521 
4522 	trace->multiple_threads = perf_thread_map__pid(evlist->core.threads, 0) == -1 ||
4523 		perf_thread_map__nr(evlist->core.threads) > 1 ||
4524 		evlist__first(evlist)->core.attr.inherit;
4525 
4526 	/*
4527 	 * Now that we already used evsel->core.attr to ask the kernel to setup the
4528 	 * events, lets reuse evsel->core.attr.sample_max_stack as the limit in
4529 	 * trace__resolve_callchain(), allowing per-event max-stack settings
4530 	 * to override an explicitly set --max-stack global setting.
4531 	 */
4532 	evlist__for_each_entry(evlist, evsel) {
4533 		if (evsel__has_callchain(evsel) &&
4534 		    evsel->core.attr.sample_max_stack == 0)
4535 			evsel->core.attr.sample_max_stack = trace->max_stack;
4536 	}
4537 again:
4538 	before = trace->nr_events;
4539 
4540 	for (i = 0; i < evlist->core.nr_mmaps; i++) {
4541 		union perf_event *event;
4542 		struct mmap *md;
4543 
4544 		md = &evlist->mmap[i];
4545 		if (perf_mmap__read_init(&md->core) < 0)
4546 			continue;
4547 
4548 		while ((event = perf_mmap__read_event(&md->core)) != NULL) {
4549 			++trace->nr_events;
4550 
4551 			err = trace__deliver_event(trace, event);
4552 			if (err)
4553 				goto out_disable;
4554 
4555 			perf_mmap__consume(&md->core);
4556 
4557 			if (interrupted)
4558 				goto out_disable;
4559 
4560 			if (done && !draining) {
4561 				evlist__disable(evlist);
4562 				draining = true;
4563 			}
4564 		}
4565 		perf_mmap__read_done(&md->core);
4566 	}
4567 
4568 	if (trace->nr_events == before) {
4569 		int timeout = done ? 100 : -1;
4570 
4571 		if (!draining && evlist__poll(evlist, timeout) > 0) {
4572 			if (evlist__filter_pollfd(evlist, POLLERR | POLLHUP | POLLNVAL) == 0)
4573 				draining = true;
4574 
4575 			goto again;
4576 		} else {
4577 			if (trace__flush_events(trace))
4578 				goto out_disable;
4579 		}
4580 	} else {
4581 		goto again;
4582 	}
4583 
4584 out_disable:
4585 	thread__zput(trace->current);
4586 
4587 	evlist__disable(evlist);
4588 
4589 	if (trace->summary_bpf)
4590 		trace_end_bpf_summary();
4591 
4592 	if (trace->sort_events)
4593 		ordered_events__flush(&trace->oe.data, OE_FLUSH__FINAL);
4594 
4595 	if (!err) {
4596 		if (trace->summary) {
4597 			if (trace->summary_bpf)
4598 				trace_print_bpf_summary(trace->output);
4599 			else if (trace->summary_mode == SUMMARY__BY_TOTAL)
4600 				trace__fprintf_total_summary(trace, trace->output);
4601 			else
4602 				trace__fprintf_thread_summary(trace, trace->output);
4603 		}
4604 
4605 		if (trace->show_tool_stats) {
4606 			fprintf(trace->output, "Stats:\n "
4607 					       " vfs_getname : %" PRIu64 "\n"
4608 					       " proc_getname: %" PRIu64 "\n",
4609 				trace->stats.vfs_getname,
4610 				trace->stats.proc_getname);
4611 		}
4612 	}
4613 
4614 out_delete_evlist:
4615 	trace_cleanup_bpf_summary();
4616 	delete_syscall_stats(trace->syscall_stats);
4617 	trace__symbols__exit(trace);
4618 	evlist__free_syscall_tp_fields(evlist);
4619 	evlist__delete(evlist);
4620 	cgroup__put(trace->cgroup);
4621 	trace->evlist = NULL;
4622 	trace->live = false;
4623 	return err;
4624 {
4625 	char errbuf[BUFSIZ];
4626 
4627 out_error_sched_stat_runtime:
4628 	tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "sched", "sched_stat_runtime");
4629 	goto out_error;
4630 
4631 out_error_raw_syscalls:
4632 	tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "raw_syscalls", "sys_(enter|exit)");
4633 	goto out_error;
4634 
4635 out_error_mmap:
4636 	evlist__strerror_mmap(evlist, errno, errbuf, sizeof(errbuf));
4637 	goto out_error;
4638 
4639 out_error_open:
4640 	evlist__strerror_open(evlist, errno, errbuf, sizeof(errbuf));
4641 
4642 out_error:
4643 	fprintf(trace->output, "%s\n", errbuf);
4644 	goto out_delete_evlist;
4645 
4646 out_error_apply_filters:
4647 	fprintf(trace->output,
4648 		"Failed to set filter \"%s\" on event %s with %d (%s)\n",
4649 		evsel->filter, evsel__name(evsel), errno,
4650 		str_error_r(errno, errbuf, sizeof(errbuf)));
4651 	goto out_delete_evlist;
4652 }
4653 out_error_mem:
4654 	fprintf(trace->output, "Not enough memory to run!\n");
4655 	goto out_delete_evlist;
4656 
4657 out_errno:
4658 	fprintf(trace->output, "errno=%d,%s\n", errno, strerror(errno));
4659 	goto out_delete_evlist;
4660 }
4661 
4662 static int trace__replay(struct trace *trace)
4663 {
4664 	const struct evsel_str_handler handlers[] = {
4665 		{ "probe:vfs_getname",	     trace__vfs_getname, },
4666 	};
4667 	struct perf_data data = {
4668 		.path  = input_name,
4669 		.mode  = PERF_DATA_MODE_READ,
4670 		.force = trace->force,
4671 	};
4672 	struct perf_session *session;
4673 	struct evsel *evsel;
4674 	int err = -1;
4675 
4676 	perf_tool__init(&trace->tool, /*ordered_events=*/true);
4677 	trace->tool.sample	  = trace__process_sample;
4678 	trace->tool.mmap	  = perf_event__process_mmap;
4679 	trace->tool.mmap2	  = perf_event__process_mmap2;
4680 	trace->tool.comm	  = perf_event__process_comm;
4681 	trace->tool.exit	  = perf_event__process_exit;
4682 	trace->tool.fork	  = perf_event__process_fork;
4683 	trace->tool.attr	  = perf_event__process_attr;
4684 	trace->tool.tracing_data  = perf_event__process_tracing_data;
4685 	trace->tool.build_id	  = perf_event__process_build_id;
4686 	trace->tool.namespaces	  = perf_event__process_namespaces;
4687 
4688 	trace->tool.ordered_events = true;
4689 	trace->tool.ordering_requires_timestamps = true;
4690 
4691 	/* add tid to output */
4692 	trace->multiple_threads = true;
4693 
4694 	session = perf_session__new(&data, &trace->tool);
4695 	if (IS_ERR(session))
4696 		return PTR_ERR(session);
4697 
4698 	if (trace->opts.target.pid)
4699 		symbol_conf.pid_list_str = strdup(trace->opts.target.pid);
4700 
4701 	if (trace->opts.target.tid)
4702 		symbol_conf.tid_list_str = strdup(trace->opts.target.tid);
4703 
4704 	if (symbol__init(&session->header.env) < 0)
4705 		goto out;
4706 
4707 	trace->host = &session->machines.host;
4708 
4709 	err = perf_session__set_tracepoints_handlers(session, handlers);
4710 	if (err)
4711 		goto out;
4712 
4713 	evsel = evlist__find_tracepoint_by_name(session->evlist, "raw_syscalls:sys_enter");
4714 	trace->syscalls.events.sys_enter = evsel;
4715 	/* older kernels have syscalls tp versus raw_syscalls */
4716 	if (evsel == NULL)
4717 		evsel = evlist__find_tracepoint_by_name(session->evlist, "syscalls:sys_enter");
4718 
4719 	if (evsel &&
4720 	    (evsel__init_raw_syscall_tp(evsel, trace__sys_enter) < 0 ||
4721 	    perf_evsel__init_sc_tp_ptr_field(evsel, args))) {
4722 		pr_err("Error during initialize raw_syscalls:sys_enter event\n");
4723 		goto out;
4724 	}
4725 
4726 	evsel = evlist__find_tracepoint_by_name(session->evlist, "raw_syscalls:sys_exit");
4727 	trace->syscalls.events.sys_exit = evsel;
4728 	if (evsel == NULL)
4729 		evsel = evlist__find_tracepoint_by_name(session->evlist, "syscalls:sys_exit");
4730 	if (evsel &&
4731 	    (evsel__init_raw_syscall_tp(evsel, trace__sys_exit) < 0 ||
4732 	    perf_evsel__init_sc_tp_uint_field(evsel, ret))) {
4733 		pr_err("Error during initialize raw_syscalls:sys_exit event\n");
4734 		goto out;
4735 	}
4736 
4737 	evlist__for_each_entry(session->evlist, evsel) {
4738 		if (evsel->core.attr.type == PERF_TYPE_SOFTWARE &&
4739 		    (evsel->core.attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ||
4740 		     evsel->core.attr.config == PERF_COUNT_SW_PAGE_FAULTS_MIN ||
4741 		     evsel->core.attr.config == PERF_COUNT_SW_PAGE_FAULTS))
4742 			evsel->handler = trace__pgfault;
4743 	}
4744 
4745 	if (trace->summary_mode == SUMMARY__BY_TOTAL) {
4746 		trace->syscall_stats = alloc_syscall_stats();
4747 		if (trace->syscall_stats == NULL)
4748 			goto out;
4749 	}
4750 
4751 	setup_pager();
4752 
4753 	err = perf_session__process_events(session);
4754 	if (err)
4755 		pr_err("Failed to process events, error %d", err);
4756 
4757 	else if (trace->summary)
4758 		trace__fprintf_thread_summary(trace, trace->output);
4759 
4760 out:
4761 	delete_syscall_stats(trace->syscall_stats);
4762 	perf_session__delete(session);
4763 
4764 	return err;
4765 }
4766 
4767 static size_t trace__fprintf_summary_header(FILE *fp)
4768 {
4769 	size_t printed;
4770 
4771 	printed  = fprintf(fp, "\n Summary of events:\n\n");
4772 
4773 	return printed;
4774 }
4775 
4776 struct syscall_entry {
4777 	struct syscall_stats *stats;
4778 	double		     msecs;
4779 	int		     syscall;
4780 };
4781 
4782 static int entry_cmp(const void *e1, const void *e2)
4783 {
4784 	const struct syscall_entry *entry1 = e1;
4785 	const struct syscall_entry *entry2 = e2;
4786 
4787 	return entry1->msecs > entry2->msecs ? -1 : 1;
4788 }
4789 
4790 static struct syscall_entry *syscall__sort_stats(struct hashmap *syscall_stats)
4791 {
4792 	struct syscall_entry *entry;
4793 	struct hashmap_entry *pos;
4794 	unsigned bkt, i, nr;
4795 
4796 	nr = syscall_stats->sz;
4797 	entry = malloc(nr * sizeof(*entry));
4798 	if (entry == NULL)
4799 		return NULL;
4800 
4801 	i = 0;
4802 	hashmap__for_each_entry(syscall_stats, pos, bkt) {
4803 		struct syscall_stats *ss = pos->pvalue;
4804 		struct stats *st = &ss->stats;
4805 
4806 		entry[i].stats = ss;
4807 		entry[i].msecs = (u64)st->n * (avg_stats(st) / NSEC_PER_MSEC);
4808 		entry[i].syscall = pos->key;
4809 		i++;
4810 	}
4811 	assert(i == nr);
4812 
4813 	qsort(entry, nr, sizeof(*entry), entry_cmp);
4814 	return entry;
4815 }
4816 
4817 static size_t syscall__dump_stats(struct trace *trace, int e_machine, FILE *fp,
4818 				  struct hashmap *syscall_stats)
4819 {
4820 	size_t printed = 0;
4821 	struct syscall *sc;
4822 	struct syscall_entry *entries;
4823 
4824 	entries = syscall__sort_stats(syscall_stats);
4825 	if (entries == NULL)
4826 		return 0;
4827 
4828 	printed += fprintf(fp, "\n");
4829 
4830 	printed += fprintf(fp, "   syscall            calls  errors  total       min       avg       max       stddev\n");
4831 	printed += fprintf(fp, "                                     (msec)    (msec)    (msec)    (msec)        (%%)\n");
4832 	printed += fprintf(fp, "   --------------- --------  ------ -------- --------- --------- ---------     ------\n");
4833 
4834 	for (size_t i = 0; i < syscall_stats->sz; i++) {
4835 		struct syscall_entry *entry = &entries[i];
4836 		struct syscall_stats *stats = entry->stats;
4837 
4838 		if (stats) {
4839 			double min = (double)(stats->stats.min) / NSEC_PER_MSEC;
4840 			double max = (double)(stats->stats.max) / NSEC_PER_MSEC;
4841 			double avg = avg_stats(&stats->stats);
4842 			double pct;
4843 			u64 n = (u64)stats->stats.n;
4844 
4845 			pct = avg ? 100.0 * stddev_stats(&stats->stats) / avg : 0.0;
4846 			avg /= NSEC_PER_MSEC;
4847 
4848 			sc = trace__syscall_info(trace, /*evsel=*/NULL, e_machine, entry->syscall);
4849 			if (!sc)
4850 				continue;
4851 
4852 			printed += fprintf(fp, "   %-15s", sc->name);
4853 			printed += fprintf(fp, " %8" PRIu64 " %6" PRIu64 " %9.3f %9.3f %9.3f",
4854 					   n, stats->nr_failures, entry->msecs, min, avg);
4855 			printed += fprintf(fp, " %9.3f %9.2f%%\n", max, pct);
4856 
4857 			if (trace->errno_summary && stats->nr_failures) {
4858 				int e;
4859 
4860 				for (e = 0; e < stats->max_errno; ++e) {
4861 					if (stats->errnos[e] != 0)
4862 						fprintf(fp, "\t\t\t\t%s: %d\n", perf_env__arch_strerrno(trace->host->env, e + 1), stats->errnos[e]);
4863 				}
4864 			}
4865 		}
4866 	}
4867 
4868 	free(entries);
4869 	printed += fprintf(fp, "\n\n");
4870 
4871 	return printed;
4872 }
4873 
4874 static size_t thread__dump_stats(struct thread_trace *ttrace,
4875 				 struct trace *trace, int e_machine, FILE *fp)
4876 {
4877 	return syscall__dump_stats(trace, e_machine, fp, ttrace->syscall_stats);
4878 }
4879 
4880 static size_t system__dump_stats(struct trace *trace, int e_machine, FILE *fp)
4881 {
4882 	return syscall__dump_stats(trace, e_machine, fp, trace->syscall_stats);
4883 }
4884 
4885 static size_t trace__fprintf_thread(FILE *fp, struct thread *thread, struct trace *trace)
4886 {
4887 	size_t printed = 0;
4888 	struct thread_trace *ttrace = thread__priv(thread);
4889 	int e_machine = thread__e_machine(thread, trace->host);
4890 	double ratio;
4891 
4892 	if (ttrace == NULL)
4893 		return 0;
4894 
4895 	ratio = (double)ttrace->nr_events / trace->nr_events * 100.0;
4896 
4897 	printed += fprintf(fp, " %s (%d), ", thread__comm_str(thread), thread__tid(thread));
4898 	printed += fprintf(fp, "%lu events, ", ttrace->nr_events);
4899 	printed += fprintf(fp, "%.1f%%", ratio);
4900 	if (ttrace->pfmaj)
4901 		printed += fprintf(fp, ", %lu majfaults", ttrace->pfmaj);
4902 	if (ttrace->pfmin)
4903 		printed += fprintf(fp, ", %lu minfaults", ttrace->pfmin);
4904 	if (trace->sched)
4905 		printed += fprintf(fp, ", %.3f msec\n", ttrace->runtime_ms);
4906 	else if (fputc('\n', fp) != EOF)
4907 		++printed;
4908 
4909 	printed += thread__dump_stats(ttrace, trace, e_machine, fp);
4910 
4911 	return printed;
4912 }
4913 
4914 static unsigned long thread__nr_events(struct thread_trace *ttrace)
4915 {
4916 	return ttrace ? ttrace->nr_events : 0;
4917 }
4918 
4919 static int trace_nr_events_cmp(void *priv __maybe_unused,
4920 			       const struct list_head *la,
4921 			       const struct list_head *lb)
4922 {
4923 	struct thread_list *a = list_entry(la, struct thread_list, list);
4924 	struct thread_list *b = list_entry(lb, struct thread_list, list);
4925 	unsigned long a_nr_events = thread__nr_events(thread__priv(a->thread));
4926 	unsigned long b_nr_events = thread__nr_events(thread__priv(b->thread));
4927 
4928 	if (a_nr_events != b_nr_events)
4929 		return a_nr_events < b_nr_events ? -1 : 1;
4930 
4931 	/* Identical number of threads, place smaller tids first. */
4932 	return thread__tid(a->thread) < thread__tid(b->thread)
4933 		? -1
4934 		: (thread__tid(a->thread) > thread__tid(b->thread) ? 1 : 0);
4935 }
4936 
4937 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp)
4938 {
4939 	size_t printed = trace__fprintf_summary_header(fp);
4940 	LIST_HEAD(threads);
4941 
4942 	if (machine__thread_list(trace->host, &threads) == 0) {
4943 		struct thread_list *pos;
4944 
4945 		list_sort(NULL, &threads, trace_nr_events_cmp);
4946 
4947 		list_for_each_entry(pos, &threads, list)
4948 			printed += trace__fprintf_thread(fp, pos->thread, trace);
4949 	}
4950 	thread_list__delete(&threads);
4951 	return printed;
4952 }
4953 
4954 static size_t trace__fprintf_total_summary(struct trace *trace, FILE *fp)
4955 {
4956 	size_t printed = trace__fprintf_summary_header(fp);
4957 
4958 	printed += fprintf(fp, " total, ");
4959 	printed += fprintf(fp, "%lu events", trace->nr_events);
4960 
4961 	if (trace->pfmaj)
4962 		printed += fprintf(fp, ", %lu majfaults", trace->pfmaj);
4963 	if (trace->pfmin)
4964 		printed += fprintf(fp, ", %lu minfaults", trace->pfmin);
4965 	if (trace->sched)
4966 		printed += fprintf(fp, ", %.3f msec\n", trace->runtime_ms);
4967 	else if (fputc('\n', fp) != EOF)
4968 		++printed;
4969 
4970 	/* TODO: get all system e_machines. */
4971 	printed += system__dump_stats(trace, EM_HOST, fp);
4972 
4973 	return printed;
4974 }
4975 
4976 static int trace__set_duration(const struct option *opt, const char *str,
4977 			       int unset __maybe_unused)
4978 {
4979 	struct trace *trace = opt->value;
4980 
4981 	trace->duration_filter = atof(str);
4982 	return 0;
4983 }
4984 
4985 static int trace__set_filter_pids_from_option(const struct option *opt, const char *str,
4986 					      int unset __maybe_unused)
4987 {
4988 	int ret = -1;
4989 	size_t i;
4990 	struct trace *trace = opt->value;
4991 	/*
4992 	 * FIXME: introduce a intarray class, plain parse csv and create a
4993 	 * { int nr, int entries[] } struct...
4994 	 */
4995 	struct intlist *list = intlist__new(str);
4996 
4997 	if (list == NULL)
4998 		return -1;
4999 
5000 	i = trace->filter_pids.nr = intlist__nr_entries(list) + 1;
5001 	trace->filter_pids.entries = calloc(i, sizeof(pid_t));
5002 
5003 	if (trace->filter_pids.entries == NULL)
5004 		goto out;
5005 
5006 	trace->filter_pids.entries[0] = getpid();
5007 
5008 	for (i = 1; i < trace->filter_pids.nr; ++i)
5009 		trace->filter_pids.entries[i] = intlist__entry(list, i - 1)->i;
5010 
5011 	intlist__delete(list);
5012 	ret = 0;
5013 out:
5014 	return ret;
5015 }
5016 
5017 static int trace__open_output(struct trace *trace, const char *filename)
5018 {
5019 	struct stat st;
5020 
5021 	if (!stat(filename, &st) && st.st_size) {
5022 		char oldname[PATH_MAX];
5023 
5024 		scnprintf(oldname, sizeof(oldname), "%s.old", filename);
5025 		unlink(oldname);
5026 		rename(filename, oldname);
5027 	}
5028 
5029 	trace->output = fopen(filename, "w");
5030 
5031 	return trace->output == NULL ? -errno : 0;
5032 }
5033 
5034 static int parse_pagefaults(const struct option *opt, const char *str,
5035 			    int unset __maybe_unused)
5036 {
5037 	int *trace_pgfaults = opt->value;
5038 
5039 	if (strcmp(str, "all") == 0)
5040 		*trace_pgfaults |= TRACE_PFMAJ | TRACE_PFMIN;
5041 	else if (strcmp(str, "maj") == 0)
5042 		*trace_pgfaults |= TRACE_PFMAJ;
5043 	else if (strcmp(str, "min") == 0)
5044 		*trace_pgfaults |= TRACE_PFMIN;
5045 	else
5046 		return -1;
5047 
5048 	return 0;
5049 }
5050 
5051 static void evlist__set_default_evsel_handler(struct evlist *evlist, void *handler)
5052 {
5053 	struct evsel *evsel;
5054 
5055 	evlist__for_each_entry(evlist, evsel) {
5056 		if (evsel->handler == NULL)
5057 			evsel->handler = handler;
5058 	}
5059 }
5060 
5061 static void evsel__set_syscall_arg_fmt(struct evsel *evsel, const char *name)
5062 {
5063 	struct syscall_arg_fmt *fmt = evsel__syscall_arg_fmt(evsel);
5064 
5065 	if (fmt) {
5066 		const struct syscall_fmt *scfmt = syscall_fmt__find(name);
5067 
5068 		if (scfmt) {
5069 			const struct tep_event *tp_format = evsel__tp_format(evsel);
5070 
5071 			if (tp_format) {
5072 				int skip = 0;
5073 
5074 				if (strcmp(tp_format->format.fields->name, "__syscall_nr") == 0 ||
5075 				    strcmp(tp_format->format.fields->name, "nr") == 0)
5076 					++skip;
5077 
5078 				memcpy(fmt + skip, scfmt->arg,
5079 				       (tp_format->format.nr_fields - skip) * sizeof(*fmt));
5080 			}
5081 		}
5082 	}
5083 }
5084 
5085 static int evlist__set_syscall_tp_fields(struct evlist *evlist, bool *use_btf)
5086 {
5087 	struct evsel *evsel;
5088 
5089 	evlist__for_each_entry(evlist, evsel) {
5090 		const struct tep_event *tp_format;
5091 
5092 		if (evsel->priv)
5093 			continue;
5094 
5095 		tp_format = evsel__tp_format(evsel);
5096 		if (!tp_format)
5097 			continue;
5098 
5099 		if (strcmp(tp_format->system, "syscalls")) {
5100 			evsel__init_tp_arg_scnprintf(evsel, use_btf);
5101 			continue;
5102 		}
5103 
5104 		if (evsel__init_syscall_tp(evsel))
5105 			return -1;
5106 
5107 		if (!strncmp(tp_format->name, "sys_enter_", 10)) {
5108 			struct syscall_tp *sc = __evsel__syscall_tp(evsel);
5109 
5110 			if (__tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64)))
5111 				return -1;
5112 
5113 			evsel__set_syscall_arg_fmt(evsel,
5114 						   tp_format->name + sizeof("sys_enter_") - 1);
5115 		} else if (!strncmp(tp_format->name, "sys_exit_", 9)) {
5116 			struct syscall_tp *sc = __evsel__syscall_tp(evsel);
5117 
5118 			if (__tp_field__init_uint(&sc->ret, sizeof(u64),
5119 						  sc->id.offset + sizeof(u64),
5120 						  evsel->needs_swap))
5121 				return -1;
5122 
5123 			evsel__set_syscall_arg_fmt(evsel,
5124 						   tp_format->name + sizeof("sys_exit_") - 1);
5125 		}
5126 	}
5127 
5128 	return 0;
5129 }
5130 
5131 /*
5132  * XXX: Hackish, just splitting the combined -e+--event (syscalls
5133  * (raw_syscalls:{sys_{enter,exit}} + events (tracepoints, HW, SW, etc) to use
5134  * existing facilities unchanged (trace->ev_qualifier + parse_options()).
5135  *
5136  * It'd be better to introduce a parse_options() variant that would return a
5137  * list with the terms it didn't match to an event...
5138  */
5139 static int trace__parse_events_option(const struct option *opt, const char *str,
5140 				      int unset __maybe_unused)
5141 {
5142 	struct trace *trace = (struct trace *)opt->value;
5143 	const char *s = str;
5144 	char *sep = NULL, *lists[2] = { NULL, NULL, };
5145 	int len = strlen(str) + 1, err = -1, list, idx;
5146 	char *strace_groups_dir = system_path(STRACE_GROUPS_DIR);
5147 	char group_name[PATH_MAX];
5148 	const struct syscall_fmt *fmt;
5149 
5150 	if (strace_groups_dir == NULL)
5151 		return -1;
5152 
5153 	if (*s == '!') {
5154 		++s;
5155 		trace->not_ev_qualifier = true;
5156 	}
5157 
5158 	while (1) {
5159 		if ((sep = strchr(s, ',')) != NULL)
5160 			*sep = '\0';
5161 
5162 		list = 0;
5163 		/* TODO: support for more than just perf binary machine type syscalls. */
5164 		if (syscalltbl__id(EM_HOST, s) >= 0 ||
5165 		    syscalltbl__strglobmatch_first(EM_HOST, s, &idx) >= 0) {
5166 			list = 1;
5167 			goto do_concat;
5168 		}
5169 
5170 		fmt = syscall_fmt__find_by_alias(s);
5171 		if (fmt != NULL) {
5172 			list = 1;
5173 			s = fmt->name;
5174 		} else {
5175 			path__join(group_name, sizeof(group_name), strace_groups_dir, s);
5176 			if (access(group_name, R_OK) == 0)
5177 				list = 1;
5178 		}
5179 do_concat:
5180 		if (lists[list]) {
5181 			sprintf(lists[list] + strlen(lists[list]), ",%s", s);
5182 		} else {
5183 			lists[list] = malloc(len);
5184 			if (lists[list] == NULL)
5185 				goto out;
5186 			strcpy(lists[list], s);
5187 		}
5188 
5189 		if (!sep)
5190 			break;
5191 
5192 		*sep = ',';
5193 		s = sep + 1;
5194 	}
5195 
5196 	if (lists[1] != NULL) {
5197 		struct strlist_config slist_config = {
5198 			.dirname = strace_groups_dir,
5199 		};
5200 
5201 		trace->ev_qualifier = strlist__new(lists[1], &slist_config);
5202 		if (trace->ev_qualifier == NULL) {
5203 			fputs("Not enough memory to parse event qualifier", trace->output);
5204 			goto out;
5205 		}
5206 
5207 		if (trace__validate_ev_qualifier(trace))
5208 			goto out;
5209 		trace->trace_syscalls = true;
5210 	}
5211 
5212 	err = 0;
5213 
5214 	if (lists[0]) {
5215 		struct parse_events_option_args parse_events_option_args = {
5216 			.evlistp = &trace->evlist,
5217 		};
5218 		struct option o = {
5219 			.value = &parse_events_option_args,
5220 		};
5221 		err = parse_events_option(&o, lists[0], 0);
5222 	}
5223 out:
5224 	free(strace_groups_dir);
5225 	free(lists[0]);
5226 	free(lists[1]);
5227 	if (sep)
5228 		*sep = ',';
5229 
5230 	return err;
5231 }
5232 
5233 static int trace__parse_cgroups(const struct option *opt, const char *str, int unset)
5234 {
5235 	struct trace *trace = opt->value;
5236 
5237 	if (!list_empty(&trace->evlist->core.entries)) {
5238 		struct option o = {
5239 			.value = &trace->evlist,
5240 		};
5241 		return parse_cgroups(&o, str, unset);
5242 	}
5243 	trace->cgroup = evlist__findnew_cgroup(trace->evlist, str);
5244 
5245 	return 0;
5246 }
5247 
5248 static int trace__parse_summary_mode(const struct option *opt, const char *str,
5249 				     int unset __maybe_unused)
5250 {
5251 	struct trace *trace = opt->value;
5252 
5253 	if (!strcmp(str, "thread")) {
5254 		trace->summary_mode = SUMMARY__BY_THREAD;
5255 	} else if (!strcmp(str, "total")) {
5256 		trace->summary_mode = SUMMARY__BY_TOTAL;
5257 	} else if (!strcmp(str, "cgroup")) {
5258 		trace->summary_mode = SUMMARY__BY_CGROUP;
5259 	} else {
5260 		pr_err("Unknown summary mode: %s\n", str);
5261 		return -1;
5262 	}
5263 
5264 	return 0;
5265 }
5266 
5267 static int trace__config(const char *var, const char *value, void *arg)
5268 {
5269 	struct trace *trace = arg;
5270 	int err = 0;
5271 
5272 	if (!strcmp(var, "trace.add_events")) {
5273 		trace->perfconfig_events = strdup(value);
5274 		if (trace->perfconfig_events == NULL) {
5275 			pr_err("Not enough memory for %s\n", "trace.add_events");
5276 			return -1;
5277 		}
5278 	} else if (!strcmp(var, "trace.show_timestamp")) {
5279 		trace->show_tstamp = perf_config_bool(var, value);
5280 	} else if (!strcmp(var, "trace.show_duration")) {
5281 		trace->show_duration = perf_config_bool(var, value);
5282 	} else if (!strcmp(var, "trace.show_arg_names")) {
5283 		trace->show_arg_names = perf_config_bool(var, value);
5284 		if (!trace->show_arg_names)
5285 			trace->show_zeros = true;
5286 	} else if (!strcmp(var, "trace.show_zeros")) {
5287 		bool new_show_zeros = perf_config_bool(var, value);
5288 		if (!trace->show_arg_names && !new_show_zeros) {
5289 			pr_warning("trace.show_zeros has to be set when trace.show_arg_names=no\n");
5290 			goto out;
5291 		}
5292 		trace->show_zeros = new_show_zeros;
5293 	} else if (!strcmp(var, "trace.show_prefix")) {
5294 		trace->show_string_prefix = perf_config_bool(var, value);
5295 	} else if (!strcmp(var, "trace.no_inherit")) {
5296 		trace->opts.no_inherit = perf_config_bool(var, value);
5297 	} else if (!strcmp(var, "trace.args_alignment")) {
5298 		int args_alignment = 0;
5299 		if (perf_config_int(&args_alignment, var, value) == 0)
5300 			trace->args_alignment = args_alignment;
5301 	} else if (!strcmp(var, "trace.tracepoint_beautifiers")) {
5302 		if (strcasecmp(value, "libtraceevent") == 0)
5303 			trace->libtraceevent_print = true;
5304 		else if (strcasecmp(value, "libbeauty") == 0)
5305 			trace->libtraceevent_print = false;
5306 	}
5307 out:
5308 	return err;
5309 }
5310 
5311 static void trace__exit(struct trace *trace)
5312 {
5313 	thread__zput(trace->current);
5314 	strlist__delete(trace->ev_qualifier);
5315 	zfree(&trace->ev_qualifier_ids.entries);
5316 	if (trace->syscalls.table) {
5317 		for (size_t i = 0; i < trace->syscalls.table_size; i++)
5318 			syscall__delete(trace->syscalls.table[i]);
5319 		zfree(&trace->syscalls.table);
5320 	}
5321 	zfree(&trace->perfconfig_events);
5322 	evlist__delete(trace->evlist);
5323 	trace->evlist = NULL;
5324 	ordered_events__free(&trace->oe.data);
5325 #ifdef HAVE_LIBBPF_SUPPORT
5326 	btf__free(trace->btf);
5327 	trace->btf = NULL;
5328 #endif
5329 }
5330 
5331 int cmd_trace(int argc, const char **argv)
5332 {
5333 	const char *trace_usage[] = {
5334 		"perf trace [<options>] [<command>]",
5335 		"perf trace [<options>] -- <command> [<options>]",
5336 		"perf trace record [<options>] [<command>]",
5337 		"perf trace record [<options>] -- <command> [<options>]",
5338 		NULL
5339 	};
5340 	struct trace trace = {
5341 		.opts = {
5342 			.target = {
5343 				.uses_mmap = true,
5344 			},
5345 			.user_freq     = UINT_MAX,
5346 			.user_interval = ULLONG_MAX,
5347 			.no_buffering  = true,
5348 			.mmap_pages    = UINT_MAX,
5349 		},
5350 		.output = stderr,
5351 		.show_comm = true,
5352 		.show_tstamp = true,
5353 		.show_duration = true,
5354 		.show_arg_names = true,
5355 		.args_alignment = 70,
5356 		.trace_syscalls = false,
5357 		.kernel_syscallchains = false,
5358 		.max_stack = UINT_MAX,
5359 		.max_events = ULONG_MAX,
5360 	};
5361 	const char *output_name = NULL;
5362 	const struct option trace_options[] = {
5363 	OPT_CALLBACK('e', "event", &trace, "event",
5364 		     "event/syscall selector. use 'perf list' to list available events",
5365 		     trace__parse_events_option),
5366 	OPT_CALLBACK(0, "filter", &trace.evlist, "filter",
5367 		     "event filter", parse_filter),
5368 	OPT_BOOLEAN(0, "comm", &trace.show_comm,
5369 		    "show the thread COMM next to its id"),
5370 	OPT_BOOLEAN(0, "tool_stats", &trace.show_tool_stats, "show tool stats"),
5371 	OPT_CALLBACK(0, "expr", &trace, "expr", "list of syscalls/events to trace",
5372 		     trace__parse_events_option),
5373 	OPT_STRING('o', "output", &output_name, "file", "output file name"),
5374 	OPT_STRING('i', "input", &input_name, "file", "Analyze events in file"),
5375 	OPT_STRING('p', "pid", &trace.opts.target.pid, "pid",
5376 		    "trace events on existing process id"),
5377 	OPT_STRING('t', "tid", &trace.opts.target.tid, "tid",
5378 		    "trace events on existing thread id"),
5379 	OPT_CALLBACK(0, "filter-pids", &trace, "CSV list of pids",
5380 		     "pids to filter (by the kernel)", trace__set_filter_pids_from_option),
5381 	OPT_BOOLEAN('a', "all-cpus", &trace.opts.target.system_wide,
5382 		    "system-wide collection from all CPUs"),
5383 	OPT_STRING('C', "cpu", &trace.opts.target.cpu_list, "cpu",
5384 		    "list of cpus to monitor"),
5385 	OPT_BOOLEAN(0, "no-inherit", &trace.opts.no_inherit,
5386 		    "child tasks do not inherit counters"),
5387 	OPT_CALLBACK('m', "mmap-pages", &trace.opts.mmap_pages, "pages",
5388 		     "number of mmap data pages", evlist__parse_mmap_pages),
5389 	OPT_STRING('u', "uid", &trace.uid_str, "user", "user to profile"),
5390 	OPT_CALLBACK(0, "duration", &trace, "float",
5391 		     "show only events with duration > N.M ms",
5392 		     trace__set_duration),
5393 	OPT_BOOLEAN(0, "sched", &trace.sched, "show blocking scheduler events"),
5394 	OPT_INCR('v', "verbose", &verbose, "be more verbose"),
5395 	OPT_BOOLEAN('T', "time", &trace.full_time,
5396 		    "Show full timestamp, not time relative to first start"),
5397 	OPT_BOOLEAN(0, "failure", &trace.failure_only,
5398 		    "Show only syscalls that failed"),
5399 	OPT_BOOLEAN('s', "summary", &trace.summary_only,
5400 		    "Show only syscall summary with statistics"),
5401 	OPT_BOOLEAN('S', "with-summary", &trace.summary,
5402 		    "Show all syscalls and summary with statistics"),
5403 	OPT_BOOLEAN(0, "errno-summary", &trace.errno_summary,
5404 		    "Show errno stats per syscall, use with -s or -S"),
5405 	OPT_CALLBACK(0, "summary-mode", &trace, "mode",
5406 		     "How to show summary: select thread (default), total or cgroup",
5407 		     trace__parse_summary_mode),
5408 	OPT_CALLBACK_DEFAULT('F', "pf", &trace.trace_pgfaults, "all|maj|min",
5409 		     "Trace pagefaults", parse_pagefaults, "maj"),
5410 	OPT_BOOLEAN(0, "syscalls", &trace.trace_syscalls, "Trace syscalls"),
5411 	OPT_BOOLEAN('f', "force", &trace.force, "don't complain, do it"),
5412 	OPT_CALLBACK(0, "call-graph", &trace.opts,
5413 		     "record_mode[,record_size]", record_callchain_help,
5414 		     &record_parse_callchain_opt),
5415 	OPT_BOOLEAN(0, "libtraceevent_print", &trace.libtraceevent_print,
5416 		    "Use libtraceevent to print the tracepoint arguments."),
5417 	OPT_BOOLEAN(0, "kernel-syscall-graph", &trace.kernel_syscallchains,
5418 		    "Show the kernel callchains on the syscall exit path"),
5419 	OPT_ULONG(0, "max-events", &trace.max_events,
5420 		"Set the maximum number of events to print, exit after that is reached. "),
5421 	OPT_UINTEGER(0, "min-stack", &trace.min_stack,
5422 		     "Set the minimum stack depth when parsing the callchain, "
5423 		     "anything below the specified depth will be ignored."),
5424 	OPT_UINTEGER(0, "max-stack", &trace.max_stack,
5425 		     "Set the maximum stack depth when parsing the callchain, "
5426 		     "anything beyond the specified depth will be ignored. "
5427 		     "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
5428 	OPT_BOOLEAN(0, "sort-events", &trace.sort_events,
5429 			"Sort batch of events before processing, use if getting out of order events"),
5430 	OPT_BOOLEAN(0, "print-sample", &trace.print_sample,
5431 			"print the PERF_RECORD_SAMPLE PERF_SAMPLE_ info, for debugging"),
5432 	OPT_UINTEGER(0, "proc-map-timeout", &proc_map_timeout,
5433 			"per thread proc mmap processing timeout in ms"),
5434 	OPT_CALLBACK('G', "cgroup", &trace, "name", "monitor event in cgroup name only",
5435 		     trace__parse_cgroups),
5436 	OPT_INTEGER('D', "delay", &trace.opts.target.initial_delay,
5437 		     "ms to wait before starting measurement after program "
5438 		     "start"),
5439 	OPT_BOOLEAN(0, "force-btf", &trace.force_btf, "Prefer btf_dump general pretty printer"
5440 		       "to customized ones"),
5441 	OPT_BOOLEAN(0, "bpf-summary", &trace.summary_bpf, "Summary syscall stats in BPF"),
5442 	OPTS_EVSWITCH(&trace.evswitch),
5443 	OPT_END()
5444 	};
5445 	bool __maybe_unused max_stack_user_set = true;
5446 	bool mmap_pages_user_set = true;
5447 	struct evsel *evsel;
5448 	const char * const trace_subcommands[] = { "record", NULL };
5449 	int err = -1;
5450 	char bf[BUFSIZ];
5451 	struct sigaction sigchld_act;
5452 
5453 	signal(SIGSEGV, sighandler_dump_stack);
5454 	signal(SIGFPE, sighandler_dump_stack);
5455 	signal(SIGINT, sighandler_interrupt);
5456 
5457 	memset(&sigchld_act, 0, sizeof(sigchld_act));
5458 	sigchld_act.sa_flags = SA_SIGINFO;
5459 	sigchld_act.sa_sigaction = sighandler_chld;
5460 	sigaction(SIGCHLD, &sigchld_act, NULL);
5461 
5462 	ordered_events__init(&trace.oe.data, ordered_events__deliver_event, &trace);
5463 	ordered_events__set_copy_on_queue(&trace.oe.data, true);
5464 
5465 	trace.evlist = evlist__new();
5466 
5467 	if (trace.evlist == NULL) {
5468 		pr_err("Not enough memory to run!\n");
5469 		err = -ENOMEM;
5470 		goto out;
5471 	}
5472 
5473 	/*
5474 	 * Parsing .perfconfig may entail creating a BPF event, that may need
5475 	 * to create BPF maps, so bump RLIM_MEMLOCK as the default 64K setting
5476 	 * is too small. This affects just this process, not touching the
5477 	 * global setting. If it fails we'll get something in 'perf trace -v'
5478 	 * to help diagnose the problem.
5479 	 */
5480 	rlimit__bump_memlock();
5481 
5482 	err = perf_config(trace__config, &trace);
5483 	if (err)
5484 		goto out;
5485 
5486 	argc = parse_options_subcommand(argc, argv, trace_options, trace_subcommands,
5487 				 trace_usage, PARSE_OPT_STOP_AT_NON_OPTION);
5488 
5489 	/*
5490 	 * Here we already passed thru trace__parse_events_option() and it has
5491 	 * already figured out if -e syscall_name, if not but if --event
5492 	 * foo:bar was used, the user is interested _just_ in those, say,
5493 	 * tracepoint events, not in the strace-like syscall-name-based mode.
5494 	 *
5495 	 * This is important because we need to check if strace-like mode is
5496 	 * needed to decided if we should filter out the eBPF
5497 	 * __augmented_syscalls__ code, if it is in the mix, say, via
5498 	 * .perfconfig trace.add_events, and filter those out.
5499 	 */
5500 	if (!trace.trace_syscalls && !trace.trace_pgfaults &&
5501 	    trace.evlist->core.nr_entries == 0 /* Was --events used? */) {
5502 		trace.trace_syscalls = true;
5503 	}
5504 	/*
5505 	 * Now that we have --verbose figured out, lets see if we need to parse
5506 	 * events from .perfconfig, so that if those events fail parsing, say some
5507 	 * BPF program fails, then we'll be able to use --verbose to see what went
5508 	 * wrong in more detail.
5509 	 */
5510 	if (trace.perfconfig_events != NULL) {
5511 		struct parse_events_error parse_err;
5512 
5513 		parse_events_error__init(&parse_err);
5514 		err = parse_events(trace.evlist, trace.perfconfig_events, &parse_err);
5515 		if (err)
5516 			parse_events_error__print(&parse_err, trace.perfconfig_events);
5517 		parse_events_error__exit(&parse_err);
5518 		if (err)
5519 			goto out;
5520 	}
5521 
5522 	if ((nr_cgroups || trace.cgroup) && !trace.opts.target.system_wide) {
5523 		usage_with_options_msg(trace_usage, trace_options,
5524 				       "cgroup monitoring only available in system-wide mode");
5525 	}
5526 
5527 	if (!trace.trace_syscalls)
5528 		goto skip_augmentation;
5529 
5530 	if ((argc >= 1) && (strcmp(argv[0], "record") == 0)) {
5531 		pr_debug("Syscall augmentation fails with record, disabling augmentation");
5532 		goto skip_augmentation;
5533 	}
5534 
5535 	if (trace.summary_bpf) {
5536 		if (!trace.opts.target.system_wide) {
5537 			/* TODO: Add filters in the BPF to support other targets. */
5538 			pr_err("Error: --bpf-summary only works for system-wide mode.\n");
5539 			goto out;
5540 		}
5541 		if (trace.summary_only)
5542 			goto skip_augmentation;
5543 	}
5544 
5545 	err = augmented_syscalls__prepare();
5546 	if (err < 0)
5547 		goto skip_augmentation;
5548 
5549 	trace__add_syscall_newtp(&trace);
5550 
5551 	err = augmented_syscalls__create_bpf_output(trace.evlist);
5552 	if (err == 0)
5553 		trace.syscalls.events.bpf_output = evlist__last(trace.evlist);
5554 
5555 skip_augmentation:
5556 	err = -1;
5557 
5558 	if (trace.trace_pgfaults) {
5559 		trace.opts.sample_address = true;
5560 		trace.opts.sample_time = true;
5561 	}
5562 
5563 	if (trace.opts.mmap_pages == UINT_MAX)
5564 		mmap_pages_user_set = false;
5565 
5566 	if (trace.max_stack == UINT_MAX) {
5567 		trace.max_stack = input_name ? PERF_MAX_STACK_DEPTH : sysctl__max_stack();
5568 		max_stack_user_set = false;
5569 	}
5570 
5571 #ifdef HAVE_DWARF_UNWIND_SUPPORT
5572 	if ((trace.min_stack || max_stack_user_set) && !callchain_param.enabled) {
5573 		record_opts__parse_callchain(&trace.opts, &callchain_param, "dwarf", false);
5574 	}
5575 #endif
5576 
5577 	if (callchain_param.enabled) {
5578 		if (!mmap_pages_user_set && geteuid() == 0)
5579 			trace.opts.mmap_pages = perf_event_mlock_kb_in_pages() * 4;
5580 
5581 		symbol_conf.use_callchain = true;
5582 	}
5583 
5584 	if (trace.evlist->core.nr_entries > 0) {
5585 		bool use_btf = false;
5586 
5587 		evlist__set_default_evsel_handler(trace.evlist, trace__event_handler);
5588 		if (evlist__set_syscall_tp_fields(trace.evlist, &use_btf)) {
5589 			perror("failed to set syscalls:* tracepoint fields");
5590 			goto out;
5591 		}
5592 
5593 		if (use_btf)
5594 			trace__load_vmlinux_btf(&trace);
5595 	}
5596 
5597 	/*
5598 	 * If we are augmenting syscalls, then combine what we put in the
5599 	 * __augmented_syscalls__ BPF map with what is in the
5600 	 * syscalls:sys_exit_FOO tracepoints, i.e. just like we do without BPF,
5601 	 * combining raw_syscalls:sys_enter with raw_syscalls:sys_exit.
5602 	 *
5603 	 * We'll switch to look at two BPF maps, one for sys_enter and the
5604 	 * other for sys_exit when we start augmenting the sys_exit paths with
5605 	 * buffers that are being copied from kernel to userspace, think 'read'
5606 	 * syscall.
5607 	 */
5608 	if (trace.syscalls.events.bpf_output) {
5609 		evlist__for_each_entry(trace.evlist, evsel) {
5610 			bool raw_syscalls_sys_exit = evsel__name_is(evsel, "raw_syscalls:sys_exit");
5611 
5612 			if (raw_syscalls_sys_exit) {
5613 				trace.raw_augmented_syscalls = true;
5614 				goto init_augmented_syscall_tp;
5615 			}
5616 
5617 			if (trace.syscalls.events.bpf_output->priv == NULL &&
5618 			    strstr(evsel__name(evsel), "syscalls:sys_enter")) {
5619 				struct evsel *augmented = trace.syscalls.events.bpf_output;
5620 				if (evsel__init_augmented_syscall_tp(augmented, evsel) ||
5621 				    evsel__init_augmented_syscall_tp_args(augmented))
5622 					goto out;
5623 				/*
5624 				 * Augmented is __augmented_syscalls__ BPF_OUTPUT event
5625 				 * Above we made sure we can get from the payload the tp fields
5626 				 * that we get from syscalls:sys_enter tracefs format file.
5627 				 */
5628 				augmented->handler = trace__sys_enter;
5629 				/*
5630 				 * Now we do the same for the *syscalls:sys_enter event so that
5631 				 * if we handle it directly, i.e. if the BPF prog returns 0 so
5632 				 * as not to filter it, then we'll handle it just like we would
5633 				 * for the BPF_OUTPUT one:
5634 				 */
5635 				if (evsel__init_augmented_syscall_tp(evsel, evsel) ||
5636 				    evsel__init_augmented_syscall_tp_args(evsel))
5637 					goto out;
5638 				evsel->handler = trace__sys_enter;
5639 			}
5640 
5641 			if (strstarts(evsel__name(evsel), "syscalls:sys_exit_")) {
5642 				struct syscall_tp *sc;
5643 init_augmented_syscall_tp:
5644 				if (evsel__init_augmented_syscall_tp(evsel, evsel))
5645 					goto out;
5646 				sc = __evsel__syscall_tp(evsel);
5647 				/*
5648 				 * For now with BPF raw_augmented we hook into
5649 				 * raw_syscalls:sys_enter and there we get all
5650 				 * 6 syscall args plus the tracepoint common
5651 				 * fields and the syscall_nr (another long).
5652 				 * So we check if that is the case and if so
5653 				 * don't look after the sc->args_size but
5654 				 * always after the full raw_syscalls:sys_enter
5655 				 * payload, which is fixed.
5656 				 *
5657 				 * We'll revisit this later to pass
5658 				 * s->args_size to the BPF augmenter (now
5659 				 * tools/perf/examples/bpf/augmented_raw_syscalls.c,
5660 				 * so that it copies only what we need for each
5661 				 * syscall, like what happens when we use
5662 				 * syscalls:sys_enter_NAME, so that we reduce
5663 				 * the kernel/userspace traffic to just what is
5664 				 * needed for each syscall.
5665 				 */
5666 				if (trace.raw_augmented_syscalls)
5667 					trace.raw_augmented_syscalls_args_size = (6 + 1) * sizeof(long) + sc->id.offset;
5668 				evsel__init_augmented_syscall_tp_ret(evsel);
5669 				evsel->handler = trace__sys_exit;
5670 			}
5671 		}
5672 	}
5673 
5674 	if ((argc >= 1) && (strcmp(argv[0], "record") == 0)) {
5675 		err = trace__record(&trace, argc-1, &argv[1]);
5676 		goto out;
5677 	}
5678 
5679 	/* Using just --errno-summary will trigger --summary */
5680 	if (trace.errno_summary && !trace.summary && !trace.summary_only)
5681 		trace.summary_only = true;
5682 
5683 	/* summary_only implies summary option, but don't overwrite summary if set */
5684 	if (trace.summary_only)
5685 		trace.summary = trace.summary_only;
5686 
5687 	/* Keep exited threads, otherwise information might be lost for summary */
5688 	if (trace.summary) {
5689 		symbol_conf.keep_exited_threads = true;
5690 		if (trace.summary_mode == SUMMARY__NONE)
5691 			trace.summary_mode = SUMMARY__BY_THREAD;
5692 
5693 		if (!trace.summary_bpf && trace.summary_mode == SUMMARY__BY_CGROUP) {
5694 			pr_err("Error: --summary-mode=cgroup only works with --bpf-summary\n");
5695 			err = -EINVAL;
5696 			goto out;
5697 		}
5698 	}
5699 
5700 	if (output_name != NULL) {
5701 		err = trace__open_output(&trace, output_name);
5702 		if (err < 0) {
5703 			perror("failed to create output file");
5704 			goto out;
5705 		}
5706 	}
5707 
5708 	err = evswitch__init(&trace.evswitch, trace.evlist, stderr);
5709 	if (err)
5710 		goto out_close;
5711 
5712 	err = target__validate(&trace.opts.target);
5713 	if (err) {
5714 		target__strerror(&trace.opts.target, err, bf, sizeof(bf));
5715 		fprintf(trace.output, "%s", bf);
5716 		goto out_close;
5717 	}
5718 
5719 	if (trace.uid_str) {
5720 		uid_t uid = parse_uid(trace.uid_str);
5721 
5722 		if (uid == UINT_MAX) {
5723 			ui__error("Invalid User: %s", trace.uid_str);
5724 			err = -EINVAL;
5725 			goto out_close;
5726 		}
5727 		err = parse_uid_filter(trace.evlist, uid);
5728 		if (err)
5729 			goto out_close;
5730 
5731 		trace.opts.target.system_wide = true;
5732 	}
5733 
5734 	if (!argc && target__none(&trace.opts.target))
5735 		trace.opts.target.system_wide = true;
5736 
5737 	if (input_name)
5738 		err = trace__replay(&trace);
5739 	else
5740 		err = trace__run(&trace, argc, argv);
5741 
5742 out_close:
5743 	if (output_name != NULL)
5744 		fclose(trace.output);
5745 out:
5746 	trace__exit(&trace);
5747 	augmented_syscalls__cleanup();
5748 	return err;
5749 }
5750