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