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