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