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