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