blob: 1a9e3d2a0e533d5b158de7d0b3d7887b2c333b1b [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
23class Time(object):
24 # BPF timestamps come from the monotonic clock. To be able to filter
25 # and compare them from Python, we need to invoke clock_gettime.
26 # Adapted from http://stackoverflow.com/a/1205762
27 CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h>
28
29 class timespec(ct.Structure):
30 _fields_ = [
31 ('tv_sec', ct.c_long),
32 ('tv_nsec', ct.c_long)
33 ]
34
35 librt = ct.CDLL('librt.so.1', use_errno=True)
36 clock_gettime = librt.clock_gettime
37 clock_gettime.argtypes = [ct.c_int, ct.POINTER(timespec)]
38
39 @staticmethod
40 def monotonic_time():
41 t = Time.timespec()
42 if Time.clock_gettime(
43 Time.CLOCK_MONOTONIC_RAW, ct.pointer(t)) != 0:
44 errno_ = ct.get_errno()
45 raise OSError(errno_, os.strerror(errno_))
46 return t.tv_sec * 1e9 + t.tv_nsec
47
48class Probe(object):
49 probe_count = 0
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070050 streq_index = 0
Sasha Goldshtein38847f02016-02-22 02:19:24 -080051 max_events = None
52 event_count = 0
53 first_ts = 0
54 use_localtime = True
Mark Draytonaa6c9162016-11-03 15:36:29 +000055 tgid = -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070056 pid = -1
Sasha Goldshtein38847f02016-02-22 02:19:24 -080057
58 @classmethod
59 def configure(cls, args):
60 cls.max_events = args.max_events
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +000061 cls.print_time = args.timestamp or args.time
62 cls.use_localtime = not args.timestamp
Sasha Goldshtein38847f02016-02-22 02:19:24 -080063 cls.first_ts = Time.monotonic_time()
Mark Draytonaa6c9162016-11-03 15:36:29 +000064 cls.tgid = args.tgid or -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070065 cls.pid = args.pid or -1
Sasha Goldshtein38847f02016-02-22 02:19:24 -080066
Teng Qin6b0ed372016-09-29 21:30:13 -070067 def __init__(self, probe, string_size, kernel_stack, user_stack):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +030068 self.usdt = None
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070069 self.streq_functions = ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -080070 self.raw_probe = probe
71 self.string_size = string_size
Teng Qin6b0ed372016-09-29 21:30:13 -070072 self.kernel_stack = kernel_stack
73 self.user_stack = user_stack
Sasha Goldshtein38847f02016-02-22 02:19:24 -080074 Probe.probe_count += 1
75 self._parse_probe()
76 self.probe_num = Probe.probe_count
77 self.probe_name = "probe_%s_%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070078 (self._display_function(), self.probe_num)
Sasha Goldshtein3fa7ba12017-01-14 11:17:40 +000079 self.probe_name = re.sub(r'[^A-Za-z0-9_]', '_', self.probe_name)
Sasha Goldshtein38847f02016-02-22 02:19:24 -080080
81 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070082 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
83 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080084 self.types, self.values)
85
86 def is_default_action(self):
87 return self.python_format == ""
88
89 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070090 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080091 (self.raw_probe, error))
92
93 def _parse_probe(self):
94 text = self.raw_probe
95
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000096 # There might be a function signature preceding the actual
97 # filter/print part, or not. Find the probe specifier first --
98 # it ends with either a space or an open paren ( for the
99 # function signature part.
100 # opt. signature
101 # probespec | rest
102 # --------- ---------- --
103 (spec, sig, rest) = re.match(r'([^ \t\(]+)(\([^\(]*\))?(.*)',
104 text).groups()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800105
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000106 self._parse_spec(spec)
107 self.signature = sig[1:-1] if sig else None # remove the parens
108 if self.signature and self.probe_type in ['u', 't']:
109 self._bail("USDT and tracepoint probes can't have " +
110 "a function signature; use arg1, arg2, " +
111 "... instead")
112
113 text = rest.lstrip()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800114 # If we now have a (, wait for the balanced closing ) and that
115 # will be the predicate
116 self.filter = None
117 if len(text) > 0 and text[0] == "(":
118 balance = 1
119 for i in range(1, len(text)):
120 if text[i] == "(":
121 balance += 1
122 if text[i] == ")":
123 balance -= 1
124 if balance == 0:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300125 self._parse_filter(text[:i + 1])
126 text = text[i + 1:]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800127 break
128 if self.filter is None:
129 self._bail("unmatched end of predicate")
130
131 if self.filter is None:
132 self.filter = "1"
133
134 # The remainder of the text is the printf action
135 self._parse_action(text.lstrip())
136
137 def _parse_spec(self, spec):
138 parts = spec.split(":")
139 # Two special cases: 'func' means 'p::func', 'lib:func' means
140 # 'p:lib:func'. Other combinations need to provide an empty
141 # value between delimiters, e.g. 'r::func' for a kretprobe on
142 # the function func.
143 if len(parts) == 1:
144 parts = ["p", "", parts[0]]
145 elif len(parts) == 2:
146 parts = ["p", parts[0], parts[1]]
147 if len(parts[0]) == 0:
148 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700149 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800150 self.probe_type = parts[0]
151 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700152 self._bail("probe type must be '', 'p', 't', 'r', " +
153 "or 'u', but got '%s'" % parts[0])
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800154 if self.probe_type == "t":
155 self.tp_category = parts[1]
156 self.tp_event = parts[2]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800157 self.library = "" # kernel
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300158 self.function = "" # from TRACEPOINT_PROBE
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700159 elif self.probe_type == "u":
160 self.library = parts[1]
161 self.usdt_name = parts[2]
162 self.function = "" # no function, just address
163 # We will discover the USDT provider by matching on
164 # the USDT name in the specified library
165 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800166 else:
167 self.library = parts[1]
168 self.function = parts[2]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800169
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700170 def _find_usdt_probe(self):
Sasha Goldshteindd045362016-11-13 05:07:38 -0800171 target = Probe.pid if Probe.pid and Probe.pid != -1 \
172 else Probe.tgid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000173 self.usdt = USDT(path=self.library, pid=target)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300174 for probe in self.usdt.enumerate_probes():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700175 if probe.name == self.usdt_name:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300176 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700177 self._bail("unrecognized USDT probe %s" % self.usdt_name)
178
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800179 def _parse_filter(self, filt):
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700180 self.filter = self._rewrite_expr(filt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800181
182 def _parse_types(self, fmt):
183 for match in re.finditer(
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300184 r'[^%]%(s|u|d|llu|lld|hu|hd|x|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800185 self.types.append(match.group(1))
186 fmt = re.sub(r'([^%]%)(u|d|llu|lld|hu|hd)', r'\1d', fmt)
187 fmt = re.sub(r'([^%]%)(x|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700188 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800189 self.python_format = fmt.strip('"')
190
191 def _parse_action(self, action):
192 self.values = []
193 self.types = []
194 self.python_format = ""
195 if len(action) == 0:
196 return
197
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800198 action = action.strip()
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700199 match = re.search(r'(\".*?\"),?(.*)', action)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800200 if match is None:
201 self._bail("expected format string in \"s")
202
203 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800204 self._parse_types(self.raw_format)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700205 for part in re.split('(?<!"),', match.group(2)):
206 part = self._rewrite_expr(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800207 if len(part) > 0:
208 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800209
210 aliases = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530211 "retval": "PT_REGS_RC(ctx)",
212 "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)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800218 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
219 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
220 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
221 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
222 "$cpu": "bpf_get_smp_processor_id()"
223 }
224
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700225 def _generate_streq_function(self, string):
226 fname = "streq_%d" % Probe.streq_index
227 Probe.streq_index += 1
228 self.streq_functions += """
229static inline bool %s(char const *ignored, unsigned long str) {
230 char needle[] = %s;
231 char haystack[sizeof(needle)];
232 bpf_probe_read(&haystack, sizeof(haystack), (void *)str);
233 for (int i = 0; i < sizeof(needle); ++i) {
234 if (needle[i] != haystack[i]) {
235 return false;
236 }
237 }
238 return true;
239}
240 """ % (fname, string)
241 return fname
242
243 def _rewrite_expr(self, expr):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800244 for alias, replacement in Probe.aliases.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700245 # For USDT probes, we replace argN values with the
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300246 # actual arguments for that probe obtained using
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300247 # bpf_readarg_N macros emitted at BPF construction.
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700248 if alias.startswith("arg") and self.probe_type == "u":
249 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800250 expr = expr.replace(alias, replacement)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700251 matches = re.finditer('STRCMP\\(("[^"]+\\")', expr)
252 for match in matches:
253 string = match.group(1)
254 fname = self._generate_streq_function(string)
255 expr = expr.replace("STRCMP", fname, 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800256 return expr
257
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300258 p_type = {"u": ct.c_uint, "d": ct.c_int,
259 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
260 "hu": ct.c_ushort, "hd": ct.c_short,
261 "x": ct.c_uint, "llx": ct.c_ulonglong, "c": ct.c_ubyte,
262 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800263
264 def _generate_python_field_decl(self, idx, fields):
265 field_type = self.types[idx]
266 if field_type == "s":
267 ptype = ct.c_char * self.string_size
268 else:
269 ptype = Probe.p_type[field_type]
270 fields.append(("v%d" % idx, ptype))
271
272 def _generate_python_data_decl(self):
273 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700274 (self._display_function(), self.probe_num)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800275 fields = [
276 ("timestamp_ns", ct.c_ulonglong),
Mark Draytonaa6c9162016-11-03 15:36:29 +0000277 ("tgid", ct.c_uint),
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800278 ("pid", ct.c_uint),
279 ("comm", ct.c_char * 16) # TASK_COMM_LEN
280 ]
281 for i in range(0, len(self.types)):
282 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700283 if self.kernel_stack:
284 fields.append(("kernel_stack_id", ct.c_int))
285 if self.user_stack:
286 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800287 return type(self.python_struct_name, (ct.Structure,),
288 dict(_fields_=fields))
289
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300290 c_type = {"u": "unsigned int", "d": "int",
291 "llu": "unsigned long long", "lld": "long long",
292 "hu": "unsigned short", "hd": "short",
293 "x": "unsigned int", "llx": "unsigned long long",
294 "c": "char", "K": "unsigned long long",
295 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800296 fmt_types = c_type.keys()
297
298 def _generate_field_decl(self, idx):
299 field_type = self.types[idx]
300 if field_type == "s":
301 return "char v%d[%d];\n" % (idx, self.string_size)
302 if field_type in Probe.fmt_types:
303 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
304 self._bail("unrecognized format specifier %s" % field_type)
305
306 def _generate_data_decl(self):
307 # The BPF program will populate values into the struct
308 # according to the format string, and the Python program will
309 # construct the final display string.
310 self.events_name = "%s_events" % self.probe_name
311 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700312 self.stacks_name = "%s_stacks" % self.probe_name
313 stack_table = "BPF_STACK_TRACE(%s, 1024);" % self.stacks_name \
314 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800315 data_fields = ""
316 for i, field_type in enumerate(self.types):
317 data_fields += " " + \
318 self._generate_field_decl(i)
319
Teng Qin6b0ed372016-09-29 21:30:13 -0700320 kernel_stack_str = " int kernel_stack_id;" \
321 if self.kernel_stack else ""
322 user_stack_str = " int user_stack_id;" \
323 if self.user_stack else ""
324
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800325 text = """
326struct %s
327{
328 u64 timestamp_ns;
Mark Draytonaa6c9162016-11-03 15:36:29 +0000329 u32 tgid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800330 u32 pid;
331 char comm[TASK_COMM_LEN];
332%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700333%s
334%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800335};
336
337BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700338%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800339"""
Teng Qin6b0ed372016-09-29 21:30:13 -0700340 return text % (self.struct_name, data_fields,
341 kernel_stack_str, user_stack_str,
342 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800343
344 def _generate_field_assign(self, idx):
345 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300346 expr = self.values[idx].strip()
347 text = ""
348 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshteinb6db17f2016-10-04 19:50:50 +0300349 text = (" u64 %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300350 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
351 % (expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300352
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800353 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300354 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800355 if (%s != 0) {
356 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), (void *)%s);
357 }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300358 """ % (expr, idx, idx, expr)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800359 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300360 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800361 (idx, Probe.c_type[field_type], expr)
362 self._bail("unrecognized field type %s" % field_type)
363
Teng Qin0615bff2016-09-28 08:19:40 -0700364 def _generate_usdt_filter_read(self):
365 text = ""
366 if self.probe_type == "u":
367 for arg, _ in Probe.aliases.items():
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300368 if not (arg.startswith("arg") and
369 (arg in self.filter)):
Teng Qin0615bff2016-09-28 08:19:40 -0700370 continue
371 arg_index = int(arg.replace("arg", ""))
372 arg_ctype = self.usdt.get_probe_arg_ctype(
373 self.usdt_name, arg_index)
374 if not arg_ctype:
375 self._bail("Unable to determine type of {} "
376 "in the filter".format(arg))
377 text += """
378 {} {}_filter;
379 bpf_usdt_readarg({}, ctx, &{}_filter);
380 """.format(arg_ctype, arg, arg_index, arg)
381 self.filter = self.filter.replace(
382 arg, "{}_filter".format(arg))
383 return text
384
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700385 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800386 data_decl = self._generate_data_decl()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800387 # kprobes don't have built-in pid filters, so we have to add
388 # it to the function body:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700389 if len(self.library) == 0 and Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800390 pid_filter = """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800391 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300392 """ % Probe.pid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000393 elif len(self.library) == 0 and Probe.tgid != -1:
394 pid_filter = """
395 if (__tgid != %d) { return 0; }
396 """ % Probe.tgid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800397 elif not include_self:
398 pid_filter = """
Mark Draytonaa6c9162016-11-03 15:36:29 +0000399 if (__tgid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300400 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800401 else:
402 pid_filter = ""
403
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700404 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700405 signature = "struct pt_regs *ctx"
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000406 if self.signature:
407 signature += ", " + self.signature
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700408
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800409 data_fields = ""
410 for i, expr in enumerate(self.values):
411 data_fields += self._generate_field_assign(i)
412
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300413 if self.probe_type == "t":
414 heading = "TRACEPOINT_PROBE(%s, %s)" % \
415 (self.tp_category, self.tp_event)
416 ctx_name = "args"
417 else:
418 heading = "int %s(%s)" % (self.probe_name, signature)
419 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300420
421 stack_trace = ""
422 if self.user_stack:
423 stack_trace += """
424 __data.user_stack_id = %s.get_stackid(
425 %s, BPF_F_REUSE_STACKID | BPF_F_USER_STACK
426 );""" % (self.stacks_name, ctx_name)
427 if self.kernel_stack:
428 stack_trace += """
429 __data.kernel_stack_id = %s.get_stackid(
430 %s, BPF_F_REUSE_STACKID
431 );""" % (self.stacks_name, ctx_name)
432
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300433 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800434{
Mark Draytonaa6c9162016-11-03 15:36:29 +0000435 u64 __pid_tgid = bpf_get_current_pid_tgid();
436 u32 __tgid = __pid_tgid >> 32;
437 u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800438 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800439 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700440 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800441 if (!(%s)) return 0;
442
443 struct %s __data = {0};
444 __data.timestamp_ns = bpf_ktime_get_ns();
Mark Draytonaa6c9162016-11-03 15:36:29 +0000445 __data.tgid = __tgid;
446 __data.pid = __pid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800447 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
448%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700449%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300450 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800451 return 0;
452}
453"""
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300454 text = text % (pid_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700455 self._generate_usdt_filter_read(), self.filter,
Teng Qin6b0ed372016-09-29 21:30:13 -0700456 self.struct_name, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300457 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700458
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700459 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800460
461 @classmethod
462 def _time_off_str(cls, timestamp_ns):
463 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
464
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800465 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700466 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800467 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700468 elif self.probe_type == 'u':
469 return self.usdt_name
470 else: # self.probe_type == 't'
471 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800472
Mark Draytonaa6c9162016-11-03 15:36:29 +0000473 def print_stack(self, bpf, stack_id, tgid):
Teng Qin6b0ed372016-09-29 21:30:13 -0700474 if stack_id < 0:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700475 print(" %d" % stack_id)
476 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700477
478 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
479 for addr in stack:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000480 print(" %016x %s" % (addr, bpf.sym(addr, tgid)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700481
Mark Draytonaa6c9162016-11-03 15:36:29 +0000482 def _format_message(self, bpf, tgid, values):
483 # Replace each %K with kernel sym and %U with user sym in tgid
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700484 kernel_placeholders = [i for i in xrange(0, len(self.types))
485 if self.types[i] == 'K']
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300486 user_placeholders = [i for i in xrange(0, len(self.types))
487 if self.types[i] == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700488 for kp in kernel_placeholders:
489 values[kp] = bpf.ksymaddr(values[kp])
490 for up in user_placeholders:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000491 values[up] = bpf.symaddr(values[up], tgid)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700492 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700493
494 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800495 # Cast as the generated structure type and display
496 # according to the format string in the probe.
497 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
498 values = map(lambda i: getattr(event, "v%d" % i),
499 range(0, len(self.values)))
Mark Draytonaa6c9162016-11-03 15:36:29 +0000500 msg = self._format_message(bpf, event.tgid, values)
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000501 if not Probe.print_time:
502 print("%-6d %-6d %-12s %-16s %s" %
503 (event.tgid, event.pid, event.comm,
504 self._display_function(), msg))
505 else:
506 time = strftime("%H:%M:%S") if Probe.use_localtime else \
507 Probe._time_off_str(event.timestamp_ns)
508 print("%-8s %-6d %-6d %-12s %-16s %s" %
509 (time[:8], event.tgid, event.pid, event.comm,
510 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800511
Teng Qin6b0ed372016-09-29 21:30:13 -0700512 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700513 self.print_stack(bpf, event.kernel_stack_id, -1)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000514 if self.user_stack:
515 self.print_stack(bpf, event.user_stack_id, event.tgid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700516 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700517 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700518
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800519 Probe.event_count += 1
520 if Probe.max_events is not None and \
521 Probe.event_count >= Probe.max_events:
522 exit()
523
524 def attach(self, bpf, verbose):
525 if len(self.library) == 0:
526 self._attach_k(bpf)
527 else:
528 self._attach_u(bpf)
529 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700530 callback = partial(self.print_event, bpf)
531 bpf[self.events_name].open_perf_buffer(callback)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800532
533 def _attach_k(self, bpf):
534 if self.probe_type == "r":
535 bpf.attach_kretprobe(event=self.function,
536 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300537 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800538 bpf.attach_kprobe(event=self.function,
539 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300540 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800541
542 def _attach_u(self, bpf):
543 libpath = BPF.find_library(self.library)
544 if libpath is None:
545 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300546 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800547 if libpath is None or len(libpath) == 0:
548 self._bail("unable to find library %s" % self.library)
549
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700550 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300551 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700552 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800553 bpf.attach_uretprobe(name=libpath,
554 sym=self.function,
555 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700556 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800557 else:
558 bpf.attach_uprobe(name=libpath,
559 sym=self.function,
560 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700561 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800562
563class Tool(object):
564 examples = """
565EXAMPLES:
566
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800567trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800568 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800569trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800570 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800571trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800572 Trace the read syscall and print a message for reads >20000 bytes
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000573trace 'r::do_sys_open "%llx", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800574 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800575trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800576 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800577trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800578 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800579trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
580 Trace the write() call from libc to monitor writes to STDOUT
Mark Draytonaa6c9162016-11-03 15:36:29 +0000581trace 'r::__kmalloc (retval == 0) "kmalloc failed!"'
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800582 Trace returns from __kmalloc which returned a null pointer
Mark Draytonaa6c9162016-11-03 15:36:29 +0000583trace 'r:c:malloc (retval) "allocated = %x", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800584 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300585trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800586 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700587trace 'u:pthread:pthread_create (arg4 != 0)'
588 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000589trace 'p::SyS_nanosleep(struct timespec *ts) "sleep for %lld ns", ts->tv_nsec'
590 Trace the nanosleep syscall and print the sleep duration in ns
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800591"""
592
593 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300594 parser = argparse.ArgumentParser(description="Attach to " +
595 "functions and print trace messages.",
596 formatter_class=argparse.RawDescriptionHelpFormatter,
597 epilog=Tool.examples)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000598 # we'll refer to the userspace concepts of "pid" and "tid" by
599 # their kernel names -- tgid and pid -- inside the script
600 parser.add_argument("-p", "--pid", type=int, metavar="PID",
601 dest="tgid", help="id of the process to trace (optional)")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000602 parser.add_argument("-L", "--tid", type=int, metavar="TID",
Mark Draytonaa6c9162016-11-03 15:36:29 +0000603 dest="pid", help="id of the thread to trace (optional)")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800604 parser.add_argument("-v", "--verbose", action="store_true",
605 help="print resulting BPF program code before executing")
606 parser.add_argument("-Z", "--string-size", type=int,
607 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300608 parser.add_argument("-S", "--include-self",
609 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800610 help="do not filter trace's own pid from the trace")
611 parser.add_argument("-M", "--max-events", type=int,
612 help="number of events to print before quitting")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000613 parser.add_argument("-t", "--timestamp", action="store_true",
614 help="print timestamp column (offset from trace start)")
615 parser.add_argument("-T", "--time", action="store_true",
616 help="print time column")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300617 parser.add_argument("-K", "--kernel-stack",
618 action="store_true", help="output kernel stack trace")
619 parser.add_argument("-U", "--user-stack",
620 action="store_true", help="output user stack trace")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800621 parser.add_argument(metavar="probe", dest="probes", nargs="+",
622 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300623 parser.add_argument("-I", "--include", action="append",
624 metavar="header",
625 help="additional header files to include in the BPF program")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800626 self.args = parser.parse_args()
Mark Draytonaa6c9162016-11-03 15:36:29 +0000627 if self.args.tgid and self.args.pid:
628 parser.error("only one of -p and -t may be specified")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800629
630 def _create_probes(self):
631 Probe.configure(self.args)
632 self.probes = []
633 for probe_spec in self.args.probes:
634 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700635 probe_spec, self.args.string_size,
636 self.args.kernel_stack, self.args.user_stack))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800637
638 def _generate_program(self):
639 self.program = """
640#include <linux/ptrace.h>
641#include <linux/sched.h> /* For TASK_COMM_LEN */
642
643"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300644 for include in (self.args.include or []):
645 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700646 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800647 map(lambda p: p.raw_probe, self.probes))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800648 for probe in self.probes:
649 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700650 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800651
652 if self.args.verbose:
653 print(self.program)
654
655 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300656 usdt_contexts = []
657 for probe in self.probes:
658 if probe.usdt:
659 # USDT probes must be enabled before the BPF object
660 # is initialized, because that's where the actual
661 # uprobe is being attached.
662 probe.usdt.enable_probe(
663 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300664 if self.args.verbose:
665 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300666 usdt_contexts.append(probe.usdt)
667 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800668 for probe in self.probes:
669 if self.args.verbose:
670 print(probe)
671 probe.attach(self.bpf, self.args.verbose)
672
673 def _main_loop(self):
674 all_probes_trivial = all(map(Probe.is_default_action,
675 self.probes))
676
677 # Print header
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000678 if self.args.timestamp or self.args.time:
679 print("%-8s %-6s %-6s %-12s %-16s %s" %
680 ("TIME", "PID", "TID", "COMM", "FUNC",
681 "-" if not all_probes_trivial else ""))
682 else:
683 print("%-6s %-6s %-12s %-16s %s" %
684 ("PID", "TID", "COMM", "FUNC",
685 "-" if not all_probes_trivial else ""))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800686
687 while True:
688 self.bpf.kprobe_poll()
689
690 def run(self):
691 try:
692 self._create_probes()
693 self._generate_program()
694 self._attach_probes()
695 self._main_loop()
696 except:
697 if self.args.verbose:
698 traceback.print_exc()
Brenden Blancode14f4f2016-04-08 15:52:55 -0700699 elif sys.exc_info()[0] is not SystemExit:
700 print(sys.exc_info()[1])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800701
702if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300703 Tool().run()