blob: 029194c77cbdafe45a8a37f5093caee114bfc723 [file] [log] [blame]
Sasha Goldshtein38847f02016-02-22 02:19:24 -08001#!/usr/bin/env python
2#
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]
7# [-M MAX_EVENTS] [-T] [-t] [-K] [-U] [-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
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +030013from bcc import BPF, USDT
Teng Qin6b0ed372016-09-29 21:30:13 -070014from functools import partial
Sasha Goldshtein38847f02016-02-22 02:19:24 -080015from time import sleep, strftime
16import argparse
17import re
18import ctypes as ct
19import os
20import traceback
21import sys
22
Sasha Goldshtein38847f02016-02-22 02:19:24 -080023class Probe(object):
24 probe_count = 0
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070025 streq_index = 0
Sasha Goldshtein38847f02016-02-22 02:19:24 -080026 max_events = None
27 event_count = 0
28 first_ts = 0
29 use_localtime = True
Mark Draytonaa6c9162016-11-03 15:36:29 +000030 tgid = -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070031 pid = -1
Mark Drayton5f5687e2017-02-20 18:13:03 +000032 page_cnt = None
Sasha Goldshtein38847f02016-02-22 02:19:24 -080033
34 @classmethod
35 def configure(cls, args):
36 cls.max_events = args.max_events
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +000037 cls.print_time = args.timestamp or args.time
38 cls.use_localtime = not args.timestamp
Sasha Goldshtein60c41922017-02-09 04:19:53 -050039 cls.first_ts = BPF.monotonic_time()
Mark Draytonaa6c9162016-11-03 15:36:29 +000040 cls.tgid = args.tgid or -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070041 cls.pid = args.pid or -1
Mark Drayton5f5687e2017-02-20 18:13:03 +000042 cls.page_cnt = args.buffer_pages
Sasha Goldshtein38847f02016-02-22 02:19:24 -080043
Teng Qin6b0ed372016-09-29 21:30:13 -070044 def __init__(self, probe, string_size, kernel_stack, user_stack):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +030045 self.usdt = None
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070046 self.streq_functions = ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -080047 self.raw_probe = probe
48 self.string_size = string_size
Teng Qin6b0ed372016-09-29 21:30:13 -070049 self.kernel_stack = kernel_stack
50 self.user_stack = user_stack
Sasha Goldshtein38847f02016-02-22 02:19:24 -080051 Probe.probe_count += 1
52 self._parse_probe()
53 self.probe_num = Probe.probe_count
54 self.probe_name = "probe_%s_%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070055 (self._display_function(), self.probe_num)
Sasha Goldshtein3fa7ba12017-01-14 11:17:40 +000056 self.probe_name = re.sub(r'[^A-Za-z0-9_]', '_', self.probe_name)
Sasha Goldshtein38847f02016-02-22 02:19:24 -080057
58 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070059 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
60 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080061 self.types, self.values)
62
63 def is_default_action(self):
64 return self.python_format == ""
65
66 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070067 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080068 (self.raw_probe, error))
69
70 def _parse_probe(self):
71 text = self.raw_probe
72
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000073 # There might be a function signature preceding the actual
74 # filter/print part, or not. Find the probe specifier first --
75 # it ends with either a space or an open paren ( for the
76 # function signature part.
77 # opt. signature
78 # probespec | rest
79 # --------- ---------- --
80 (spec, sig, rest) = re.match(r'([^ \t\(]+)(\([^\(]*\))?(.*)',
81 text).groups()
Sasha Goldshtein38847f02016-02-22 02:19:24 -080082
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000083 self._parse_spec(spec)
84 self.signature = sig[1:-1] if sig else None # remove the parens
85 if self.signature and self.probe_type in ['u', 't']:
86 self._bail("USDT and tracepoint probes can't have " +
87 "a function signature; use arg1, arg2, " +
88 "... instead")
89
90 text = rest.lstrip()
Sasha Goldshtein38847f02016-02-22 02:19:24 -080091 # If we now have a (, wait for the balanced closing ) and that
92 # will be the predicate
93 self.filter = None
94 if len(text) > 0 and text[0] == "(":
95 balance = 1
96 for i in range(1, len(text)):
97 if text[i] == "(":
98 balance += 1
99 if text[i] == ")":
100 balance -= 1
101 if balance == 0:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300102 self._parse_filter(text[:i + 1])
103 text = text[i + 1:]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800104 break
105 if self.filter is None:
106 self._bail("unmatched end of predicate")
107
108 if self.filter is None:
109 self.filter = "1"
110
111 # The remainder of the text is the printf action
112 self._parse_action(text.lstrip())
113
114 def _parse_spec(self, spec):
115 parts = spec.split(":")
116 # Two special cases: 'func' means 'p::func', 'lib:func' means
117 # 'p:lib:func'. Other combinations need to provide an empty
118 # value between delimiters, e.g. 'r::func' for a kretprobe on
119 # the function func.
120 if len(parts) == 1:
121 parts = ["p", "", parts[0]]
122 elif len(parts) == 2:
123 parts = ["p", parts[0], parts[1]]
124 if len(parts[0]) == 0:
125 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700126 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800127 self.probe_type = parts[0]
128 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700129 self._bail("probe type must be '', 'p', 't', 'r', " +
130 "or 'u', but got '%s'" % parts[0])
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800131 if self.probe_type == "t":
132 self.tp_category = parts[1]
133 self.tp_event = parts[2]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800134 self.library = "" # kernel
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300135 self.function = "" # from TRACEPOINT_PROBE
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700136 elif self.probe_type == "u":
137 self.library = parts[1]
138 self.usdt_name = parts[2]
139 self.function = "" # no function, just address
140 # We will discover the USDT provider by matching on
141 # the USDT name in the specified library
142 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800143 else:
144 self.library = parts[1]
145 self.function = parts[2]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800146
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700147 def _find_usdt_probe(self):
Sasha Goldshteindd045362016-11-13 05:07:38 -0800148 target = Probe.pid if Probe.pid and Probe.pid != -1 \
149 else Probe.tgid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000150 self.usdt = USDT(path=self.library, pid=target)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300151 for probe in self.usdt.enumerate_probes():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700152 if probe.name == self.usdt_name:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300153 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700154 self._bail("unrecognized USDT probe %s" % self.usdt_name)
155
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800156 def _parse_filter(self, filt):
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700157 self.filter = self._rewrite_expr(filt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800158
159 def _parse_types(self, fmt):
160 for match in re.finditer(
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300161 r'[^%]%(s|u|d|llu|lld|hu|hd|x|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800162 self.types.append(match.group(1))
163 fmt = re.sub(r'([^%]%)(u|d|llu|lld|hu|hd)', r'\1d', fmt)
164 fmt = re.sub(r'([^%]%)(x|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700165 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800166 self.python_format = fmt.strip('"')
167
168 def _parse_action(self, action):
169 self.values = []
170 self.types = []
171 self.python_format = ""
172 if len(action) == 0:
173 return
174
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800175 action = action.strip()
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700176 match = re.search(r'(\".*?\"),?(.*)', action)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800177 if match is None:
178 self._bail("expected format string in \"s")
179
180 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800181 self._parse_types(self.raw_format)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700182 for part in re.split('(?<!"),', match.group(2)):
183 part = self._rewrite_expr(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800184 if len(part) > 0:
185 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800186
187 aliases = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530188 "retval": "PT_REGS_RC(ctx)",
189 "arg1": "PT_REGS_PARM1(ctx)",
190 "arg2": "PT_REGS_PARM2(ctx)",
191 "arg3": "PT_REGS_PARM3(ctx)",
192 "arg4": "PT_REGS_PARM4(ctx)",
193 "arg5": "PT_REGS_PARM5(ctx)",
194 "arg6": "PT_REGS_PARM6(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800195 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
196 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
197 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
198 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
199 "$cpu": "bpf_get_smp_processor_id()"
200 }
201
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700202 def _generate_streq_function(self, string):
203 fname = "streq_%d" % Probe.streq_index
204 Probe.streq_index += 1
205 self.streq_functions += """
Sasha Goldshteinb9aec342017-01-16 18:41:22 +0000206static inline bool %s(char const *ignored, uintptr_t str) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700207 char needle[] = %s;
208 char haystack[sizeof(needle)];
209 bpf_probe_read(&haystack, sizeof(haystack), (void *)str);
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000210 for (int i = 0; i < sizeof(needle) - 1; ++i) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700211 if (needle[i] != haystack[i]) {
212 return false;
213 }
214 }
215 return true;
216}
217 """ % (fname, string)
218 return fname
219
220 def _rewrite_expr(self, expr):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800221 for alias, replacement in Probe.aliases.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700222 # For USDT probes, we replace argN values with the
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300223 # actual arguments for that probe obtained using
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300224 # bpf_readarg_N macros emitted at BPF construction.
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700225 if alias.startswith("arg") and self.probe_type == "u":
226 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800227 expr = expr.replace(alias, replacement)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700228 matches = re.finditer('STRCMP\\(("[^"]+\\")', expr)
229 for match in matches:
230 string = match.group(1)
231 fname = self._generate_streq_function(string)
232 expr = expr.replace("STRCMP", fname, 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800233 return expr
234
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300235 p_type = {"u": ct.c_uint, "d": ct.c_int,
236 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
237 "hu": ct.c_ushort, "hd": ct.c_short,
238 "x": ct.c_uint, "llx": ct.c_ulonglong, "c": ct.c_ubyte,
239 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800240
241 def _generate_python_field_decl(self, idx, fields):
242 field_type = self.types[idx]
243 if field_type == "s":
244 ptype = ct.c_char * self.string_size
245 else:
246 ptype = Probe.p_type[field_type]
247 fields.append(("v%d" % idx, ptype))
248
249 def _generate_python_data_decl(self):
250 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700251 (self._display_function(), self.probe_num)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800252 fields = [
253 ("timestamp_ns", ct.c_ulonglong),
Mark Draytonaa6c9162016-11-03 15:36:29 +0000254 ("tgid", ct.c_uint),
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800255 ("pid", ct.c_uint),
256 ("comm", ct.c_char * 16) # TASK_COMM_LEN
257 ]
258 for i in range(0, len(self.types)):
259 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700260 if self.kernel_stack:
261 fields.append(("kernel_stack_id", ct.c_int))
262 if self.user_stack:
263 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800264 return type(self.python_struct_name, (ct.Structure,),
265 dict(_fields_=fields))
266
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300267 c_type = {"u": "unsigned int", "d": "int",
268 "llu": "unsigned long long", "lld": "long long",
269 "hu": "unsigned short", "hd": "short",
270 "x": "unsigned int", "llx": "unsigned long long",
271 "c": "char", "K": "unsigned long long",
272 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800273 fmt_types = c_type.keys()
274
275 def _generate_field_decl(self, idx):
276 field_type = self.types[idx]
277 if field_type == "s":
278 return "char v%d[%d];\n" % (idx, self.string_size)
279 if field_type in Probe.fmt_types:
280 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
281 self._bail("unrecognized format specifier %s" % field_type)
282
283 def _generate_data_decl(self):
284 # The BPF program will populate values into the struct
285 # according to the format string, and the Python program will
286 # construct the final display string.
287 self.events_name = "%s_events" % self.probe_name
288 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700289 self.stacks_name = "%s_stacks" % self.probe_name
290 stack_table = "BPF_STACK_TRACE(%s, 1024);" % self.stacks_name \
291 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800292 data_fields = ""
293 for i, field_type in enumerate(self.types):
294 data_fields += " " + \
295 self._generate_field_decl(i)
296
Teng Qin6b0ed372016-09-29 21:30:13 -0700297 kernel_stack_str = " int kernel_stack_id;" \
298 if self.kernel_stack else ""
299 user_stack_str = " int user_stack_id;" \
300 if self.user_stack else ""
301
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800302 text = """
303struct %s
304{
305 u64 timestamp_ns;
Mark Draytonaa6c9162016-11-03 15:36:29 +0000306 u32 tgid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800307 u32 pid;
308 char comm[TASK_COMM_LEN];
309%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700310%s
311%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800312};
313
314BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700315%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800316"""
Teng Qin6b0ed372016-09-29 21:30:13 -0700317 return text % (self.struct_name, data_fields,
318 kernel_stack_str, user_stack_str,
319 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800320
321 def _generate_field_assign(self, idx):
322 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300323 expr = self.values[idx].strip()
324 text = ""
325 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000326 arg_index = int(expr[3])
327 arg_ctype = self.usdt.get_probe_arg_ctype(
328 self.usdt_name, arg_index - 1)
329 text = (" %s %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300330 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000331 % (arg_ctype, expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300332
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800333 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300334 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800335 if (%s != 0) {
336 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), (void *)%s);
337 }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300338 """ % (expr, idx, idx, expr)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800339 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300340 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800341 (idx, Probe.c_type[field_type], expr)
342 self._bail("unrecognized field type %s" % field_type)
343
Teng Qin0615bff2016-09-28 08:19:40 -0700344 def _generate_usdt_filter_read(self):
345 text = ""
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000346 if self.probe_type != "u":
347 return text
348 for arg, _ in Probe.aliases.items():
349 if not (arg.startswith("arg") and
350 (arg in self.filter)):
351 continue
352 arg_index = int(arg.replace("arg", ""))
353 arg_ctype = self.usdt.get_probe_arg_ctype(
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000354 self.usdt_name, arg_index - 1)
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000355 if not arg_ctype:
356 self._bail("Unable to determine type of {} "
357 "in the filter".format(arg))
358 text += """
Teng Qin0615bff2016-09-28 08:19:40 -0700359 {} {}_filter;
360 bpf_usdt_readarg({}, ctx, &{}_filter);
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000361 """.format(arg_ctype, arg, arg_index, arg)
362 self.filter = self.filter.replace(
363 arg, "{}_filter".format(arg))
Teng Qin0615bff2016-09-28 08:19:40 -0700364 return text
365
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700366 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800367 data_decl = self._generate_data_decl()
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000368 if Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800369 pid_filter = """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800370 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300371 """ % Probe.pid
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000372 # uprobes can have a built-in tgid filter passed to
373 # attach_uprobe, hence the check here -- for kprobes, we
374 # need to do the tgid test by hand:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000375 elif len(self.library) == 0 and Probe.tgid != -1:
376 pid_filter = """
377 if (__tgid != %d) { return 0; }
378 """ % Probe.tgid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800379 elif not include_self:
380 pid_filter = """
Mark Draytonaa6c9162016-11-03 15:36:29 +0000381 if (__tgid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300382 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800383 else:
384 pid_filter = ""
385
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700386 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700387 signature = "struct pt_regs *ctx"
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000388 if self.signature:
389 signature += ", " + self.signature
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700390
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800391 data_fields = ""
392 for i, expr in enumerate(self.values):
393 data_fields += self._generate_field_assign(i)
394
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300395 if self.probe_type == "t":
396 heading = "TRACEPOINT_PROBE(%s, %s)" % \
397 (self.tp_category, self.tp_event)
398 ctx_name = "args"
399 else:
400 heading = "int %s(%s)" % (self.probe_name, signature)
401 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300402
403 stack_trace = ""
404 if self.user_stack:
405 stack_trace += """
406 __data.user_stack_id = %s.get_stackid(
407 %s, BPF_F_REUSE_STACKID | BPF_F_USER_STACK
408 );""" % (self.stacks_name, ctx_name)
409 if self.kernel_stack:
410 stack_trace += """
411 __data.kernel_stack_id = %s.get_stackid(
412 %s, BPF_F_REUSE_STACKID
413 );""" % (self.stacks_name, ctx_name)
414
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300415 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800416{
Mark Draytonaa6c9162016-11-03 15:36:29 +0000417 u64 __pid_tgid = bpf_get_current_pid_tgid();
418 u32 __tgid = __pid_tgid >> 32;
419 u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800420 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800421 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700422 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800423 if (!(%s)) return 0;
424
425 struct %s __data = {0};
426 __data.timestamp_ns = bpf_ktime_get_ns();
Mark Draytonaa6c9162016-11-03 15:36:29 +0000427 __data.tgid = __tgid;
428 __data.pid = __pid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800429 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
430%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700431%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300432 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800433 return 0;
434}
435"""
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300436 text = text % (pid_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700437 self._generate_usdt_filter_read(), self.filter,
Teng Qin6b0ed372016-09-29 21:30:13 -0700438 self.struct_name, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300439 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700440
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700441 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800442
443 @classmethod
444 def _time_off_str(cls, timestamp_ns):
445 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
446
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800447 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700448 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800449 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700450 elif self.probe_type == 'u':
451 return self.usdt_name
452 else: # self.probe_type == 't'
453 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800454
Mark Draytonaa6c9162016-11-03 15:36:29 +0000455 def print_stack(self, bpf, stack_id, tgid):
Teng Qin6b0ed372016-09-29 21:30:13 -0700456 if stack_id < 0:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700457 print(" %d" % stack_id)
458 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700459
460 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
461 for addr in stack:
Sasha Goldshtein1e34f4e2017-02-09 00:21:49 -0500462 print(" %s" % (bpf.sym(addr, tgid,
Sasha Goldshtein01553852017-02-09 03:58:09 -0500463 show_module=True, show_offset=True)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700464
Mark Draytonaa6c9162016-11-03 15:36:29 +0000465 def _format_message(self, bpf, tgid, values):
466 # Replace each %K with kernel sym and %U with user sym in tgid
Rafael Fonsecaaee5ecf2017-02-08 16:14:31 +0100467 kernel_placeholders = [i for i, t in enumerate(self.types)
468 if t == 'K']
469 user_placeholders = [i for i, t in enumerate(self.types)
470 if t == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700471 for kp in kernel_placeholders:
Sasha Goldshtein01553852017-02-09 03:58:09 -0500472 values[kp] = bpf.ksym(values[kp], show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700473 for up in user_placeholders:
Sasha Goldshtein1e34f4e2017-02-09 00:21:49 -0500474 values[up] = bpf.sym(values[up], tgid,
Sasha Goldshtein01553852017-02-09 03:58:09 -0500475 show_module=True, show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700476 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700477
478 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800479 # Cast as the generated structure type and display
480 # according to the format string in the probe.
481 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
482 values = map(lambda i: getattr(event, "v%d" % i),
483 range(0, len(self.values)))
Mark Draytonaa6c9162016-11-03 15:36:29 +0000484 msg = self._format_message(bpf, event.tgid, values)
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000485 if not Probe.print_time:
486 print("%-6d %-6d %-12s %-16s %s" %
487 (event.tgid, event.pid, event.comm,
488 self._display_function(), msg))
489 else:
490 time = strftime("%H:%M:%S") if Probe.use_localtime else \
491 Probe._time_off_str(event.timestamp_ns)
492 print("%-8s %-6d %-6d %-12s %-16s %s" %
493 (time[:8], event.tgid, event.pid, event.comm,
494 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800495
Teng Qin6b0ed372016-09-29 21:30:13 -0700496 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700497 self.print_stack(bpf, event.kernel_stack_id, -1)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000498 if self.user_stack:
499 self.print_stack(bpf, event.user_stack_id, event.tgid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700500 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700501 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700502
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800503 Probe.event_count += 1
504 if Probe.max_events is not None and \
505 Probe.event_count >= Probe.max_events:
506 exit()
507
508 def attach(self, bpf, verbose):
509 if len(self.library) == 0:
510 self._attach_k(bpf)
511 else:
512 self._attach_u(bpf)
513 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700514 callback = partial(self.print_event, bpf)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000515 bpf[self.events_name].open_perf_buffer(callback,
516 page_cnt=self.page_cnt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800517
518 def _attach_k(self, bpf):
519 if self.probe_type == "r":
520 bpf.attach_kretprobe(event=self.function,
521 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300522 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800523 bpf.attach_kprobe(event=self.function,
524 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300525 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800526
527 def _attach_u(self, bpf):
528 libpath = BPF.find_library(self.library)
529 if libpath is None:
530 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300531 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800532 if libpath is None or len(libpath) == 0:
533 self._bail("unable to find library %s" % self.library)
534
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700535 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300536 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700537 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800538 bpf.attach_uretprobe(name=libpath,
539 sym=self.function,
540 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000541 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800542 else:
543 bpf.attach_uprobe(name=libpath,
544 sym=self.function,
545 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000546 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800547
548class Tool(object):
Mark Drayton5f5687e2017-02-20 18:13:03 +0000549 DEFAULT_PERF_BUFFER_PAGES = 64
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800550 examples = """
551EXAMPLES:
552
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800553trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800554 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800555trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800556 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800557trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800558 Trace the read syscall and print a message for reads >20000 bytes
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000559trace 'r::do_sys_open "%llx", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800560 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800561trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800562 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800563trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800564 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800565trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
566 Trace the write() call from libc to monitor writes to STDOUT
Mark Draytonaa6c9162016-11-03 15:36:29 +0000567trace 'r::__kmalloc (retval == 0) "kmalloc failed!"'
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800568 Trace returns from __kmalloc which returned a null pointer
Mark Draytonaa6c9162016-11-03 15:36:29 +0000569trace 'r:c:malloc (retval) "allocated = %x", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800570 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300571trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800572 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700573trace 'u:pthread:pthread_create (arg4 != 0)'
574 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000575trace 'p::SyS_nanosleep(struct timespec *ts) "sleep for %lld ns", ts->tv_nsec'
576 Trace the nanosleep syscall and print the sleep duration in ns
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800577"""
578
579 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300580 parser = argparse.ArgumentParser(description="Attach to " +
581 "functions and print trace messages.",
582 formatter_class=argparse.RawDescriptionHelpFormatter,
583 epilog=Tool.examples)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000584 parser.add_argument("-b", "--buffer-pages", type=int,
585 default=Tool.DEFAULT_PERF_BUFFER_PAGES,
586 help="number of pages to use for perf_events ring buffer "
587 "(default: %(default)d)")
Mark Draytonaa6c9162016-11-03 15:36:29 +0000588 # we'll refer to the userspace concepts of "pid" and "tid" by
589 # their kernel names -- tgid and pid -- inside the script
590 parser.add_argument("-p", "--pid", type=int, metavar="PID",
591 dest="tgid", help="id of the process to trace (optional)")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000592 parser.add_argument("-L", "--tid", type=int, metavar="TID",
Mark Draytonaa6c9162016-11-03 15:36:29 +0000593 dest="pid", help="id of the thread to trace (optional)")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800594 parser.add_argument("-v", "--verbose", action="store_true",
595 help="print resulting BPF program code before executing")
596 parser.add_argument("-Z", "--string-size", type=int,
597 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300598 parser.add_argument("-S", "--include-self",
599 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800600 help="do not filter trace's own pid from the trace")
601 parser.add_argument("-M", "--max-events", type=int,
602 help="number of events to print before quitting")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000603 parser.add_argument("-t", "--timestamp", action="store_true",
604 help="print timestamp column (offset from trace start)")
605 parser.add_argument("-T", "--time", action="store_true",
606 help="print time column")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300607 parser.add_argument("-K", "--kernel-stack",
608 action="store_true", help="output kernel stack trace")
609 parser.add_argument("-U", "--user-stack",
610 action="store_true", help="output user stack trace")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800611 parser.add_argument(metavar="probe", dest="probes", nargs="+",
612 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300613 parser.add_argument("-I", "--include", action="append",
614 metavar="header",
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300615 help="additional header files to include in the BPF program "
616 "as either full path, or relative to '/usr/include'")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800617 self.args = parser.parse_args()
Mark Draytonaa6c9162016-11-03 15:36:29 +0000618 if self.args.tgid and self.args.pid:
619 parser.error("only one of -p and -t may be specified")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800620
621 def _create_probes(self):
622 Probe.configure(self.args)
623 self.probes = []
624 for probe_spec in self.args.probes:
625 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700626 probe_spec, self.args.string_size,
627 self.args.kernel_stack, self.args.user_stack))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800628
629 def _generate_program(self):
630 self.program = """
631#include <linux/ptrace.h>
632#include <linux/sched.h> /* For TASK_COMM_LEN */
633
634"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300635 for include in (self.args.include or []):
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300636 if include.startswith((".", "/")):
637 include = os.path.abspath(include)
638 self.program += "#include \"%s\"\n" % include
639 else:
640 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700641 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800642 map(lambda p: p.raw_probe, self.probes))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800643 for probe in self.probes:
644 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700645 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800646
647 if self.args.verbose:
648 print(self.program)
649
650 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300651 usdt_contexts = []
652 for probe in self.probes:
653 if probe.usdt:
654 # USDT probes must be enabled before the BPF object
655 # is initialized, because that's where the actual
656 # uprobe is being attached.
657 probe.usdt.enable_probe(
658 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300659 if self.args.verbose:
660 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300661 usdt_contexts.append(probe.usdt)
662 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800663 for probe in self.probes:
664 if self.args.verbose:
665 print(probe)
666 probe.attach(self.bpf, self.args.verbose)
667
668 def _main_loop(self):
669 all_probes_trivial = all(map(Probe.is_default_action,
670 self.probes))
671
672 # Print header
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000673 if self.args.timestamp or self.args.time:
674 print("%-8s %-6s %-6s %-12s %-16s %s" %
675 ("TIME", "PID", "TID", "COMM", "FUNC",
676 "-" if not all_probes_trivial else ""))
677 else:
678 print("%-6s %-6s %-12s %-16s %s" %
679 ("PID", "TID", "COMM", "FUNC",
680 "-" if not all_probes_trivial else ""))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800681
682 while True:
683 self.bpf.kprobe_poll()
684
685 def run(self):
686 try:
687 self._create_probes()
688 self._generate_program()
689 self._attach_probes()
690 self._main_loop()
691 except:
692 if self.args.verbose:
693 traceback.print_exc()
Brenden Blancode14f4f2016-04-08 15:52:55 -0700694 elif sys.exc_info()[0] is not SystemExit:
695 print(sys.exc_info()[1])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800696
697if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300698 Tool().run()