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