blob: 0b8797c9ee04d7f690bf67224b0396fc2a7524d8 [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#
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +00006# usage: trace [-h] [-p PID] [-L TID] [-v] [-Z STRING_SIZE] [-S]
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
17import argparse
18import re
19import ctypes as ct
20import os
21import traceback
22import sys
23
Sasha Goldshtein38847f02016-02-22 02:19:24 -080024class Probe(object):
25 probe_count = 0
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070026 streq_index = 0
Sasha Goldshtein38847f02016-02-22 02:19:24 -080027 max_events = None
28 event_count = 0
29 first_ts = 0
Teng Qinc200b6c2017-12-16 00:15:55 -080030 print_time = False
Sasha Goldshtein38847f02016-02-22 02:19:24 -080031 use_localtime = True
Teng Qinc200b6c2017-12-16 00:15:55 -080032 time_field = False
33 print_cpu = False
Mirek Klimose5382282018-01-26 14:52:50 -080034 print_address = False
Mark Draytonaa6c9162016-11-03 15:36:29 +000035 tgid = -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070036 pid = -1
Mark Drayton5f5687e2017-02-20 18:13:03 +000037 page_cnt = None
vijunag9924e642019-01-23 12:35:33 +053038 build_id_enabled = False
Sasha Goldshtein38847f02016-02-22 02:19:24 -080039
40 @classmethod
41 def configure(cls, args):
42 cls.max_events = args.max_events
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +000043 cls.print_time = args.timestamp or args.time
44 cls.use_localtime = not args.timestamp
Teng Qinc200b6c2017-12-16 00:15:55 -080045 cls.time_field = cls.print_time and (not cls.use_localtime)
46 cls.print_cpu = args.print_cpu
Mirek Klimose5382282018-01-26 14:52:50 -080047 cls.print_address = args.address
Sasha Goldshtein60c41922017-02-09 04:19:53 -050048 cls.first_ts = BPF.monotonic_time()
Mark Draytonaa6c9162016-11-03 15:36:29 +000049 cls.tgid = args.tgid or -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070050 cls.pid = args.pid or -1
Mark Drayton5f5687e2017-02-20 18:13:03 +000051 cls.page_cnt = args.buffer_pages
Nikita V. Shirokov3953c702018-07-27 16:13:47 -070052 cls.bin_cmp = args.bin_cmp
vijunag9924e642019-01-23 12:35:33 +053053 cls.build_id_enabled = args.sym_file_list is not None
Sasha Goldshtein38847f02016-02-22 02:19:24 -080054
Teng Qin6b0ed372016-09-29 21:30:13 -070055 def __init__(self, probe, string_size, kernel_stack, user_stack):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +030056 self.usdt = None
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070057 self.streq_functions = ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -080058 self.raw_probe = probe
59 self.string_size = string_size
Teng Qin6b0ed372016-09-29 21:30:13 -070060 self.kernel_stack = kernel_stack
61 self.user_stack = user_stack
Sasha Goldshtein38847f02016-02-22 02:19:24 -080062 Probe.probe_count += 1
63 self._parse_probe()
64 self.probe_num = Probe.probe_count
65 self.probe_name = "probe_%s_%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070066 (self._display_function(), self.probe_num)
Paul Chaignon956ca1c2017-03-04 20:07:56 +010067 self.probe_name = re.sub(r'[^A-Za-z0-9_]', '_',
68 self.probe_name)
Sasha Goldshtein38847f02016-02-22 02:19:24 -080069
yonghong-song2da34262018-06-13 06:12:22 -070070 # compiler can generate proper codes for function
71 # signatures with "syscall__" prefix
72 if self.is_syscall_kprobe:
73 self.probe_name = "syscall__" + self.probe_name[6:]
74
Sasha Goldshtein38847f02016-02-22 02:19:24 -080075 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070076 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
77 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080078 self.types, self.values)
79
80 def is_default_action(self):
81 return self.python_format == ""
82
83 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070084 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080085 (self.raw_probe, error))
86
87 def _parse_probe(self):
88 text = self.raw_probe
89
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000090 # There might be a function signature preceding the actual
91 # filter/print part, or not. Find the probe specifier first --
92 # it ends with either a space or an open paren ( for the
93 # function signature part.
94 # opt. signature
95 # probespec | rest
96 # --------- ---------- --
97 (spec, sig, rest) = re.match(r'([^ \t\(]+)(\([^\(]*\))?(.*)',
98 text).groups()
Sasha Goldshtein38847f02016-02-22 02:19:24 -080099
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000100 self._parse_spec(spec)
Paul Chaignon956ca1c2017-03-04 20:07:56 +0100101 # Remove the parens
102 self.signature = sig[1:-1] if sig else None
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000103 if self.signature and self.probe_type in ['u', 't']:
104 self._bail("USDT and tracepoint probes can't have " +
105 "a function signature; use arg1, arg2, " +
106 "... instead")
107
108 text = rest.lstrip()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800109 # If we now have a (, wait for the balanced closing ) and that
110 # will be the predicate
111 self.filter = None
112 if len(text) > 0 and text[0] == "(":
113 balance = 1
114 for i in range(1, len(text)):
115 if text[i] == "(":
116 balance += 1
117 if text[i] == ")":
118 balance -= 1
119 if balance == 0:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300120 self._parse_filter(text[:i + 1])
121 text = text[i + 1:]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800122 break
123 if self.filter is None:
124 self._bail("unmatched end of predicate")
125
126 if self.filter is None:
127 self.filter = "1"
128
129 # The remainder of the text is the printf action
130 self._parse_action(text.lstrip())
131
132 def _parse_spec(self, spec):
133 parts = spec.split(":")
134 # Two special cases: 'func' means 'p::func', 'lib:func' means
135 # 'p:lib:func'. Other combinations need to provide an empty
136 # value between delimiters, e.g. 'r::func' for a kretprobe on
137 # the function func.
138 if len(parts) == 1:
139 parts = ["p", "", parts[0]]
140 elif len(parts) == 2:
141 parts = ["p", parts[0], parts[1]]
142 if len(parts[0]) == 0:
143 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700144 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800145 self.probe_type = parts[0]
146 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700147 self._bail("probe type must be '', 'p', 't', 'r', " +
148 "or 'u', but got '%s'" % parts[0])
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800149 if self.probe_type == "t":
150 self.tp_category = parts[1]
151 self.tp_event = parts[2]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800152 self.library = "" # kernel
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300153 self.function = "" # from TRACEPOINT_PROBE
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700154 elif self.probe_type == "u":
vkhromov5a2b39e2017-07-14 20:42:29 +0100155 self.library = ':'.join(parts[1:-1])
156 self.usdt_name = parts[-1]
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700157 self.function = "" # no function, just address
158 # We will discover the USDT provider by matching on
159 # the USDT name in the specified library
160 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800161 else:
vkhromov5a2b39e2017-07-14 20:42:29 +0100162 self.library = ':'.join(parts[1:-1])
163 self.function = parts[-1]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800164
yonghong-song2da34262018-06-13 06:12:22 -0700165 # only x64 syscalls needs checking, no other syscall wrapper yet.
166 self.is_syscall_kprobe = False
167 if self.probe_type == "p" and len(self.library) == 0 and \
168 self.function[:10] == "__x64_sys_":
169 self.is_syscall_kprobe = True
170
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700171 def _find_usdt_probe(self):
Sasha Goldshteindd045362016-11-13 05:07:38 -0800172 target = Probe.pid if Probe.pid and Probe.pid != -1 \
173 else Probe.tgid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000174 self.usdt = USDT(path=self.library, pid=target)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300175 for probe in self.usdt.enumerate_probes():
Javier Honduvilla Coto1ef82e22018-04-19 14:14:24 +0200176 if probe.name == self.usdt_name.encode('ascii'):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300177 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700178 self._bail("unrecognized USDT probe %s" % self.usdt_name)
179
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800180 def _parse_filter(self, filt):
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700181 self.filter = self._rewrite_expr(filt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800182
183 def _parse_types(self, fmt):
184 for match in re.finditer(
yonghong-songf7202572018-09-19 08:50:59 -0700185 r'[^%]%(s|u|d|lu|llu|ld|lld|hu|hd|x|lx|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800186 self.types.append(match.group(1))
yonghong-songf7202572018-09-19 08:50:59 -0700187 fmt = re.sub(r'([^%]%)(u|d|lu|llu|ld|lld|hu|hd)', r'\1d', fmt)
188 fmt = re.sub(r'([^%]%)(x|lx|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700189 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800190 self.python_format = fmt.strip('"')
191
192 def _parse_action(self, action):
193 self.values = []
194 self.types = []
195 self.python_format = ""
196 if len(action) == 0:
197 return
198
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800199 action = action.strip()
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700200 match = re.search(r'(\".*?\"),?(.*)', action)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800201 if match is None:
202 self._bail("expected format string in \"s")
203
204 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800205 self._parse_types(self.raw_format)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700206 for part in re.split('(?<!"),', match.group(2)):
207 part = self._rewrite_expr(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800208 if len(part) > 0:
209 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800210
yonghong-song2da34262018-06-13 06:12:22 -0700211 aliases_arg = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530212 "arg1": "PT_REGS_PARM1(ctx)",
213 "arg2": "PT_REGS_PARM2(ctx)",
214 "arg3": "PT_REGS_PARM3(ctx)",
215 "arg4": "PT_REGS_PARM4(ctx)",
216 "arg5": "PT_REGS_PARM5(ctx)",
217 "arg6": "PT_REGS_PARM6(ctx)",
yonghong-song2da34262018-06-13 06:12:22 -0700218 }
219
220 aliases_indarg = {
Prashant Bhole05765ee2018-12-28 01:47:56 +0900221 "arg1": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700222 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM1(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800223 "arg2": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700224 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM2(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800225 "arg3": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700226 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM3(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800227 "arg4": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700228 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM4(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800229 "arg5": "({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_PARM5(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800231 "arg6": "({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_PARM6(_ctx))); _val;})",
233 }
234
235 aliases_common = {
236 "retval": "PT_REGS_RC(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800237 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
238 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
239 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
240 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
Yonghong Songf92fef22018-01-24 20:51:46 -0800241 "$cpu": "bpf_get_smp_processor_id()",
242 "$task" : "((struct task_struct *)bpf_get_current_task())"
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800243 }
244
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700245 def _generate_streq_function(self, string):
246 fname = "streq_%d" % Probe.streq_index
247 Probe.streq_index += 1
248 self.streq_functions += """
Sasha Goldshteinb9aec342017-01-16 18:41:22 +0000249static inline bool %s(char const *ignored, uintptr_t str) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700250 char needle[] = %s;
251 char haystack[sizeof(needle)];
252 bpf_probe_read(&haystack, sizeof(haystack), (void *)str);
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000253 for (int i = 0; i < sizeof(needle) - 1; ++i) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700254 if (needle[i] != haystack[i]) {
255 return false;
256 }
257 }
258 return true;
259}
260 """ % (fname, string)
261 return fname
262
263 def _rewrite_expr(self, expr):
yonghong-song2da34262018-06-13 06:12:22 -0700264 if self.is_syscall_kprobe:
265 for alias, replacement in Probe.aliases_indarg.items():
266 expr = expr.replace(alias, replacement)
267 else:
268 for alias, replacement in Probe.aliases_arg.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700269 # For USDT probes, we replace argN values with the
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300270 # actual arguments for that probe obtained using
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300271 # bpf_readarg_N macros emitted at BPF construction.
yonghong-song2da34262018-06-13 06:12:22 -0700272 if self.probe_type == "u":
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700273 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800274 expr = expr.replace(alias, replacement)
yonghong-song2da34262018-06-13 06:12:22 -0700275 for alias, replacement in Probe.aliases_common.items():
276 expr = expr.replace(alias, replacement)
Nikita V. Shirokov3953c702018-07-27 16:13:47 -0700277 if self.bin_cmp:
278 STRCMP_RE = 'STRCMP\\(\"([^"]+)\\"'
279 else:
280 STRCMP_RE = 'STRCMP\\(("[^"]+\\")'
281 matches = re.finditer(STRCMP_RE, expr)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700282 for match in matches:
283 string = match.group(1)
284 fname = self._generate_streq_function(string)
285 expr = expr.replace("STRCMP", fname, 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800286 return expr
287
yonghong-songf7202572018-09-19 08:50:59 -0700288 p_type = {"u": ct.c_uint, "d": ct.c_int, "lu": ct.c_ulong,
289 "ld": ct.c_long,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300290 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
291 "hu": ct.c_ushort, "hd": ct.c_short,
yonghong-songf7202572018-09-19 08:50:59 -0700292 "x": ct.c_uint, "lx": ct.c_ulong, "llx": ct.c_ulonglong,
293 "c": ct.c_ubyte,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300294 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800295
296 def _generate_python_field_decl(self, idx, fields):
297 field_type = self.types[idx]
298 if field_type == "s":
299 ptype = ct.c_char * self.string_size
300 else:
301 ptype = Probe.p_type[field_type]
302 fields.append(("v%d" % idx, ptype))
303
304 def _generate_python_data_decl(self):
305 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700306 (self._display_function(), self.probe_num)
Teng Qinc200b6c2017-12-16 00:15:55 -0800307 fields = []
308 if self.time_field:
309 fields.append(("timestamp_ns", ct.c_ulonglong))
310 if self.print_cpu:
311 fields.append(("cpu", ct.c_int))
312 fields.extend([
Mark Draytonaa6c9162016-11-03 15:36:29 +0000313 ("tgid", ct.c_uint),
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800314 ("pid", ct.c_uint),
315 ("comm", ct.c_char * 16) # TASK_COMM_LEN
Teng Qinc200b6c2017-12-16 00:15:55 -0800316 ])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800317 for i in range(0, len(self.types)):
318 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700319 if self.kernel_stack:
320 fields.append(("kernel_stack_id", ct.c_int))
321 if self.user_stack:
322 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800323 return type(self.python_struct_name, (ct.Structure,),
324 dict(_fields_=fields))
325
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300326 c_type = {"u": "unsigned int", "d": "int",
yonghong-songf7202572018-09-19 08:50:59 -0700327 "lu": "unsigned long", "ld": "long",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300328 "llu": "unsigned long long", "lld": "long long",
329 "hu": "unsigned short", "hd": "short",
yonghong-songf7202572018-09-19 08:50:59 -0700330 "x": "unsigned int", "lx": "unsigned long",
331 "llx": "unsigned long long",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300332 "c": "char", "K": "unsigned long long",
333 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800334 fmt_types = c_type.keys()
335
336 def _generate_field_decl(self, idx):
337 field_type = self.types[idx]
338 if field_type == "s":
339 return "char v%d[%d];\n" % (idx, self.string_size)
340 if field_type in Probe.fmt_types:
341 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
342 self._bail("unrecognized format specifier %s" % field_type)
343
344 def _generate_data_decl(self):
345 # The BPF program will populate values into the struct
346 # according to the format string, and the Python program will
347 # construct the final display string.
348 self.events_name = "%s_events" % self.probe_name
349 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700350 self.stacks_name = "%s_stacks" % self.probe_name
vijunag9924e642019-01-23 12:35:33 +0530351 stack_type = "BPF_STACK_TRACE" if self.build_id_enabled is False \
352 else "BPF_STACK_TRACE_BUILDID"
353 stack_table = "%s(%s, 1024);" % (stack_type,self.stacks_name) \
Teng Qin6b0ed372016-09-29 21:30:13 -0700354 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800355 data_fields = ""
356 for i, field_type in enumerate(self.types):
357 data_fields += " " + \
358 self._generate_field_decl(i)
Teng Qinc200b6c2017-12-16 00:15:55 -0800359 time_str = "u64 timestamp_ns;" if self.time_field else ""
360 cpu_str = "int cpu;" if self.print_cpu else ""
Teng Qin6b0ed372016-09-29 21:30:13 -0700361 kernel_stack_str = " int kernel_stack_id;" \
362 if self.kernel_stack else ""
363 user_stack_str = " int user_stack_id;" \
364 if self.user_stack else ""
365
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800366 text = """
367struct %s
368{
Teng Qinc200b6c2017-12-16 00:15:55 -0800369%s
370%s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000371 u32 tgid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800372 u32 pid;
373 char comm[TASK_COMM_LEN];
374%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700375%s
376%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800377};
378
379BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700380%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800381"""
Teng Qinc200b6c2017-12-16 00:15:55 -0800382 return text % (self.struct_name, time_str, cpu_str, data_fields,
Teng Qin6b0ed372016-09-29 21:30:13 -0700383 kernel_stack_str, user_stack_str,
384 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800385
386 def _generate_field_assign(self, idx):
387 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300388 expr = self.values[idx].strip()
389 text = ""
390 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000391 arg_index = int(expr[3])
392 arg_ctype = self.usdt.get_probe_arg_ctype(
393 self.usdt_name, arg_index - 1)
394 text = (" %s %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300395 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000396 % (arg_ctype, expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300397
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800398 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300399 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800400 if (%s != 0) {
yonghong-song61484e12018-09-17 22:24:31 -0700401 void *__tmp = (void *)%s;
402 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), __tmp);
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800403 }
yonghong-song61484e12018-09-17 22:24:31 -0700404 """ % (expr, expr, idx, idx)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800405 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300406 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800407 (idx, Probe.c_type[field_type], expr)
408 self._bail("unrecognized field type %s" % field_type)
409
Teng Qin0615bff2016-09-28 08:19:40 -0700410 def _generate_usdt_filter_read(self):
411 text = ""
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000412 if self.probe_type != "u":
413 return text
yonghong-song2da34262018-06-13 06:12:22 -0700414 for arg, _ in Probe.aliases_arg.items():
415 if not (arg in self.filter):
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000416 continue
417 arg_index = int(arg.replace("arg", ""))
418 arg_ctype = self.usdt.get_probe_arg_ctype(
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000419 self.usdt_name, arg_index - 1)
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000420 if not arg_ctype:
421 self._bail("Unable to determine type of {} "
422 "in the filter".format(arg))
423 text += """
Teng Qin0615bff2016-09-28 08:19:40 -0700424 {} {}_filter;
425 bpf_usdt_readarg({}, ctx, &{}_filter);
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000426 """.format(arg_ctype, arg, arg_index, arg)
427 self.filter = self.filter.replace(
428 arg, "{}_filter".format(arg))
Teng Qin0615bff2016-09-28 08:19:40 -0700429 return text
430
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700431 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800432 data_decl = self._generate_data_decl()
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000433 if Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800434 pid_filter = """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800435 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300436 """ % Probe.pid
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000437 # uprobes can have a built-in tgid filter passed to
438 # attach_uprobe, hence the check here -- for kprobes, we
439 # need to do the tgid test by hand:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000440 elif len(self.library) == 0 and Probe.tgid != -1:
441 pid_filter = """
442 if (__tgid != %d) { return 0; }
443 """ % Probe.tgid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800444 elif not include_self:
445 pid_filter = """
Mark Draytonaa6c9162016-11-03 15:36:29 +0000446 if (__tgid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300447 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800448 else:
449 pid_filter = ""
450
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700451 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700452 signature = "struct pt_regs *ctx"
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000453 if self.signature:
454 signature += ", " + self.signature
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700455
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800456 data_fields = ""
457 for i, expr in enumerate(self.values):
458 data_fields += self._generate_field_assign(i)
459
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300460 if self.probe_type == "t":
461 heading = "TRACEPOINT_PROBE(%s, %s)" % \
462 (self.tp_category, self.tp_event)
463 ctx_name = "args"
464 else:
465 heading = "int %s(%s)" % (self.probe_name, signature)
466 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300467
Teng Qinc200b6c2017-12-16 00:15:55 -0800468 time_str = """
469 __data.timestamp_ns = bpf_ktime_get_ns();""" if self.time_field else ""
470 cpu_str = """
471 __data.cpu = bpf_get_smp_processor_id();""" if self.print_cpu else ""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300472 stack_trace = ""
473 if self.user_stack:
474 stack_trace += """
475 __data.user_stack_id = %s.get_stackid(
476 %s, BPF_F_REUSE_STACKID | BPF_F_USER_STACK
477 );""" % (self.stacks_name, ctx_name)
478 if self.kernel_stack:
479 stack_trace += """
480 __data.kernel_stack_id = %s.get_stackid(
481 %s, BPF_F_REUSE_STACKID
482 );""" % (self.stacks_name, ctx_name)
483
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300484 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800485{
Mark Draytonaa6c9162016-11-03 15:36:29 +0000486 u64 __pid_tgid = bpf_get_current_pid_tgid();
487 u32 __tgid = __pid_tgid >> 32;
488 u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800489 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800490 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700491 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800492 if (!(%s)) return 0;
493
494 struct %s __data = {0};
Teng Qinc200b6c2017-12-16 00:15:55 -0800495 %s
496 %s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000497 __data.tgid = __tgid;
498 __data.pid = __pid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800499 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
500%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700501%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300502 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800503 return 0;
504}
505"""
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300506 text = text % (pid_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700507 self._generate_usdt_filter_read(), self.filter,
Teng Qinc200b6c2017-12-16 00:15:55 -0800508 self.struct_name, time_str, cpu_str, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300509 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700510
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700511 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800512
513 @classmethod
514 def _time_off_str(cls, timestamp_ns):
515 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
516
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800517 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700518 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800519 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700520 elif self.probe_type == 'u':
521 return self.usdt_name
522 else: # self.probe_type == 't'
523 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800524
Mark Draytonaa6c9162016-11-03 15:36:29 +0000525 def print_stack(self, bpf, stack_id, tgid):
Teng Qin6b0ed372016-09-29 21:30:13 -0700526 if stack_id < 0:
Mirek Klimose5382282018-01-26 14:52:50 -0800527 print(" %d" % stack_id)
528 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700529
530 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
531 for addr in stack:
Mirek Klimose5382282018-01-26 14:52:50 -0800532 print(" ", end="")
533 if Probe.print_address:
534 print("%16x " % addr, end="")
535 print("%s" % (bpf.sym(addr, tgid,
536 show_module=True, show_offset=True)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700537
Mark Draytonaa6c9162016-11-03 15:36:29 +0000538 def _format_message(self, bpf, tgid, values):
539 # Replace each %K with kernel sym and %U with user sym in tgid
Rafael Fonsecaaee5ecf2017-02-08 16:14:31 +0100540 kernel_placeholders = [i for i, t in enumerate(self.types)
541 if t == 'K']
542 user_placeholders = [i for i, t in enumerate(self.types)
543 if t == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700544 for kp in kernel_placeholders:
Sasha Goldshtein01553852017-02-09 03:58:09 -0500545 values[kp] = bpf.ksym(values[kp], show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700546 for up in user_placeholders:
Sasha Goldshtein1e34f4e2017-02-09 00:21:49 -0500547 values[up] = bpf.sym(values[up], tgid,
Sasha Goldshtein01553852017-02-09 03:58:09 -0500548 show_module=True, show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700549 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700550
551 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800552 # Cast as the generated structure type and display
553 # according to the format string in the probe.
554 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
555 values = map(lambda i: getattr(event, "v%d" % i),
556 range(0, len(self.values)))
Mark Draytonaa6c9162016-11-03 15:36:29 +0000557 msg = self._format_message(bpf, event.tgid, values)
Teng Qinc200b6c2017-12-16 00:15:55 -0800558 if Probe.print_time:
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000559 time = strftime("%H:%M:%S") if Probe.use_localtime else \
560 Probe._time_off_str(event.timestamp_ns)
Teng Qinc200b6c2017-12-16 00:15:55 -0800561 print("%-8s " % time[:8], end="")
562 if Probe.print_cpu:
563 print("%-3s " % event.cpu, end="")
564 print("%-7d %-7d %-15s %-16s %s" %
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200565 (event.tgid, event.pid,
566 event.comm.decode('utf-8', 'replace'),
Teng Qinc200b6c2017-12-16 00:15:55 -0800567 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800568
Teng Qin6b0ed372016-09-29 21:30:13 -0700569 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700570 self.print_stack(bpf, event.kernel_stack_id, -1)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000571 if self.user_stack:
572 self.print_stack(bpf, event.user_stack_id, event.tgid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700573 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700574 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700575
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800576 Probe.event_count += 1
577 if Probe.max_events is not None and \
578 Probe.event_count >= Probe.max_events:
579 exit()
580
581 def attach(self, bpf, verbose):
582 if len(self.library) == 0:
583 self._attach_k(bpf)
584 else:
585 self._attach_u(bpf)
586 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700587 callback = partial(self.print_event, bpf)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000588 bpf[self.events_name].open_perf_buffer(callback,
589 page_cnt=self.page_cnt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800590
591 def _attach_k(self, bpf):
592 if self.probe_type == "r":
593 bpf.attach_kretprobe(event=self.function,
594 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300595 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800596 bpf.attach_kprobe(event=self.function,
597 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300598 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800599
600 def _attach_u(self, bpf):
601 libpath = BPF.find_library(self.library)
602 if libpath is None:
603 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300604 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800605 if libpath is None or len(libpath) == 0:
606 self._bail("unable to find library %s" % self.library)
607
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700608 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300609 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700610 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800611 bpf.attach_uretprobe(name=libpath,
612 sym=self.function,
613 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000614 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800615 else:
616 bpf.attach_uprobe(name=libpath,
617 sym=self.function,
618 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000619 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800620
621class Tool(object):
Mark Drayton5f5687e2017-02-20 18:13:03 +0000622 DEFAULT_PERF_BUFFER_PAGES = 64
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800623 examples = """
624EXAMPLES:
625
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800626trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800627 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800628trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800629 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800630trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800631 Trace the read syscall and print a message for reads >20000 bytes
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000632trace 'r::do_sys_open "%llx", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800633 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800634trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800635 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800636trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800637 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800638trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
639 Trace the write() call from libc to monitor writes to STDOUT
Mark Draytonaa6c9162016-11-03 15:36:29 +0000640trace 'r::__kmalloc (retval == 0) "kmalloc failed!"'
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800641 Trace returns from __kmalloc which returned a null pointer
Mark Draytonaa6c9162016-11-03 15:36:29 +0000642trace 'r:c:malloc (retval) "allocated = %x", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800643 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300644trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800645 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700646trace 'u:pthread:pthread_create (arg4 != 0)'
647 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000648trace 'p::SyS_nanosleep(struct timespec *ts) "sleep for %lld ns", ts->tv_nsec'
649 Trace the nanosleep syscall and print the sleep duration in ns
Yonghong Songf4470dc2017-12-13 14:12:13 -0800650trace -I 'linux/fs.h' \\
651 'p::uprobe_register(struct inode *inode) "a_ops = %llx", inode->i_mapping->a_ops'
652 Trace the uprobe_register inode mapping ops, and the symbol can be found
653 in /proc/kallsyms
654trace -I 'kernel/sched/sched.h' \\
655 'p::__account_cfs_rq_runtime(struct cfs_rq *cfs_rq) "%d", cfs_rq->runtime_remaining'
656 Trace the cfs scheduling runqueue remaining runtime. The struct cfs_rq is defined
657 in kernel/sched/sched.h which is in kernel source tree and not in kernel-devel
658 package. So this command needs to run at the kernel source tree root directory
659 so that the added header file can be found by the compiler.
tehnerd86293f02018-01-23 21:21:58 -0800660trace -I 'net/sock.h' \\
661 'udpv6_sendmsg(struct sock *sk) (sk->sk_dport == 13568)'
662 Trace udpv6 sendmsg calls only if socket's destination port is equal
663 to 53 (DNS; 13568 in big endian order)
Yonghong Songf92fef22018-01-24 20:51:46 -0800664trace -I 'linux/fs_struct.h' 'mntns_install "users = %d", $task->fs->users'
665 Trace the number of users accessing the file system of the current task
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800666"""
667
668 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300669 parser = argparse.ArgumentParser(description="Attach to " +
670 "functions and print trace messages.",
671 formatter_class=argparse.RawDescriptionHelpFormatter,
672 epilog=Tool.examples)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000673 parser.add_argument("-b", "--buffer-pages", type=int,
674 default=Tool.DEFAULT_PERF_BUFFER_PAGES,
675 help="number of pages to use for perf_events ring buffer "
676 "(default: %(default)d)")
Mark Draytonaa6c9162016-11-03 15:36:29 +0000677 # we'll refer to the userspace concepts of "pid" and "tid" by
678 # their kernel names -- tgid and pid -- inside the script
679 parser.add_argument("-p", "--pid", type=int, metavar="PID",
680 dest="tgid", help="id of the process to trace (optional)")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000681 parser.add_argument("-L", "--tid", type=int, metavar="TID",
Mark Draytonaa6c9162016-11-03 15:36:29 +0000682 dest="pid", help="id of the thread to trace (optional)")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800683 parser.add_argument("-v", "--verbose", action="store_true",
684 help="print resulting BPF program code before executing")
685 parser.add_argument("-Z", "--string-size", type=int,
686 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300687 parser.add_argument("-S", "--include-self",
688 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800689 help="do not filter trace's own pid from the trace")
690 parser.add_argument("-M", "--max-events", type=int,
691 help="number of events to print before quitting")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000692 parser.add_argument("-t", "--timestamp", action="store_true",
693 help="print timestamp column (offset from trace start)")
694 parser.add_argument("-T", "--time", action="store_true",
695 help="print time column")
Teng Qinc200b6c2017-12-16 00:15:55 -0800696 parser.add_argument("-C", "--print_cpu", action="store_true",
697 help="print CPU id")
Nikita V. Shirokov3953c702018-07-27 16:13:47 -0700698 parser.add_argument("-B", "--bin_cmp", action="store_true",
699 help="allow to use STRCMP with binary values")
vijunag9924e642019-01-23 12:35:33 +0530700 parser.add_argument('-s', "--sym_file_list", type=str, \
701 metavar="SYM_FILE_LIST", dest="sym_file_list", \
702 help="coma separated list of symbol files to use \
703 for symbol resolution")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300704 parser.add_argument("-K", "--kernel-stack",
705 action="store_true", help="output kernel stack trace")
706 parser.add_argument("-U", "--user-stack",
707 action="store_true", help="output user stack trace")
Mirek Klimose5382282018-01-26 14:52:50 -0800708 parser.add_argument("-a", "--address", action="store_true",
709 help="print virtual address in stacks")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800710 parser.add_argument(metavar="probe", dest="probes", nargs="+",
711 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300712 parser.add_argument("-I", "--include", action="append",
713 metavar="header",
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300714 help="additional header files to include in the BPF program "
Yonghong Songf4470dc2017-12-13 14:12:13 -0800715 "as either full path, "
716 "or relative to current working directory, "
717 "or relative to default kernel header search path")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100718 parser.add_argument("--ebpf", action="store_true",
719 help=argparse.SUPPRESS)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800720 self.args = parser.parse_args()
Mark Draytonaa6c9162016-11-03 15:36:29 +0000721 if self.args.tgid and self.args.pid:
Yonghong Songf4470dc2017-12-13 14:12:13 -0800722 parser.error("only one of -p and -L may be specified")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800723
724 def _create_probes(self):
725 Probe.configure(self.args)
726 self.probes = []
727 for probe_spec in self.args.probes:
728 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700729 probe_spec, self.args.string_size,
730 self.args.kernel_stack, self.args.user_stack))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800731
732 def _generate_program(self):
733 self.program = """
734#include <linux/ptrace.h>
735#include <linux/sched.h> /* For TASK_COMM_LEN */
736
737"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300738 for include in (self.args.include or []):
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300739 if include.startswith((".", "/")):
740 include = os.path.abspath(include)
741 self.program += "#include \"%s\"\n" % include
742 else:
743 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700744 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800745 map(lambda p: p.raw_probe, self.probes))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800746 for probe in self.probes:
747 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700748 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800749
Nathan Scottcf0792f2018-02-02 16:56:50 +1100750 if self.args.verbose or self.args.ebpf:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800751 print(self.program)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100752 if self.args.ebpf:
753 exit()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800754
755 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300756 usdt_contexts = []
757 for probe in self.probes:
758 if probe.usdt:
759 # USDT probes must be enabled before the BPF object
760 # is initialized, because that's where the actual
761 # uprobe is being attached.
762 probe.usdt.enable_probe(
763 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300764 if self.args.verbose:
765 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300766 usdt_contexts.append(probe.usdt)
767 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
vijunag9924e642019-01-23 12:35:33 +0530768 if self.args.sym_file_list is not None:
769 print("Note: Kernel bpf will report stack map with ip/build_id")
770 map(lambda x: self.bpf.add_module(x), self.args.sym_file_list.split(','))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800771 for probe in self.probes:
772 if self.args.verbose:
773 print(probe)
774 probe.attach(self.bpf, self.args.verbose)
775
776 def _main_loop(self):
777 all_probes_trivial = all(map(Probe.is_default_action,
778 self.probes))
779
780 # Print header
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000781 if self.args.timestamp or self.args.time:
Teng Qinc200b6c2017-12-16 00:15:55 -0800782 print("%-8s " % "TIME", end="");
783 if self.args.print_cpu:
784 print("%-3s " % "CPU", end="");
785 print("%-7s %-7s %-15s %-16s %s" %
786 ("PID", "TID", "COMM", "FUNC",
787 "-" if not all_probes_trivial else ""))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800788
789 while True:
Teng Qindbf00292018-02-28 21:47:50 -0800790 self.bpf.perf_buffer_poll()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800791
792 def run(self):
793 try:
794 self._create_probes()
795 self._generate_program()
796 self._attach_probes()
797 self._main_loop()
798 except:
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500799 exc_info = sys.exc_info()
800 sys_exit = exc_info[0] is SystemExit
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800801 if self.args.verbose:
802 traceback.print_exc()
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500803 elif not sys_exit:
804 print(exc_info[1])
805 exit(0 if sys_exit else 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800806
807if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300808 Tool().run()