blob: 0bd28613d79d331e32c2ec7216bafd83177dcb20 [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,
61 cgroup_map_name):
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
Sasha Goldshtein38847f02016-02-22 02:19:24 -080076
yonghong-song2da34262018-06-13 06:12:22 -070077 # compiler can generate proper codes for function
78 # signatures with "syscall__" prefix
79 if self.is_syscall_kprobe:
80 self.probe_name = "syscall__" + self.probe_name[6:]
81
Sasha Goldshtein38847f02016-02-22 02:19:24 -080082 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070083 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
84 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080085 self.types, self.values)
86
87 def is_default_action(self):
88 return self.python_format == ""
89
90 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070091 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080092 (self.raw_probe, error))
93
94 def _parse_probe(self):
95 text = self.raw_probe
96
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000097 # There might be a function signature preceding the actual
98 # filter/print part, or not. Find the probe specifier first --
99 # it ends with either a space or an open paren ( for the
100 # function signature part.
101 # opt. signature
102 # probespec | rest
103 # --------- ---------- --
104 (spec, sig, rest) = re.match(r'([^ \t\(]+)(\([^\(]*\))?(.*)',
105 text).groups()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800106
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000107 self._parse_spec(spec)
Paul Chaignon956ca1c2017-03-04 20:07:56 +0100108 # Remove the parens
109 self.signature = sig[1:-1] if sig else None
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000110 if self.signature and self.probe_type in ['u', 't']:
111 self._bail("USDT and tracepoint probes can't have " +
112 "a function signature; use arg1, arg2, " +
113 "... instead")
114
115 text = rest.lstrip()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800116 # If we now have a (, wait for the balanced closing ) and that
117 # will be the predicate
118 self.filter = None
119 if len(text) > 0 and text[0] == "(":
120 balance = 1
121 for i in range(1, len(text)):
122 if text[i] == "(":
123 balance += 1
124 if text[i] == ")":
125 balance -= 1
126 if balance == 0:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300127 self._parse_filter(text[:i + 1])
128 text = text[i + 1:]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800129 break
130 if self.filter is None:
131 self._bail("unmatched end of predicate")
132
133 if self.filter is None:
134 self.filter = "1"
135
136 # The remainder of the text is the printf action
137 self._parse_action(text.lstrip())
138
139 def _parse_spec(self, spec):
140 parts = spec.split(":")
141 # Two special cases: 'func' means 'p::func', 'lib:func' means
142 # 'p:lib:func'. Other combinations need to provide an empty
143 # value between delimiters, e.g. 'r::func' for a kretprobe on
144 # the function func.
145 if len(parts) == 1:
146 parts = ["p", "", parts[0]]
147 elif len(parts) == 2:
148 parts = ["p", parts[0], parts[1]]
149 if len(parts[0]) == 0:
150 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700151 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800152 self.probe_type = parts[0]
153 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700154 self._bail("probe type must be '', 'p', 't', 'r', " +
155 "or 'u', but got '%s'" % parts[0])
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800156 if self.probe_type == "t":
157 self.tp_category = parts[1]
158 self.tp_event = parts[2]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800159 self.library = "" # kernel
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300160 self.function = "" # from TRACEPOINT_PROBE
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700161 elif self.probe_type == "u":
vkhromov5a2b39e2017-07-14 20:42:29 +0100162 self.library = ':'.join(parts[1:-1])
163 self.usdt_name = parts[-1]
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700164 self.function = "" # no function, just address
165 # We will discover the USDT provider by matching on
166 # the USDT name in the specified library
167 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800168 else:
vkhromov5a2b39e2017-07-14 20:42:29 +0100169 self.library = ':'.join(parts[1:-1])
170 self.function = parts[-1]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800171
yonghong-song2da34262018-06-13 06:12:22 -0700172 # only x64 syscalls needs checking, no other syscall wrapper yet.
173 self.is_syscall_kprobe = False
174 if self.probe_type == "p" and len(self.library) == 0 and \
175 self.function[:10] == "__x64_sys_":
176 self.is_syscall_kprobe = True
177
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700178 def _find_usdt_probe(self):
Sasha Goldshteindd045362016-11-13 05:07:38 -0800179 target = Probe.pid if Probe.pid and Probe.pid != -1 \
180 else Probe.tgid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000181 self.usdt = USDT(path=self.library, pid=target)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300182 for probe in self.usdt.enumerate_probes():
Javier Honduvilla Coto1ef82e22018-04-19 14:14:24 +0200183 if probe.name == self.usdt_name.encode('ascii'):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300184 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700185 self._bail("unrecognized USDT probe %s" % self.usdt_name)
186
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800187 def _parse_filter(self, filt):
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700188 self.filter = self._rewrite_expr(filt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800189
190 def _parse_types(self, fmt):
191 for match in re.finditer(
yonghong-songf7202572018-09-19 08:50:59 -0700192 r'[^%]%(s|u|d|lu|llu|ld|lld|hu|hd|x|lx|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800193 self.types.append(match.group(1))
yonghong-songf7202572018-09-19 08:50:59 -0700194 fmt = re.sub(r'([^%]%)(u|d|lu|llu|ld|lld|hu|hd)', r'\1d', fmt)
195 fmt = re.sub(r'([^%]%)(x|lx|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700196 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800197 self.python_format = fmt.strip('"')
198
199 def _parse_action(self, action):
200 self.values = []
201 self.types = []
202 self.python_format = ""
203 if len(action) == 0:
204 return
205
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800206 action = action.strip()
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700207 match = re.search(r'(\".*?\"),?(.*)', action)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800208 if match is None:
209 self._bail("expected format string in \"s")
210
211 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800212 self._parse_types(self.raw_format)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700213 for part in re.split('(?<!"),', match.group(2)):
214 part = self._rewrite_expr(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800215 if len(part) > 0:
216 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800217
yonghong-song2da34262018-06-13 06:12:22 -0700218 aliases_arg = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530219 "arg1": "PT_REGS_PARM1(ctx)",
220 "arg2": "PT_REGS_PARM2(ctx)",
221 "arg3": "PT_REGS_PARM3(ctx)",
222 "arg4": "PT_REGS_PARM4(ctx)",
223 "arg5": "PT_REGS_PARM5(ctx)",
224 "arg6": "PT_REGS_PARM6(ctx)",
yonghong-song2da34262018-06-13 06:12:22 -0700225 }
226
227 aliases_indarg = {
Prashant Bhole05765ee2018-12-28 01:47:56 +0900228 "arg1": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700229 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM1(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800230 "arg2": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700231 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM2(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800232 "arg3": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700233 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM3(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800234 "arg4": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700235 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM4(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800236 "arg5": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700237 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM5(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800238 "arg6": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700239 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM6(_ctx))); _val;})",
240 }
241
242 aliases_common = {
243 "retval": "PT_REGS_RC(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800244 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
245 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
246 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
247 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
Yonghong Songf92fef22018-01-24 20:51:46 -0800248 "$cpu": "bpf_get_smp_processor_id()",
249 "$task" : "((struct task_struct *)bpf_get_current_task())"
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800250 }
251
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700252 def _generate_streq_function(self, string):
253 fname = "streq_%d" % Probe.streq_index
254 Probe.streq_index += 1
255 self.streq_functions += """
Sasha Goldshteinb9aec342017-01-16 18:41:22 +0000256static inline bool %s(char const *ignored, uintptr_t str) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700257 char needle[] = %s;
258 char haystack[sizeof(needle)];
259 bpf_probe_read(&haystack, sizeof(haystack), (void *)str);
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000260 for (int i = 0; i < sizeof(needle) - 1; ++i) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700261 if (needle[i] != haystack[i]) {
262 return false;
263 }
264 }
265 return true;
266}
267 """ % (fname, string)
268 return fname
269
270 def _rewrite_expr(self, expr):
yonghong-song2da34262018-06-13 06:12:22 -0700271 if self.is_syscall_kprobe:
272 for alias, replacement in Probe.aliases_indarg.items():
273 expr = expr.replace(alias, replacement)
274 else:
275 for alias, replacement in Probe.aliases_arg.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700276 # For USDT probes, we replace argN values with the
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300277 # actual arguments for that probe obtained using
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300278 # bpf_readarg_N macros emitted at BPF construction.
yonghong-song2da34262018-06-13 06:12:22 -0700279 if self.probe_type == "u":
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700280 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800281 expr = expr.replace(alias, replacement)
yonghong-song2da34262018-06-13 06:12:22 -0700282 for alias, replacement in Probe.aliases_common.items():
283 expr = expr.replace(alias, replacement)
Nikita V. Shirokov3953c702018-07-27 16:13:47 -0700284 if self.bin_cmp:
285 STRCMP_RE = 'STRCMP\\(\"([^"]+)\\"'
286 else:
287 STRCMP_RE = 'STRCMP\\(("[^"]+\\")'
288 matches = re.finditer(STRCMP_RE, expr)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700289 for match in matches:
290 string = match.group(1)
291 fname = self._generate_streq_function(string)
292 expr = expr.replace("STRCMP", fname, 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800293 return expr
294
yonghong-songf7202572018-09-19 08:50:59 -0700295 p_type = {"u": ct.c_uint, "d": ct.c_int, "lu": ct.c_ulong,
296 "ld": ct.c_long,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300297 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
298 "hu": ct.c_ushort, "hd": ct.c_short,
yonghong-songf7202572018-09-19 08:50:59 -0700299 "x": ct.c_uint, "lx": ct.c_ulong, "llx": ct.c_ulonglong,
300 "c": ct.c_ubyte,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300301 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800302
303 def _generate_python_field_decl(self, idx, fields):
304 field_type = self.types[idx]
305 if field_type == "s":
306 ptype = ct.c_char * self.string_size
307 else:
308 ptype = Probe.p_type[field_type]
309 fields.append(("v%d" % idx, ptype))
310
311 def _generate_python_data_decl(self):
312 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700313 (self._display_function(), self.probe_num)
Teng Qinc200b6c2017-12-16 00:15:55 -0800314 fields = []
315 if self.time_field:
316 fields.append(("timestamp_ns", ct.c_ulonglong))
317 if self.print_cpu:
318 fields.append(("cpu", ct.c_int))
319 fields.extend([
Mark Draytonaa6c9162016-11-03 15:36:29 +0000320 ("tgid", ct.c_uint),
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800321 ("pid", ct.c_uint),
322 ("comm", ct.c_char * 16) # TASK_COMM_LEN
Teng Qinc200b6c2017-12-16 00:15:55 -0800323 ])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800324 for i in range(0, len(self.types)):
325 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700326 if self.kernel_stack:
327 fields.append(("kernel_stack_id", ct.c_int))
328 if self.user_stack:
329 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800330 return type(self.python_struct_name, (ct.Structure,),
331 dict(_fields_=fields))
332
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300333 c_type = {"u": "unsigned int", "d": "int",
yonghong-songf7202572018-09-19 08:50:59 -0700334 "lu": "unsigned long", "ld": "long",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300335 "llu": "unsigned long long", "lld": "long long",
336 "hu": "unsigned short", "hd": "short",
yonghong-songf7202572018-09-19 08:50:59 -0700337 "x": "unsigned int", "lx": "unsigned long",
338 "llx": "unsigned long long",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300339 "c": "char", "K": "unsigned long long",
340 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800341 fmt_types = c_type.keys()
342
343 def _generate_field_decl(self, idx):
344 field_type = self.types[idx]
345 if field_type == "s":
346 return "char v%d[%d];\n" % (idx, self.string_size)
347 if field_type in Probe.fmt_types:
348 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
349 self._bail("unrecognized format specifier %s" % field_type)
350
351 def _generate_data_decl(self):
352 # The BPF program will populate values into the struct
353 # according to the format string, and the Python program will
354 # construct the final display string.
355 self.events_name = "%s_events" % self.probe_name
356 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700357 self.stacks_name = "%s_stacks" % self.probe_name
vijunag9924e642019-01-23 12:35:33 +0530358 stack_type = "BPF_STACK_TRACE" if self.build_id_enabled is False \
359 else "BPF_STACK_TRACE_BUILDID"
360 stack_table = "%s(%s, 1024);" % (stack_type,self.stacks_name) \
Teng Qin6b0ed372016-09-29 21:30:13 -0700361 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800362 data_fields = ""
363 for i, field_type in enumerate(self.types):
364 data_fields += " " + \
365 self._generate_field_decl(i)
Teng Qinc200b6c2017-12-16 00:15:55 -0800366 time_str = "u64 timestamp_ns;" if self.time_field else ""
367 cpu_str = "int cpu;" if self.print_cpu else ""
Teng Qin6b0ed372016-09-29 21:30:13 -0700368 kernel_stack_str = " int kernel_stack_id;" \
369 if self.kernel_stack else ""
370 user_stack_str = " int user_stack_id;" \
371 if self.user_stack else ""
372
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800373 text = """
374struct %s
375{
Teng Qinc200b6c2017-12-16 00:15:55 -0800376%s
377%s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000378 u32 tgid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800379 u32 pid;
380 char comm[TASK_COMM_LEN];
381%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700382%s
383%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800384};
385
386BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700387%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800388"""
Teng Qinc200b6c2017-12-16 00:15:55 -0800389 return text % (self.struct_name, time_str, cpu_str, data_fields,
Teng Qin6b0ed372016-09-29 21:30:13 -0700390 kernel_stack_str, user_stack_str,
391 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800392
393 def _generate_field_assign(self, idx):
394 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300395 expr = self.values[idx].strip()
396 text = ""
397 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000398 arg_index = int(expr[3])
399 arg_ctype = self.usdt.get_probe_arg_ctype(
400 self.usdt_name, arg_index - 1)
401 text = (" %s %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300402 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000403 % (arg_ctype, expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300404
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800405 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300406 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800407 if (%s != 0) {
yonghong-song61484e12018-09-17 22:24:31 -0700408 void *__tmp = (void *)%s;
409 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), __tmp);
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800410 }
yonghong-song61484e12018-09-17 22:24:31 -0700411 """ % (expr, expr, idx, idx)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800412 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300413 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800414 (idx, Probe.c_type[field_type], expr)
415 self._bail("unrecognized field type %s" % field_type)
416
Teng Qin0615bff2016-09-28 08:19:40 -0700417 def _generate_usdt_filter_read(self):
418 text = ""
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000419 if self.probe_type != "u":
420 return text
yonghong-song2da34262018-06-13 06:12:22 -0700421 for arg, _ in Probe.aliases_arg.items():
422 if not (arg in self.filter):
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000423 continue
424 arg_index = int(arg.replace("arg", ""))
425 arg_ctype = self.usdt.get_probe_arg_ctype(
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000426 self.usdt_name, arg_index - 1)
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000427 if not arg_ctype:
428 self._bail("Unable to determine type of {} "
429 "in the filter".format(arg))
430 text += """
Teng Qin0615bff2016-09-28 08:19:40 -0700431 {} {}_filter;
432 bpf_usdt_readarg({}, ctx, &{}_filter);
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000433 """.format(arg_ctype, arg, arg_index, arg)
434 self.filter = self.filter.replace(
435 arg, "{}_filter".format(arg))
Teng Qin0615bff2016-09-28 08:19:40 -0700436 return text
437
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700438 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800439 data_decl = self._generate_data_decl()
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000440 if Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800441 pid_filter = """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800442 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300443 """ % Probe.pid
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000444 # uprobes can have a built-in tgid filter passed to
445 # attach_uprobe, hence the check here -- for kprobes, we
446 # need to do the tgid test by hand:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000447 elif len(self.library) == 0 and Probe.tgid != -1:
448 pid_filter = """
449 if (__tgid != %d) { return 0; }
450 """ % Probe.tgid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800451 elif not include_self:
452 pid_filter = """
Mark Draytonaa6c9162016-11-03 15:36:29 +0000453 if (__tgid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300454 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800455 else:
456 pid_filter = ""
457
yonghong-songc2a530b2019-10-20 09:35:55 -0700458 if self.cgroup_map_name is not None:
459 cgroup_filter = """
460 if (%s.check_current_task(0) <= 0) { return 0; }
461 """ % self.cgroup_map_name
462 else:
463 cgroup_filter = ""
464
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700465 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700466 signature = "struct pt_regs *ctx"
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000467 if self.signature:
468 signature += ", " + self.signature
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700469
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800470 data_fields = ""
471 for i, expr in enumerate(self.values):
472 data_fields += self._generate_field_assign(i)
473
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300474 if self.probe_type == "t":
475 heading = "TRACEPOINT_PROBE(%s, %s)" % \
476 (self.tp_category, self.tp_event)
477 ctx_name = "args"
478 else:
479 heading = "int %s(%s)" % (self.probe_name, signature)
480 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300481
Teng Qinc200b6c2017-12-16 00:15:55 -0800482 time_str = """
483 __data.timestamp_ns = bpf_ktime_get_ns();""" if self.time_field else ""
484 cpu_str = """
485 __data.cpu = bpf_get_smp_processor_id();""" if self.print_cpu else ""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300486 stack_trace = ""
487 if self.user_stack:
488 stack_trace += """
489 __data.user_stack_id = %s.get_stackid(
Yonghong Song90f20862019-11-27 09:16:23 -0800490 %s, BPF_F_USER_STACK
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300491 );""" % (self.stacks_name, ctx_name)
492 if self.kernel_stack:
493 stack_trace += """
494 __data.kernel_stack_id = %s.get_stackid(
Yonghong Song90f20862019-11-27 09:16:23 -0800495 %s, 0
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300496 );""" % (self.stacks_name, ctx_name)
497
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300498 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800499{
Mark Draytonaa6c9162016-11-03 15:36:29 +0000500 u64 __pid_tgid = bpf_get_current_pid_tgid();
501 u32 __tgid = __pid_tgid >> 32;
502 u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800503 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800504 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700505 %s
yonghong-songc2a530b2019-10-20 09:35:55 -0700506 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800507 if (!(%s)) return 0;
508
509 struct %s __data = {0};
Teng Qinc200b6c2017-12-16 00:15:55 -0800510 %s
511 %s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000512 __data.tgid = __tgid;
513 __data.pid = __pid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800514 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
515%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700516%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300517 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800518 return 0;
519}
520"""
yonghong-songc2a530b2019-10-20 09:35:55 -0700521 text = text % (pid_filter, cgroup_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700522 self._generate_usdt_filter_read(), self.filter,
Teng Qinc200b6c2017-12-16 00:15:55 -0800523 self.struct_name, time_str, cpu_str, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300524 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700525
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700526 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800527
528 @classmethod
529 def _time_off_str(cls, timestamp_ns):
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100530 offset = 1e-9 * (timestamp_ns - cls.first_ts)
531 if cls.print_unix_timestamp:
532 return "%.6f" % (offset + cls.first_ts_real)
533 else:
534 return "%.6f" % offset
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800535
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800536 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700537 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800538 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700539 elif self.probe_type == 'u':
540 return self.usdt_name
541 else: # self.probe_type == 't'
542 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800543
Mark Draytonaa6c9162016-11-03 15:36:29 +0000544 def print_stack(self, bpf, stack_id, tgid):
Teng Qin6b0ed372016-09-29 21:30:13 -0700545 if stack_id < 0:
Mirek Klimose5382282018-01-26 14:52:50 -0800546 print(" %d" % stack_id)
547 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700548
549 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
550 for addr in stack:
Mirek Klimose5382282018-01-26 14:52:50 -0800551 print(" ", end="")
552 if Probe.print_address:
553 print("%16x " % addr, end="")
554 print("%s" % (bpf.sym(addr, tgid,
555 show_module=True, show_offset=True)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700556
Mark Draytonaa6c9162016-11-03 15:36:29 +0000557 def _format_message(self, bpf, tgid, values):
558 # Replace each %K with kernel sym and %U with user sym in tgid
Rafael Fonsecaaee5ecf2017-02-08 16:14:31 +0100559 kernel_placeholders = [i for i, t in enumerate(self.types)
560 if t == 'K']
561 user_placeholders = [i for i, t in enumerate(self.types)
562 if t == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700563 for kp in kernel_placeholders:
Sasha Goldshtein01553852017-02-09 03:58:09 -0500564 values[kp] = bpf.ksym(values[kp], show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700565 for up in user_placeholders:
Sasha Goldshtein1e34f4e2017-02-09 00:21:49 -0500566 values[up] = bpf.sym(values[up], tgid,
Sasha Goldshtein01553852017-02-09 03:58:09 -0500567 show_module=True, show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700568 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700569
570 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800571 # Cast as the generated structure type and display
572 # according to the format string in the probe.
573 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
574 values = map(lambda i: getattr(event, "v%d" % i),
575 range(0, len(self.values)))
Mark Draytonaa6c9162016-11-03 15:36:29 +0000576 msg = self._format_message(bpf, event.tgid, values)
Teng Qinc200b6c2017-12-16 00:15:55 -0800577 if Probe.print_time:
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000578 time = strftime("%H:%M:%S") if Probe.use_localtime else \
579 Probe._time_off_str(event.timestamp_ns)
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100580 if Probe.print_unix_timestamp:
581 print("%-17s " % time[:17], end="")
582 else:
583 print("%-8s " % time[:8], end="")
Teng Qinc200b6c2017-12-16 00:15:55 -0800584 if Probe.print_cpu:
585 print("%-3s " % event.cpu, end="")
586 print("%-7d %-7d %-15s %-16s %s" %
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200587 (event.tgid, event.pid,
588 event.comm.decode('utf-8', 'replace'),
Teng Qinc200b6c2017-12-16 00:15:55 -0800589 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800590
Teng Qin6b0ed372016-09-29 21:30:13 -0700591 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700592 self.print_stack(bpf, event.kernel_stack_id, -1)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000593 if self.user_stack:
594 self.print_stack(bpf, event.user_stack_id, event.tgid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700595 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700596 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700597
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800598 Probe.event_count += 1
599 if Probe.max_events is not None and \
600 Probe.event_count >= Probe.max_events:
601 exit()
602
603 def attach(self, bpf, verbose):
604 if len(self.library) == 0:
605 self._attach_k(bpf)
606 else:
607 self._attach_u(bpf)
608 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700609 callback = partial(self.print_event, bpf)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000610 bpf[self.events_name].open_perf_buffer(callback,
611 page_cnt=self.page_cnt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800612
613 def _attach_k(self, bpf):
614 if self.probe_type == "r":
615 bpf.attach_kretprobe(event=self.function,
616 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300617 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800618 bpf.attach_kprobe(event=self.function,
619 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300620 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800621
622 def _attach_u(self, bpf):
623 libpath = BPF.find_library(self.library)
624 if libpath is None:
625 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300626 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800627 if libpath is None or len(libpath) == 0:
628 self._bail("unable to find library %s" % self.library)
629
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700630 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300631 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700632 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800633 bpf.attach_uretprobe(name=libpath,
634 sym=self.function,
635 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000636 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800637 else:
638 bpf.attach_uprobe(name=libpath,
639 sym=self.function,
640 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000641 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800642
643class Tool(object):
Mark Drayton5f5687e2017-02-20 18:13:03 +0000644 DEFAULT_PERF_BUFFER_PAGES = 64
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800645 examples = """
646EXAMPLES:
647
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800648trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800649 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800650trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800651 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800652trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800653 Trace the read syscall and print a message for reads >20000 bytes
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000654trace 'r::do_sys_open "%llx", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800655 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800656trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800657 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800658trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800659 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800660trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
661 Trace the write() call from libc to monitor writes to STDOUT
Mark Draytonaa6c9162016-11-03 15:36:29 +0000662trace 'r::__kmalloc (retval == 0) "kmalloc failed!"'
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800663 Trace returns from __kmalloc which returned a null pointer
Mark Draytonaa6c9162016-11-03 15:36:29 +0000664trace 'r:c:malloc (retval) "allocated = %x", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800665 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300666trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800667 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700668trace 'u:pthread:pthread_create (arg4 != 0)'
669 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000670trace 'p::SyS_nanosleep(struct timespec *ts) "sleep for %lld ns", ts->tv_nsec'
671 Trace the nanosleep syscall and print the sleep duration in ns
yonghong-songc2a530b2019-10-20 09:35:55 -0700672trace -c /sys/fs/cgroup/system.slice/workload.service '__x64_sys_nanosleep' '__x64_sys_clone'
673 Trace nanosleep/clone syscall calls only under workload.service
674 cgroup hierarchy.
Yonghong Songf4470dc2017-12-13 14:12:13 -0800675trace -I 'linux/fs.h' \\
676 'p::uprobe_register(struct inode *inode) "a_ops = %llx", inode->i_mapping->a_ops'
677 Trace the uprobe_register inode mapping ops, and the symbol can be found
678 in /proc/kallsyms
679trace -I 'kernel/sched/sched.h' \\
680 'p::__account_cfs_rq_runtime(struct cfs_rq *cfs_rq) "%d", cfs_rq->runtime_remaining'
681 Trace the cfs scheduling runqueue remaining runtime. The struct cfs_rq is defined
682 in kernel/sched/sched.h which is in kernel source tree and not in kernel-devel
683 package. So this command needs to run at the kernel source tree root directory
684 so that the added header file can be found by the compiler.
tehnerd86293f02018-01-23 21:21:58 -0800685trace -I 'net/sock.h' \\
686 'udpv6_sendmsg(struct sock *sk) (sk->sk_dport == 13568)'
687 Trace udpv6 sendmsg calls only if socket's destination port is equal
688 to 53 (DNS; 13568 in big endian order)
Yonghong Songf92fef22018-01-24 20:51:46 -0800689trace -I 'linux/fs_struct.h' 'mntns_install "users = %d", $task->fs->users'
690 Trace the number of users accessing the file system of the current task
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800691"""
692
693 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300694 parser = argparse.ArgumentParser(description="Attach to " +
695 "functions and print trace messages.",
696 formatter_class=argparse.RawDescriptionHelpFormatter,
697 epilog=Tool.examples)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000698 parser.add_argument("-b", "--buffer-pages", type=int,
699 default=Tool.DEFAULT_PERF_BUFFER_PAGES,
700 help="number of pages to use for perf_events ring buffer "
701 "(default: %(default)d)")
Mark Draytonaa6c9162016-11-03 15:36:29 +0000702 # we'll refer to the userspace concepts of "pid" and "tid" by
703 # their kernel names -- tgid and pid -- inside the script
704 parser.add_argument("-p", "--pid", type=int, metavar="PID",
705 dest="tgid", help="id of the process to trace (optional)")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000706 parser.add_argument("-L", "--tid", type=int, metavar="TID",
Mark Draytonaa6c9162016-11-03 15:36:29 +0000707 dest="pid", help="id of the thread to trace (optional)")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800708 parser.add_argument("-v", "--verbose", action="store_true",
709 help="print resulting BPF program code before executing")
710 parser.add_argument("-Z", "--string-size", type=int,
711 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300712 parser.add_argument("-S", "--include-self",
713 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800714 help="do not filter trace's own pid from the trace")
715 parser.add_argument("-M", "--max-events", type=int,
716 help="number of events to print before quitting")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000717 parser.add_argument("-t", "--timestamp", action="store_true",
718 help="print timestamp column (offset from trace start)")
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100719 parser.add_argument("-u", "--unix-timestamp", action="store_true",
720 help="print UNIX timestamp instead of offset from trace start, requires -t")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000721 parser.add_argument("-T", "--time", action="store_true",
722 help="print time column")
Teng Qinc200b6c2017-12-16 00:15:55 -0800723 parser.add_argument("-C", "--print_cpu", action="store_true",
724 help="print CPU id")
yonghong-songc2a530b2019-10-20 09:35:55 -0700725 parser.add_argument("-c", "--cgroup-path", type=str, \
726 metavar="CGROUP_PATH", dest="cgroup_path", \
727 help="cgroup path")
Nikita V. Shirokov3953c702018-07-27 16:13:47 -0700728 parser.add_argument("-B", "--bin_cmp", action="store_true",
729 help="allow to use STRCMP with binary values")
vijunag9924e642019-01-23 12:35:33 +0530730 parser.add_argument('-s', "--sym_file_list", type=str, \
731 metavar="SYM_FILE_LIST", dest="sym_file_list", \
732 help="coma separated list of symbol files to use \
733 for symbol resolution")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300734 parser.add_argument("-K", "--kernel-stack",
735 action="store_true", help="output kernel stack trace")
736 parser.add_argument("-U", "--user-stack",
737 action="store_true", help="output user stack trace")
Mirek Klimose5382282018-01-26 14:52:50 -0800738 parser.add_argument("-a", "--address", action="store_true",
739 help="print virtual address in stacks")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800740 parser.add_argument(metavar="probe", dest="probes", nargs="+",
741 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300742 parser.add_argument("-I", "--include", action="append",
743 metavar="header",
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300744 help="additional header files to include in the BPF program "
Yonghong Songf4470dc2017-12-13 14:12:13 -0800745 "as either full path, "
746 "or relative to current working directory, "
747 "or relative to default kernel header search path")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100748 parser.add_argument("--ebpf", action="store_true",
749 help=argparse.SUPPRESS)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800750 self.args = parser.parse_args()
Mark Draytonaa6c9162016-11-03 15:36:29 +0000751 if self.args.tgid and self.args.pid:
Yonghong Songf4470dc2017-12-13 14:12:13 -0800752 parser.error("only one of -p and -L may be specified")
yonghong-songc2a530b2019-10-20 09:35:55 -0700753 if self.args.cgroup_path is not None:
754 self.cgroup_map_name = "__cgroup"
755 else:
756 self.cgroup_map_name = None
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800757
758 def _create_probes(self):
759 Probe.configure(self.args)
760 self.probes = []
761 for probe_spec in self.args.probes:
762 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700763 probe_spec, self.args.string_size,
yonghong-songc2a530b2019-10-20 09:35:55 -0700764 self.args.kernel_stack, self.args.user_stack,
765 self.cgroup_map_name))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800766
767 def _generate_program(self):
768 self.program = """
769#include <linux/ptrace.h>
770#include <linux/sched.h> /* For TASK_COMM_LEN */
771
772"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300773 for include in (self.args.include or []):
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300774 if include.startswith((".", "/")):
775 include = os.path.abspath(include)
776 self.program += "#include \"%s\"\n" % include
777 else:
778 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700779 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800780 map(lambda p: p.raw_probe, self.probes))
yonghong-songc2a530b2019-10-20 09:35:55 -0700781 if self.cgroup_map_name is not None:
782 self.program += "BPF_CGROUP_ARRAY(%s, 1);\n" % \
783 self.cgroup_map_name
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800784 for probe in self.probes:
785 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700786 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800787
Nathan Scottcf0792f2018-02-02 16:56:50 +1100788 if self.args.verbose or self.args.ebpf:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800789 print(self.program)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100790 if self.args.ebpf:
791 exit()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800792
793 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300794 usdt_contexts = []
795 for probe in self.probes:
796 if probe.usdt:
797 # USDT probes must be enabled before the BPF object
798 # is initialized, because that's where the actual
799 # uprobe is being attached.
800 probe.usdt.enable_probe(
801 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300802 if self.args.verbose:
803 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300804 usdt_contexts.append(probe.usdt)
805 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
vijunag9924e642019-01-23 12:35:33 +0530806 if self.args.sym_file_list is not None:
807 print("Note: Kernel bpf will report stack map with ip/build_id")
808 map(lambda x: self.bpf.add_module(x), self.args.sym_file_list.split(','))
yonghong-songc2a530b2019-10-20 09:35:55 -0700809
810 # if cgroup filter is requested, update the cgroup array map
811 if self.cgroup_map_name is not None:
812 cgroup_array = self.bpf.get_table(self.cgroup_map_name)
813 cgroup_array[0] = self.args.cgroup_path
814
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800815 for probe in self.probes:
816 if self.args.verbose:
817 print(probe)
818 probe.attach(self.bpf, self.args.verbose)
819
820 def _main_loop(self):
821 all_probes_trivial = all(map(Probe.is_default_action,
822 self.probes))
823
824 # Print header
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000825 if self.args.timestamp or self.args.time:
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100826 col_fmt = "%-17s " if self.args.unix_timestamp else "%-8s "
827 print(col_fmt % "TIME", end="");
Teng Qinc200b6c2017-12-16 00:15:55 -0800828 if self.args.print_cpu:
829 print("%-3s " % "CPU", end="");
830 print("%-7s %-7s %-15s %-16s %s" %
831 ("PID", "TID", "COMM", "FUNC",
832 "-" if not all_probes_trivial else ""))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800833
834 while True:
Teng Qindbf00292018-02-28 21:47:50 -0800835 self.bpf.perf_buffer_poll()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800836
837 def run(self):
838 try:
839 self._create_probes()
840 self._generate_program()
841 self._attach_probes()
842 self._main_loop()
843 except:
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500844 exc_info = sys.exc_info()
845 sys_exit = exc_info[0] is SystemExit
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800846 if self.args.verbose:
847 traceback.print_exc()
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500848 elif not sys_exit:
849 print(exc_info[1])
850 exit(0 if sys_exit else 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800851
852if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300853 Tool().run()