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