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