blob: 8b2ca3587c091f6e5ddb80f64e26e7bac235047c [file] [log] [blame]
Alexey Ivanovcc01a9c2019-01-16 09:50:46 -08001#!/usr/bin/python
Sasha Goldshtein38847f02016-02-22 02:19:24 -08002#
3# trace Trace a function and print a trace message based on its
4# parameters, with an optional filter.
5#
yonghong-songc2a530b2019-10-20 09:35:55 -07006# usage: trace [-h] [-p PID] [-L TID] [-v] [-Z STRING_SIZE] [-S] [-c cgroup_path]
vijunag9924e642019-01-23 12:35:33 +05307# [-M MAX_EVENTS] [-s SYMBOLFILES] [-T] [-t] [-K] [-U] [-a] [-I header]
Mark Draytonaa6c9162016-11-03 15:36:29 +00008# probe [probe ...]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -08009#
Sasha Goldshtein38847f02016-02-22 02:19:24 -080010# Licensed under the Apache License, Version 2.0 (the "License")
11# Copyright (C) 2016 Sasha Goldshtein.
12
Teng Qinc200b6c2017-12-16 00:15:55 -080013from __future__ import print_function
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +030014from bcc import BPF, USDT
Teng Qin6b0ed372016-09-29 21:30:13 -070015from functools import partial
Sasha Goldshtein38847f02016-02-22 02:19:24 -080016from time import sleep, strftime
Maik Riechert3a0d3c42019-05-23 17:57:10 +010017import time
Sasha Goldshtein38847f02016-02-22 02:19:24 -080018import argparse
19import re
20import ctypes as ct
21import os
22import traceback
23import sys
24
Sasha Goldshtein38847f02016-02-22 02:19:24 -080025class Probe(object):
26 probe_count = 0
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070027 streq_index = 0
Sasha Goldshtein38847f02016-02-22 02:19:24 -080028 max_events = None
29 event_count = 0
30 first_ts = 0
Maik Riechert3a0d3c42019-05-23 17:57:10 +010031 first_ts_real = None
Teng Qinc200b6c2017-12-16 00:15:55 -080032 print_time = False
Maik Riechert3a0d3c42019-05-23 17:57:10 +010033 print_unix_timestamp = False
Sasha Goldshtein38847f02016-02-22 02:19:24 -080034 use_localtime = True
Teng Qinc200b6c2017-12-16 00:15:55 -080035 time_field = False
36 print_cpu = False
Mirek Klimose5382282018-01-26 14:52:50 -080037 print_address = False
Mark Draytonaa6c9162016-11-03 15:36:29 +000038 tgid = -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070039 pid = -1
Mark Drayton5f5687e2017-02-20 18:13:03 +000040 page_cnt = None
vijunag9924e642019-01-23 12:35:33 +053041 build_id_enabled = False
Sasha Goldshtein38847f02016-02-22 02:19:24 -080042
43 @classmethod
44 def configure(cls, args):
45 cls.max_events = args.max_events
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +000046 cls.print_time = args.timestamp or args.time
Maik Riechert3a0d3c42019-05-23 17:57:10 +010047 cls.print_unix_timestamp = args.unix_timestamp
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +000048 cls.use_localtime = not args.timestamp
Teng Qinc200b6c2017-12-16 00:15:55 -080049 cls.time_field = cls.print_time and (not cls.use_localtime)
50 cls.print_cpu = args.print_cpu
Mirek Klimose5382282018-01-26 14:52:50 -080051 cls.print_address = args.address
Sasha Goldshtein60c41922017-02-09 04:19:53 -050052 cls.first_ts = BPF.monotonic_time()
Maik Riechert3a0d3c42019-05-23 17:57:10 +010053 cls.first_ts_real = time.time()
Mark Draytonaa6c9162016-11-03 15:36:29 +000054 cls.tgid = args.tgid or -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070055 cls.pid = args.pid or -1
Mark Drayton5f5687e2017-02-20 18:13:03 +000056 cls.page_cnt = args.buffer_pages
Nikita V. Shirokov3953c702018-07-27 16:13:47 -070057 cls.bin_cmp = args.bin_cmp
vijunag9924e642019-01-23 12:35:33 +053058 cls.build_id_enabled = args.sym_file_list is not None
Sasha Goldshtein38847f02016-02-22 02:19:24 -080059
yonghong-songc2a530b2019-10-20 09:35:55 -070060 def __init__(self, probe, string_size, kernel_stack, user_stack,
tty55cf529e2019-12-06 17:52:56 +080061 cgroup_map_name, name, msg_filter):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +030062 self.usdt = None
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070063 self.streq_functions = ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -080064 self.raw_probe = probe
65 self.string_size = string_size
Teng Qin6b0ed372016-09-29 21:30:13 -070066 self.kernel_stack = kernel_stack
67 self.user_stack = user_stack
Sasha Goldshtein38847f02016-02-22 02:19:24 -080068 Probe.probe_count += 1
69 self._parse_probe()
70 self.probe_num = Probe.probe_count
71 self.probe_name = "probe_%s_%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070072 (self._display_function(), self.probe_num)
Paul Chaignon956ca1c2017-03-04 20:07:56 +010073 self.probe_name = re.sub(r'[^A-Za-z0-9_]', '_',
74 self.probe_name)
yonghong-songc2a530b2019-10-20 09:35:55 -070075 self.cgroup_map_name = cgroup_map_name
tty59ce7b7e2019-12-04 22:49:38 +080076 self.name = name
tty55cf529e2019-12-06 17:52:56 +080077 self.msg_filter = msg_filter
yonghong-song2da34262018-06-13 06:12:22 -070078 # compiler can generate proper codes for function
79 # signatures with "syscall__" prefix
80 if self.is_syscall_kprobe:
81 self.probe_name = "syscall__" + self.probe_name[6:]
82
Sasha Goldshtein38847f02016-02-22 02:19:24 -080083 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070084 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
85 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080086 self.types, self.values)
87
88 def is_default_action(self):
89 return self.python_format == ""
90
91 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070092 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080093 (self.raw_probe, error))
94
95 def _parse_probe(self):
96 text = self.raw_probe
97
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000098 # There might be a function signature preceding the actual
99 # filter/print part, or not. Find the probe specifier first --
100 # it ends with either a space or an open paren ( for the
101 # function signature part.
102 # opt. signature
103 # probespec | rest
104 # --------- ---------- --
105 (spec, sig, rest) = re.match(r'([^ \t\(]+)(\([^\(]*\))?(.*)',
106 text).groups()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800107
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000108 self._parse_spec(spec)
Paul Chaignon956ca1c2017-03-04 20:07:56 +0100109 # Remove the parens
110 self.signature = sig[1:-1] if sig else None
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000111 if self.signature and self.probe_type in ['u', 't']:
112 self._bail("USDT and tracepoint probes can't have " +
113 "a function signature; use arg1, arg2, " +
114 "... instead")
115
116 text = rest.lstrip()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800117 # If we now have a (, wait for the balanced closing ) and that
118 # will be the predicate
119 self.filter = None
120 if len(text) > 0 and text[0] == "(":
121 balance = 1
122 for i in range(1, len(text)):
123 if text[i] == "(":
124 balance += 1
125 if text[i] == ")":
126 balance -= 1
127 if balance == 0:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300128 self._parse_filter(text[:i + 1])
129 text = text[i + 1:]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800130 break
131 if self.filter is None:
132 self._bail("unmatched end of predicate")
133
134 if self.filter is None:
135 self.filter = "1"
136
137 # The remainder of the text is the printf action
138 self._parse_action(text.lstrip())
139
140 def _parse_spec(self, spec):
141 parts = spec.split(":")
142 # Two special cases: 'func' means 'p::func', 'lib:func' means
143 # 'p:lib:func'. Other combinations need to provide an empty
144 # value between delimiters, e.g. 'r::func' for a kretprobe on
145 # the function func.
146 if len(parts) == 1:
147 parts = ["p", "", parts[0]]
148 elif len(parts) == 2:
149 parts = ["p", parts[0], parts[1]]
150 if len(parts[0]) == 0:
151 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700152 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800153 self.probe_type = parts[0]
154 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700155 self._bail("probe type must be '', 'p', 't', 'r', " +
156 "or 'u', but got '%s'" % parts[0])
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800157 if self.probe_type == "t":
158 self.tp_category = parts[1]
159 self.tp_event = parts[2]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800160 self.library = "" # kernel
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300161 self.function = "" # from TRACEPOINT_PROBE
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700162 elif self.probe_type == "u":
vkhromov5a2b39e2017-07-14 20:42:29 +0100163 self.library = ':'.join(parts[1:-1])
164 self.usdt_name = parts[-1]
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700165 self.function = "" # no function, just address
166 # We will discover the USDT provider by matching on
167 # the USDT name in the specified library
168 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800169 else:
vkhromov5a2b39e2017-07-14 20:42:29 +0100170 self.library = ':'.join(parts[1:-1])
171 self.function = parts[-1]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800172
yonghong-song2da34262018-06-13 06:12:22 -0700173 # only x64 syscalls needs checking, no other syscall wrapper yet.
174 self.is_syscall_kprobe = False
175 if self.probe_type == "p" and len(self.library) == 0 and \
176 self.function[:10] == "__x64_sys_":
177 self.is_syscall_kprobe = True
178
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700179 def _find_usdt_probe(self):
Sasha Goldshteindd045362016-11-13 05:07:38 -0800180 target = Probe.pid if Probe.pid and Probe.pid != -1 \
181 else Probe.tgid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000182 self.usdt = USDT(path=self.library, pid=target)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300183 for probe in self.usdt.enumerate_probes():
Javier Honduvilla Coto1ef82e22018-04-19 14:14:24 +0200184 if probe.name == self.usdt_name.encode('ascii'):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300185 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700186 self._bail("unrecognized USDT probe %s" % self.usdt_name)
187
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800188 def _parse_filter(self, filt):
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700189 self.filter = self._rewrite_expr(filt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800190
191 def _parse_types(self, fmt):
192 for match in re.finditer(
yonghong-songf7202572018-09-19 08:50:59 -0700193 r'[^%]%(s|u|d|lu|llu|ld|lld|hu|hd|x|lx|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800194 self.types.append(match.group(1))
yonghong-songf7202572018-09-19 08:50:59 -0700195 fmt = re.sub(r'([^%]%)(u|d|lu|llu|ld|lld|hu|hd)', r'\1d', fmt)
196 fmt = re.sub(r'([^%]%)(x|lx|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700197 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800198 self.python_format = fmt.strip('"')
199
200 def _parse_action(self, action):
201 self.values = []
202 self.types = []
203 self.python_format = ""
204 if len(action) == 0:
205 return
206
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800207 action = action.strip()
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700208 match = re.search(r'(\".*?\"),?(.*)', action)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800209 if match is None:
210 self._bail("expected format string in \"s")
211
212 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800213 self._parse_types(self.raw_format)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700214 for part in re.split('(?<!"),', match.group(2)):
215 part = self._rewrite_expr(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800216 if len(part) > 0:
217 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800218
yonghong-song2da34262018-06-13 06:12:22 -0700219 aliases_arg = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530220 "arg1": "PT_REGS_PARM1(ctx)",
221 "arg2": "PT_REGS_PARM2(ctx)",
222 "arg3": "PT_REGS_PARM3(ctx)",
223 "arg4": "PT_REGS_PARM4(ctx)",
224 "arg5": "PT_REGS_PARM5(ctx)",
225 "arg6": "PT_REGS_PARM6(ctx)",
yonghong-song2da34262018-06-13 06:12:22 -0700226 }
227
228 aliases_indarg = {
Prashant Bhole05765ee2018-12-28 01:47:56 +0900229 "arg1": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700230 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM1(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800231 "arg2": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700232 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM2(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800233 "arg3": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700234 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM3(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800235 "arg4": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700236 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM4(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800237 "arg5": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700238 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM5(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800239 "arg6": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700240 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM6(_ctx))); _val;})",
241 }
242
243 aliases_common = {
244 "retval": "PT_REGS_RC(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800245 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
246 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
247 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
248 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
Yonghong Songf92fef22018-01-24 20:51:46 -0800249 "$cpu": "bpf_get_smp_processor_id()",
250 "$task" : "((struct task_struct *)bpf_get_current_task())"
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800251 }
252
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700253 def _generate_streq_function(self, string):
254 fname = "streq_%d" % Probe.streq_index
255 Probe.streq_index += 1
256 self.streq_functions += """
Sasha Goldshteinb9aec342017-01-16 18:41:22 +0000257static inline bool %s(char const *ignored, uintptr_t str) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700258 char needle[] = %s;
259 char haystack[sizeof(needle)];
260 bpf_probe_read(&haystack, sizeof(haystack), (void *)str);
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000261 for (int i = 0; i < sizeof(needle) - 1; ++i) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700262 if (needle[i] != haystack[i]) {
263 return false;
264 }
265 }
266 return true;
267}
268 """ % (fname, string)
269 return fname
270
271 def _rewrite_expr(self, expr):
yonghong-song2da34262018-06-13 06:12:22 -0700272 if self.is_syscall_kprobe:
273 for alias, replacement in Probe.aliases_indarg.items():
274 expr = expr.replace(alias, replacement)
275 else:
276 for alias, replacement in Probe.aliases_arg.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700277 # For USDT probes, we replace argN values with the
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300278 # actual arguments for that probe obtained using
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300279 # bpf_readarg_N macros emitted at BPF construction.
yonghong-song2da34262018-06-13 06:12:22 -0700280 if self.probe_type == "u":
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700281 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800282 expr = expr.replace(alias, replacement)
yonghong-song2da34262018-06-13 06:12:22 -0700283 for alias, replacement in Probe.aliases_common.items():
284 expr = expr.replace(alias, replacement)
Nikita V. Shirokov3953c702018-07-27 16:13:47 -0700285 if self.bin_cmp:
286 STRCMP_RE = 'STRCMP\\(\"([^"]+)\\"'
287 else:
288 STRCMP_RE = 'STRCMP\\(("[^"]+\\")'
289 matches = re.finditer(STRCMP_RE, expr)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700290 for match in matches:
291 string = match.group(1)
292 fname = self._generate_streq_function(string)
293 expr = expr.replace("STRCMP", fname, 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800294 return expr
295
yonghong-songf7202572018-09-19 08:50:59 -0700296 p_type = {"u": ct.c_uint, "d": ct.c_int, "lu": ct.c_ulong,
297 "ld": ct.c_long,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300298 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
299 "hu": ct.c_ushort, "hd": ct.c_short,
yonghong-songf7202572018-09-19 08:50:59 -0700300 "x": ct.c_uint, "lx": ct.c_ulong, "llx": ct.c_ulonglong,
301 "c": ct.c_ubyte,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300302 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800303
304 def _generate_python_field_decl(self, idx, fields):
305 field_type = self.types[idx]
306 if field_type == "s":
307 ptype = ct.c_char * self.string_size
308 else:
309 ptype = Probe.p_type[field_type]
310 fields.append(("v%d" % idx, ptype))
311
312 def _generate_python_data_decl(self):
313 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700314 (self._display_function(), self.probe_num)
Teng Qinc200b6c2017-12-16 00:15:55 -0800315 fields = []
316 if self.time_field:
317 fields.append(("timestamp_ns", ct.c_ulonglong))
318 if self.print_cpu:
319 fields.append(("cpu", ct.c_int))
320 fields.extend([
Mark Draytonaa6c9162016-11-03 15:36:29 +0000321 ("tgid", ct.c_uint),
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800322 ("pid", ct.c_uint),
323 ("comm", ct.c_char * 16) # TASK_COMM_LEN
Teng Qinc200b6c2017-12-16 00:15:55 -0800324 ])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800325 for i in range(0, len(self.types)):
326 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700327 if self.kernel_stack:
328 fields.append(("kernel_stack_id", ct.c_int))
329 if self.user_stack:
330 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800331 return type(self.python_struct_name, (ct.Structure,),
332 dict(_fields_=fields))
333
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300334 c_type = {"u": "unsigned int", "d": "int",
yonghong-songf7202572018-09-19 08:50:59 -0700335 "lu": "unsigned long", "ld": "long",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300336 "llu": "unsigned long long", "lld": "long long",
337 "hu": "unsigned short", "hd": "short",
yonghong-songf7202572018-09-19 08:50:59 -0700338 "x": "unsigned int", "lx": "unsigned long",
339 "llx": "unsigned long long",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300340 "c": "char", "K": "unsigned long long",
341 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800342 fmt_types = c_type.keys()
343
344 def _generate_field_decl(self, idx):
345 field_type = self.types[idx]
346 if field_type == "s":
347 return "char v%d[%d];\n" % (idx, self.string_size)
348 if field_type in Probe.fmt_types:
349 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
350 self._bail("unrecognized format specifier %s" % field_type)
351
352 def _generate_data_decl(self):
353 # The BPF program will populate values into the struct
354 # according to the format string, and the Python program will
355 # construct the final display string.
356 self.events_name = "%s_events" % self.probe_name
357 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700358 self.stacks_name = "%s_stacks" % self.probe_name
vijunag9924e642019-01-23 12:35:33 +0530359 stack_type = "BPF_STACK_TRACE" if self.build_id_enabled is False \
360 else "BPF_STACK_TRACE_BUILDID"
361 stack_table = "%s(%s, 1024);" % (stack_type,self.stacks_name) \
Teng Qin6b0ed372016-09-29 21:30:13 -0700362 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800363 data_fields = ""
364 for i, field_type in enumerate(self.types):
365 data_fields += " " + \
366 self._generate_field_decl(i)
Teng Qinc200b6c2017-12-16 00:15:55 -0800367 time_str = "u64 timestamp_ns;" if self.time_field else ""
368 cpu_str = "int cpu;" if self.print_cpu else ""
Teng Qin6b0ed372016-09-29 21:30:13 -0700369 kernel_stack_str = " int kernel_stack_id;" \
370 if self.kernel_stack else ""
371 user_stack_str = " int user_stack_id;" \
372 if self.user_stack else ""
373
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800374 text = """
375struct %s
376{
Teng Qinc200b6c2017-12-16 00:15:55 -0800377%s
378%s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000379 u32 tgid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800380 u32 pid;
381 char comm[TASK_COMM_LEN];
382%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700383%s
384%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800385};
386
387BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700388%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800389"""
Teng Qinc200b6c2017-12-16 00:15:55 -0800390 return text % (self.struct_name, time_str, cpu_str, data_fields,
Teng Qin6b0ed372016-09-29 21:30:13 -0700391 kernel_stack_str, user_stack_str,
392 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800393
394 def _generate_field_assign(self, idx):
395 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300396 expr = self.values[idx].strip()
397 text = ""
398 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000399 arg_index = int(expr[3])
400 arg_ctype = self.usdt.get_probe_arg_ctype(
401 self.usdt_name, arg_index - 1)
402 text = (" %s %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300403 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000404 % (arg_ctype, expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300405
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800406 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300407 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800408 if (%s != 0) {
yonghong-song61484e12018-09-17 22:24:31 -0700409 void *__tmp = (void *)%s;
410 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), __tmp);
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800411 }
yonghong-song61484e12018-09-17 22:24:31 -0700412 """ % (expr, expr, idx, idx)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800413 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300414 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800415 (idx, Probe.c_type[field_type], expr)
416 self._bail("unrecognized field type %s" % field_type)
417
Teng Qin0615bff2016-09-28 08:19:40 -0700418 def _generate_usdt_filter_read(self):
419 text = ""
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000420 if self.probe_type != "u":
421 return text
yonghong-song2da34262018-06-13 06:12:22 -0700422 for arg, _ in Probe.aliases_arg.items():
423 if not (arg in self.filter):
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000424 continue
425 arg_index = int(arg.replace("arg", ""))
426 arg_ctype = self.usdt.get_probe_arg_ctype(
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000427 self.usdt_name, arg_index - 1)
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000428 if not arg_ctype:
429 self._bail("Unable to determine type of {} "
430 "in the filter".format(arg))
431 text += """
Teng Qin0615bff2016-09-28 08:19:40 -0700432 {} {}_filter;
433 bpf_usdt_readarg({}, ctx, &{}_filter);
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000434 """.format(arg_ctype, arg, arg_index, arg)
435 self.filter = self.filter.replace(
436 arg, "{}_filter".format(arg))
Teng Qin0615bff2016-09-28 08:19:40 -0700437 return text
438
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700439 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800440 data_decl = self._generate_data_decl()
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000441 if Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800442 pid_filter = """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800443 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300444 """ % Probe.pid
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000445 # uprobes can have a built-in tgid filter passed to
446 # attach_uprobe, hence the check here -- for kprobes, we
447 # need to do the tgid test by hand:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000448 elif len(self.library) == 0 and Probe.tgid != -1:
449 pid_filter = """
450 if (__tgid != %d) { return 0; }
451 """ % Probe.tgid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800452 elif not include_self:
453 pid_filter = """
Mark Draytonaa6c9162016-11-03 15:36:29 +0000454 if (__tgid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300455 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800456 else:
457 pid_filter = ""
458
yonghong-songc2a530b2019-10-20 09:35:55 -0700459 if self.cgroup_map_name is not None:
460 cgroup_filter = """
461 if (%s.check_current_task(0) <= 0) { return 0; }
462 """ % self.cgroup_map_name
463 else:
464 cgroup_filter = ""
465
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700466 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700467 signature = "struct pt_regs *ctx"
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000468 if self.signature:
469 signature += ", " + self.signature
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700470
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800471 data_fields = ""
472 for i, expr in enumerate(self.values):
473 data_fields += self._generate_field_assign(i)
474
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300475 if self.probe_type == "t":
476 heading = "TRACEPOINT_PROBE(%s, %s)" % \
477 (self.tp_category, self.tp_event)
478 ctx_name = "args"
479 else:
480 heading = "int %s(%s)" % (self.probe_name, signature)
481 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300482
Teng Qinc200b6c2017-12-16 00:15:55 -0800483 time_str = """
484 __data.timestamp_ns = bpf_ktime_get_ns();""" if self.time_field else ""
485 cpu_str = """
486 __data.cpu = bpf_get_smp_processor_id();""" if self.print_cpu else ""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300487 stack_trace = ""
488 if self.user_stack:
489 stack_trace += """
490 __data.user_stack_id = %s.get_stackid(
Yonghong Song90f20862019-11-27 09:16:23 -0800491 %s, BPF_F_USER_STACK
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300492 );""" % (self.stacks_name, ctx_name)
493 if self.kernel_stack:
494 stack_trace += """
495 __data.kernel_stack_id = %s.get_stackid(
Yonghong Song90f20862019-11-27 09:16:23 -0800496 %s, 0
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300497 );""" % (self.stacks_name, ctx_name)
498
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300499 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800500{
Mark Draytonaa6c9162016-11-03 15:36:29 +0000501 u64 __pid_tgid = bpf_get_current_pid_tgid();
502 u32 __tgid = __pid_tgid >> 32;
503 u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800504 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800505 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700506 %s
yonghong-songc2a530b2019-10-20 09:35:55 -0700507 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800508 if (!(%s)) return 0;
509
510 struct %s __data = {0};
Teng Qinc200b6c2017-12-16 00:15:55 -0800511 %s
512 %s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000513 __data.tgid = __tgid;
514 __data.pid = __pid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800515 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
516%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700517%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300518 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800519 return 0;
520}
521"""
yonghong-songc2a530b2019-10-20 09:35:55 -0700522 text = text % (pid_filter, cgroup_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700523 self._generate_usdt_filter_read(), self.filter,
Teng Qinc200b6c2017-12-16 00:15:55 -0800524 self.struct_name, time_str, cpu_str, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300525 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700526
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700527 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800528
529 @classmethod
530 def _time_off_str(cls, timestamp_ns):
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100531 offset = 1e-9 * (timestamp_ns - cls.first_ts)
532 if cls.print_unix_timestamp:
533 return "%.6f" % (offset + cls.first_ts_real)
534 else:
535 return "%.6f" % offset
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800536
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800537 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700538 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800539 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700540 elif self.probe_type == 'u':
541 return self.usdt_name
542 else: # self.probe_type == 't'
543 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800544
Mark Draytonaa6c9162016-11-03 15:36:29 +0000545 def print_stack(self, bpf, stack_id, tgid):
Teng Qin6b0ed372016-09-29 21:30:13 -0700546 if stack_id < 0:
Mirek Klimose5382282018-01-26 14:52:50 -0800547 print(" %d" % stack_id)
548 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700549
550 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
551 for addr in stack:
Mirek Klimose5382282018-01-26 14:52:50 -0800552 print(" ", end="")
553 if Probe.print_address:
554 print("%16x " % addr, end="")
555 print("%s" % (bpf.sym(addr, tgid,
556 show_module=True, show_offset=True)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700557
Mark Draytonaa6c9162016-11-03 15:36:29 +0000558 def _format_message(self, bpf, tgid, values):
559 # Replace each %K with kernel sym and %U with user sym in tgid
Rafael Fonsecaaee5ecf2017-02-08 16:14:31 +0100560 kernel_placeholders = [i for i, t in enumerate(self.types)
561 if t == 'K']
562 user_placeholders = [i for i, t in enumerate(self.types)
563 if t == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700564 for kp in kernel_placeholders:
Sasha Goldshtein01553852017-02-09 03:58:09 -0500565 values[kp] = bpf.ksym(values[kp], show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700566 for up in user_placeholders:
Sasha Goldshtein1e34f4e2017-02-09 00:21:49 -0500567 values[up] = bpf.sym(values[up], tgid,
Sasha Goldshtein01553852017-02-09 03:58:09 -0500568 show_module=True, show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700569 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700570
571 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800572 # Cast as the generated structure type and display
573 # according to the format string in the probe.
574 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
tty59ce7b7e2019-12-04 22:49:38 +0800575 if self.name and bytes(self.name) not in event.comm:
576 return
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800577 values = map(lambda i: getattr(event, "v%d" % i),
578 range(0, len(self.values)))
Mark Draytonaa6c9162016-11-03 15:36:29 +0000579 msg = self._format_message(bpf, event.tgid, values)
tty55cf529e2019-12-06 17:52:56 +0800580 if self.msg_filter and bytes(self.msg_filter) not in msg:
581 return
Teng Qinc200b6c2017-12-16 00:15:55 -0800582 if Probe.print_time:
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000583 time = strftime("%H:%M:%S") if Probe.use_localtime else \
584 Probe._time_off_str(event.timestamp_ns)
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100585 if Probe.print_unix_timestamp:
586 print("%-17s " % time[:17], end="")
587 else:
588 print("%-8s " % time[:8], end="")
Teng Qinc200b6c2017-12-16 00:15:55 -0800589 if Probe.print_cpu:
590 print("%-3s " % event.cpu, end="")
591 print("%-7d %-7d %-15s %-16s %s" %
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200592 (event.tgid, event.pid,
593 event.comm.decode('utf-8', 'replace'),
Teng Qinc200b6c2017-12-16 00:15:55 -0800594 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800595
Teng Qin6b0ed372016-09-29 21:30:13 -0700596 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700597 self.print_stack(bpf, event.kernel_stack_id, -1)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000598 if self.user_stack:
599 self.print_stack(bpf, event.user_stack_id, event.tgid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700600 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700601 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700602
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800603 Probe.event_count += 1
604 if Probe.max_events is not None and \
605 Probe.event_count >= Probe.max_events:
606 exit()
Alban Crequy8bb4e472019-12-21 16:09:53 +0100607 sys.stdout.flush()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800608
609 def attach(self, bpf, verbose):
610 if len(self.library) == 0:
611 self._attach_k(bpf)
612 else:
613 self._attach_u(bpf)
614 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700615 callback = partial(self.print_event, bpf)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000616 bpf[self.events_name].open_perf_buffer(callback,
617 page_cnt=self.page_cnt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800618
619 def _attach_k(self, bpf):
620 if self.probe_type == "r":
621 bpf.attach_kretprobe(event=self.function,
622 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300623 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800624 bpf.attach_kprobe(event=self.function,
625 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300626 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800627
628 def _attach_u(self, bpf):
629 libpath = BPF.find_library(self.library)
630 if libpath is None:
631 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300632 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800633 if libpath is None or len(libpath) == 0:
634 self._bail("unable to find library %s" % self.library)
635
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700636 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300637 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700638 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800639 bpf.attach_uretprobe(name=libpath,
640 sym=self.function,
641 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000642 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800643 else:
644 bpf.attach_uprobe(name=libpath,
645 sym=self.function,
646 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000647 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800648
649class Tool(object):
Mark Drayton5f5687e2017-02-20 18:13:03 +0000650 DEFAULT_PERF_BUFFER_PAGES = 64
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800651 examples = """
652EXAMPLES:
653
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800654trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800655 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800656trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800657 Trace the open syscall and print the filename being opened
tty59ce7b7e2019-12-04 22:49:38 +0800658trace 'do_sys_open "%s", arg2' -n main
659 Trace the open syscall and only print event that process names containing "main"
tty55cf529e2019-12-06 17:52:56 +0800660trace 'do_sys_open "%s", arg2' -f config
661 Trace the open syscall and print the filename being opened filtered by "config"
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800662trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800663 Trace the read syscall and print a message for reads >20000 bytes
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000664trace 'r::do_sys_open "%llx", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800665 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800666trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800667 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800668trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800669 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800670trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
671 Trace the write() call from libc to monitor writes to STDOUT
Mark Draytonaa6c9162016-11-03 15:36:29 +0000672trace 'r::__kmalloc (retval == 0) "kmalloc failed!"'
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800673 Trace returns from __kmalloc which returned a null pointer
Mark Draytonaa6c9162016-11-03 15:36:29 +0000674trace 'r:c:malloc (retval) "allocated = %x", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800675 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300676trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800677 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700678trace 'u:pthread:pthread_create (arg4 != 0)'
679 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000680trace 'p::SyS_nanosleep(struct timespec *ts) "sleep for %lld ns", ts->tv_nsec'
681 Trace the nanosleep syscall and print the sleep duration in ns
yonghong-songc2a530b2019-10-20 09:35:55 -0700682trace -c /sys/fs/cgroup/system.slice/workload.service '__x64_sys_nanosleep' '__x64_sys_clone'
683 Trace nanosleep/clone syscall calls only under workload.service
684 cgroup hierarchy.
Yonghong Songf4470dc2017-12-13 14:12:13 -0800685trace -I 'linux/fs.h' \\
686 'p::uprobe_register(struct inode *inode) "a_ops = %llx", inode->i_mapping->a_ops'
687 Trace the uprobe_register inode mapping ops, and the symbol can be found
688 in /proc/kallsyms
689trace -I 'kernel/sched/sched.h' \\
690 'p::__account_cfs_rq_runtime(struct cfs_rq *cfs_rq) "%d", cfs_rq->runtime_remaining'
691 Trace the cfs scheduling runqueue remaining runtime. The struct cfs_rq is defined
692 in kernel/sched/sched.h which is in kernel source tree and not in kernel-devel
693 package. So this command needs to run at the kernel source tree root directory
694 so that the added header file can be found by the compiler.
tehnerd86293f02018-01-23 21:21:58 -0800695trace -I 'net/sock.h' \\
696 'udpv6_sendmsg(struct sock *sk) (sk->sk_dport == 13568)'
697 Trace udpv6 sendmsg calls only if socket's destination port is equal
698 to 53 (DNS; 13568 in big endian order)
Yonghong Songf92fef22018-01-24 20:51:46 -0800699trace -I 'linux/fs_struct.h' 'mntns_install "users = %d", $task->fs->users'
700 Trace the number of users accessing the file system of the current task
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800701"""
702
703 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300704 parser = argparse.ArgumentParser(description="Attach to " +
705 "functions and print trace messages.",
706 formatter_class=argparse.RawDescriptionHelpFormatter,
707 epilog=Tool.examples)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000708 parser.add_argument("-b", "--buffer-pages", type=int,
709 default=Tool.DEFAULT_PERF_BUFFER_PAGES,
710 help="number of pages to use for perf_events ring buffer "
711 "(default: %(default)d)")
Mark Draytonaa6c9162016-11-03 15:36:29 +0000712 # we'll refer to the userspace concepts of "pid" and "tid" by
713 # their kernel names -- tgid and pid -- inside the script
714 parser.add_argument("-p", "--pid", type=int, metavar="PID",
715 dest="tgid", help="id of the process to trace (optional)")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000716 parser.add_argument("-L", "--tid", type=int, metavar="TID",
Mark Draytonaa6c9162016-11-03 15:36:29 +0000717 dest="pid", help="id of the thread to trace (optional)")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800718 parser.add_argument("-v", "--verbose", action="store_true",
719 help="print resulting BPF program code before executing")
720 parser.add_argument("-Z", "--string-size", type=int,
721 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300722 parser.add_argument("-S", "--include-self",
723 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800724 help="do not filter trace's own pid from the trace")
725 parser.add_argument("-M", "--max-events", type=int,
726 help="number of events to print before quitting")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000727 parser.add_argument("-t", "--timestamp", action="store_true",
728 help="print timestamp column (offset from trace start)")
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100729 parser.add_argument("-u", "--unix-timestamp", action="store_true",
730 help="print UNIX timestamp instead of offset from trace start, requires -t")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000731 parser.add_argument("-T", "--time", action="store_true",
732 help="print time column")
Teng Qinc200b6c2017-12-16 00:15:55 -0800733 parser.add_argument("-C", "--print_cpu", action="store_true",
734 help="print CPU id")
yonghong-songc2a530b2019-10-20 09:35:55 -0700735 parser.add_argument("-c", "--cgroup-path", type=str, \
736 metavar="CGROUP_PATH", dest="cgroup_path", \
737 help="cgroup path")
tty59ce7b7e2019-12-04 22:49:38 +0800738 parser.add_argument("-n", "--name", type=str,
739 help="only print process names containing this name")
tty55cf529e2019-12-06 17:52:56 +0800740 parser.add_argument("-f", "--msg-filter", type=str, dest="msg_filter",
741 help="only print the msg of event containing this string")
Nikita V. Shirokov3953c702018-07-27 16:13:47 -0700742 parser.add_argument("-B", "--bin_cmp", action="store_true",
743 help="allow to use STRCMP with binary values")
vijunag9924e642019-01-23 12:35:33 +0530744 parser.add_argument('-s', "--sym_file_list", type=str, \
745 metavar="SYM_FILE_LIST", dest="sym_file_list", \
746 help="coma separated list of symbol files to use \
747 for symbol resolution")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300748 parser.add_argument("-K", "--kernel-stack",
749 action="store_true", help="output kernel stack trace")
750 parser.add_argument("-U", "--user-stack",
751 action="store_true", help="output user stack trace")
Mirek Klimose5382282018-01-26 14:52:50 -0800752 parser.add_argument("-a", "--address", action="store_true",
753 help="print virtual address in stacks")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800754 parser.add_argument(metavar="probe", dest="probes", nargs="+",
755 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300756 parser.add_argument("-I", "--include", action="append",
757 metavar="header",
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300758 help="additional header files to include in the BPF program "
Yonghong Songf4470dc2017-12-13 14:12:13 -0800759 "as either full path, "
760 "or relative to current working directory, "
761 "or relative to default kernel header search path")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100762 parser.add_argument("--ebpf", action="store_true",
763 help=argparse.SUPPRESS)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800764 self.args = parser.parse_args()
Mark Draytonaa6c9162016-11-03 15:36:29 +0000765 if self.args.tgid and self.args.pid:
Yonghong Songf4470dc2017-12-13 14:12:13 -0800766 parser.error("only one of -p and -L may be specified")
yonghong-songc2a530b2019-10-20 09:35:55 -0700767 if self.args.cgroup_path is not None:
768 self.cgroup_map_name = "__cgroup"
769 else:
770 self.cgroup_map_name = None
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800771
772 def _create_probes(self):
773 Probe.configure(self.args)
774 self.probes = []
775 for probe_spec in self.args.probes:
776 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700777 probe_spec, self.args.string_size,
yonghong-songc2a530b2019-10-20 09:35:55 -0700778 self.args.kernel_stack, self.args.user_stack,
tty55cf529e2019-12-06 17:52:56 +0800779 self.cgroup_map_name, self.args.name, self.args.msg_filter))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800780
781 def _generate_program(self):
782 self.program = """
783#include <linux/ptrace.h>
784#include <linux/sched.h> /* For TASK_COMM_LEN */
785
786"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300787 for include in (self.args.include or []):
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300788 if include.startswith((".", "/")):
789 include = os.path.abspath(include)
790 self.program += "#include \"%s\"\n" % include
791 else:
792 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700793 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800794 map(lambda p: p.raw_probe, self.probes))
yonghong-songc2a530b2019-10-20 09:35:55 -0700795 if self.cgroup_map_name is not None:
796 self.program += "BPF_CGROUP_ARRAY(%s, 1);\n" % \
797 self.cgroup_map_name
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800798 for probe in self.probes:
799 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700800 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800801
Nathan Scottcf0792f2018-02-02 16:56:50 +1100802 if self.args.verbose or self.args.ebpf:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800803 print(self.program)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100804 if self.args.ebpf:
805 exit()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800806
807 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300808 usdt_contexts = []
809 for probe in self.probes:
810 if probe.usdt:
811 # USDT probes must be enabled before the BPF object
812 # is initialized, because that's where the actual
813 # uprobe is being attached.
814 probe.usdt.enable_probe(
815 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300816 if self.args.verbose:
817 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300818 usdt_contexts.append(probe.usdt)
819 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
vijunag9924e642019-01-23 12:35:33 +0530820 if self.args.sym_file_list is not None:
821 print("Note: Kernel bpf will report stack map with ip/build_id")
822 map(lambda x: self.bpf.add_module(x), self.args.sym_file_list.split(','))
yonghong-songc2a530b2019-10-20 09:35:55 -0700823
824 # if cgroup filter is requested, update the cgroup array map
825 if self.cgroup_map_name is not None:
826 cgroup_array = self.bpf.get_table(self.cgroup_map_name)
827 cgroup_array[0] = self.args.cgroup_path
828
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800829 for probe in self.probes:
830 if self.args.verbose:
831 print(probe)
832 probe.attach(self.bpf, self.args.verbose)
833
834 def _main_loop(self):
835 all_probes_trivial = all(map(Probe.is_default_action,
836 self.probes))
837
838 # Print header
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000839 if self.args.timestamp or self.args.time:
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100840 col_fmt = "%-17s " if self.args.unix_timestamp else "%-8s "
841 print(col_fmt % "TIME", end="");
Teng Qinc200b6c2017-12-16 00:15:55 -0800842 if self.args.print_cpu:
843 print("%-3s " % "CPU", end="");
844 print("%-7s %-7s %-15s %-16s %s" %
845 ("PID", "TID", "COMM", "FUNC",
846 "-" if not all_probes_trivial else ""))
Alban Crequy8bb4e472019-12-21 16:09:53 +0100847 sys.stdout.flush()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800848
849 while True:
Teng Qindbf00292018-02-28 21:47:50 -0800850 self.bpf.perf_buffer_poll()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800851
852 def run(self):
853 try:
854 self._create_probes()
855 self._generate_program()
856 self._attach_probes()
857 self._main_loop()
858 except:
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500859 exc_info = sys.exc_info()
860 sys_exit = exc_info[0] is SystemExit
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800861 if self.args.verbose:
862 traceback.print_exc()
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500863 elif not sys_exit:
864 print(exc_info[1])
865 exit(0 if sys_exit else 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800866
867if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300868 Tool().run()