blob: eae625cb2437b53ae8341908372339867c9420a2 [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#
6# USAGE: trace [-h] [-p PID] [-v] [-Z STRING_SIZE] [-S] [-M MAX_EVENTS] [-o]
Sasha Goldshtein4725a722016-10-18 20:54:47 +03007# [-K] [-U] [-I header] probe [probe ...]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -08008#
Sasha Goldshtein38847f02016-02-22 02:19:24 -08009# Licensed under the Apache License, Version 2.0 (the "License")
10# Copyright (C) 2016 Sasha Goldshtein.
11
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +030012from bcc import BPF, USDT
Teng Qin6b0ed372016-09-29 21:30:13 -070013from functools import partial
Sasha Goldshtein38847f02016-02-22 02:19:24 -080014from time import sleep, strftime
15import argparse
16import re
17import ctypes as ct
18import os
19import traceback
20import sys
21
22class Time(object):
23 # BPF timestamps come from the monotonic clock. To be able to filter
24 # and compare them from Python, we need to invoke clock_gettime.
25 # Adapted from http://stackoverflow.com/a/1205762
26 CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h>
27
28 class timespec(ct.Structure):
29 _fields_ = [
30 ('tv_sec', ct.c_long),
31 ('tv_nsec', ct.c_long)
32 ]
33
34 librt = ct.CDLL('librt.so.1', use_errno=True)
35 clock_gettime = librt.clock_gettime
36 clock_gettime.argtypes = [ct.c_int, ct.POINTER(timespec)]
37
38 @staticmethod
39 def monotonic_time():
40 t = Time.timespec()
41 if Time.clock_gettime(
42 Time.CLOCK_MONOTONIC_RAW, ct.pointer(t)) != 0:
43 errno_ = ct.get_errno()
44 raise OSError(errno_, os.strerror(errno_))
45 return t.tv_sec * 1e9 + t.tv_nsec
46
47class Probe(object):
48 probe_count = 0
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070049 streq_index = 0
Sasha Goldshtein38847f02016-02-22 02:19:24 -080050 max_events = None
51 event_count = 0
52 first_ts = 0
53 use_localtime = True
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070054 pid = -1
Sasha Goldshtein38847f02016-02-22 02:19:24 -080055
56 @classmethod
57 def configure(cls, args):
58 cls.max_events = args.max_events
59 cls.use_localtime = not args.offset
60 cls.first_ts = Time.monotonic_time()
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070061 cls.pid = args.pid or -1
Sasha Goldshtein38847f02016-02-22 02:19:24 -080062
Teng Qin6b0ed372016-09-29 21:30:13 -070063 def __init__(self, probe, string_size, kernel_stack, user_stack):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +030064 self.usdt = None
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070065 self.streq_functions = ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -080066 self.raw_probe = probe
67 self.string_size = string_size
Teng Qin6b0ed372016-09-29 21:30:13 -070068 self.kernel_stack = kernel_stack
69 self.user_stack = user_stack
Sasha Goldshtein38847f02016-02-22 02:19:24 -080070 Probe.probe_count += 1
71 self._parse_probe()
72 self.probe_num = Probe.probe_count
73 self.probe_name = "probe_%s_%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070074 (self._display_function(), self.probe_num)
Sasha Goldshtein38847f02016-02-22 02:19:24 -080075
76 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070077 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
78 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080079 self.types, self.values)
80
81 def is_default_action(self):
82 return self.python_format == ""
83
84 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070085 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080086 (self.raw_probe, error))
87
88 def _parse_probe(self):
89 text = self.raw_probe
90
91 # Everything until the first space is the probe specifier
92 first_space = text.find(' ')
93 spec = text[:first_space] if first_space >= 0 else text
94 self._parse_spec(spec)
95 if first_space >= 0:
96 text = text[first_space:].lstrip()
97 else:
98 text = ""
99
100 # If we now have a (, wait for the balanced closing ) and that
101 # will be the predicate
102 self.filter = None
103 if len(text) > 0 and text[0] == "(":
104 balance = 1
105 for i in range(1, len(text)):
106 if text[i] == "(":
107 balance += 1
108 if text[i] == ")":
109 balance -= 1
110 if balance == 0:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300111 self._parse_filter(text[:i + 1])
112 text = text[i + 1:]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800113 break
114 if self.filter is None:
115 self._bail("unmatched end of predicate")
116
117 if self.filter is None:
118 self.filter = "1"
119
120 # The remainder of the text is the printf action
121 self._parse_action(text.lstrip())
122
123 def _parse_spec(self, spec):
124 parts = spec.split(":")
125 # Two special cases: 'func' means 'p::func', 'lib:func' means
126 # 'p:lib:func'. Other combinations need to provide an empty
127 # value between delimiters, e.g. 'r::func' for a kretprobe on
128 # the function func.
129 if len(parts) == 1:
130 parts = ["p", "", parts[0]]
131 elif len(parts) == 2:
132 parts = ["p", parts[0], parts[1]]
133 if len(parts[0]) == 0:
134 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700135 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800136 self.probe_type = parts[0]
137 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700138 self._bail("probe type must be '', 'p', 't', 'r', " +
139 "or 'u', but got '%s'" % parts[0])
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800140 if self.probe_type == "t":
141 self.tp_category = parts[1]
142 self.tp_event = parts[2]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800143 self.library = "" # kernel
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300144 self.function = "" # from TRACEPOINT_PROBE
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700145 elif self.probe_type == "u":
146 self.library = parts[1]
147 self.usdt_name = parts[2]
148 self.function = "" # no function, just address
149 # We will discover the USDT provider by matching on
150 # the USDT name in the specified library
151 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800152 else:
153 self.library = parts[1]
154 self.function = parts[2]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800155
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700156 def _find_usdt_probe(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300157 self.usdt = USDT(path=self.library, pid=Probe.pid)
158 for probe in self.usdt.enumerate_probes():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700159 if probe.name == self.usdt_name:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300160 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700161 self._bail("unrecognized USDT probe %s" % self.usdt_name)
162
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800163 def _parse_filter(self, filt):
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700164 self.filter = self._rewrite_expr(filt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800165
166 def _parse_types(self, fmt):
167 for match in re.finditer(
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300168 r'[^%]%(s|u|d|llu|lld|hu|hd|x|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800169 self.types.append(match.group(1))
170 fmt = re.sub(r'([^%]%)(u|d|llu|lld|hu|hd)', r'\1d', fmt)
171 fmt = re.sub(r'([^%]%)(x|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700172 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800173 self.python_format = fmt.strip('"')
174
175 def _parse_action(self, action):
176 self.values = []
177 self.types = []
178 self.python_format = ""
179 if len(action) == 0:
180 return
181
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800182 action = action.strip()
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700183 match = re.search(r'(\".*?\"),?(.*)', action)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800184 if match is None:
185 self._bail("expected format string in \"s")
186
187 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800188 self._parse_types(self.raw_format)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700189 for part in re.split('(?<!"),', match.group(2)):
190 part = self._rewrite_expr(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800191 if len(part) > 0:
192 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800193
194 aliases = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530195 "retval": "PT_REGS_RC(ctx)",
196 "arg1": "PT_REGS_PARM1(ctx)",
197 "arg2": "PT_REGS_PARM2(ctx)",
198 "arg3": "PT_REGS_PARM3(ctx)",
199 "arg4": "PT_REGS_PARM4(ctx)",
200 "arg5": "PT_REGS_PARM5(ctx)",
201 "arg6": "PT_REGS_PARM6(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800202 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
203 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
204 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
205 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
206 "$cpu": "bpf_get_smp_processor_id()"
207 }
208
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700209 def _generate_streq_function(self, string):
210 fname = "streq_%d" % Probe.streq_index
211 Probe.streq_index += 1
212 self.streq_functions += """
213static inline bool %s(char const *ignored, unsigned long str) {
214 char needle[] = %s;
215 char haystack[sizeof(needle)];
216 bpf_probe_read(&haystack, sizeof(haystack), (void *)str);
217 for (int i = 0; i < sizeof(needle); ++i) {
218 if (needle[i] != haystack[i]) {
219 return false;
220 }
221 }
222 return true;
223}
224 """ % (fname, string)
225 return fname
226
227 def _rewrite_expr(self, expr):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800228 for alias, replacement in Probe.aliases.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700229 # For USDT probes, we replace argN values with the
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300230 # actual arguments for that probe obtained using
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300231 # bpf_readarg_N macros emitted at BPF construction.
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700232 if alias.startswith("arg") and self.probe_type == "u":
233 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800234 expr = expr.replace(alias, replacement)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700235 matches = re.finditer('STRCMP\\(("[^"]+\\")', expr)
236 for match in matches:
237 string = match.group(1)
238 fname = self._generate_streq_function(string)
239 expr = expr.replace("STRCMP", fname, 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800240 return expr
241
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300242 p_type = {"u": ct.c_uint, "d": ct.c_int,
243 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
244 "hu": ct.c_ushort, "hd": ct.c_short,
245 "x": ct.c_uint, "llx": ct.c_ulonglong, "c": ct.c_ubyte,
246 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800247
248 def _generate_python_field_decl(self, idx, fields):
249 field_type = self.types[idx]
250 if field_type == "s":
251 ptype = ct.c_char * self.string_size
252 else:
253 ptype = Probe.p_type[field_type]
254 fields.append(("v%d" % idx, ptype))
255
256 def _generate_python_data_decl(self):
257 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700258 (self._display_function(), self.probe_num)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800259 fields = [
260 ("timestamp_ns", ct.c_ulonglong),
261 ("pid", ct.c_uint),
262 ("comm", ct.c_char * 16) # TASK_COMM_LEN
263 ]
264 for i in range(0, len(self.types)):
265 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700266 if self.kernel_stack:
267 fields.append(("kernel_stack_id", ct.c_int))
268 if self.user_stack:
269 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800270 return type(self.python_struct_name, (ct.Structure,),
271 dict(_fields_=fields))
272
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300273 c_type = {"u": "unsigned int", "d": "int",
274 "llu": "unsigned long long", "lld": "long long",
275 "hu": "unsigned short", "hd": "short",
276 "x": "unsigned int", "llx": "unsigned long long",
277 "c": "char", "K": "unsigned long long",
278 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800279 fmt_types = c_type.keys()
280
281 def _generate_field_decl(self, idx):
282 field_type = self.types[idx]
283 if field_type == "s":
284 return "char v%d[%d];\n" % (idx, self.string_size)
285 if field_type in Probe.fmt_types:
286 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
287 self._bail("unrecognized format specifier %s" % field_type)
288
289 def _generate_data_decl(self):
290 # The BPF program will populate values into the struct
291 # according to the format string, and the Python program will
292 # construct the final display string.
293 self.events_name = "%s_events" % self.probe_name
294 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700295 self.stacks_name = "%s_stacks" % self.probe_name
296 stack_table = "BPF_STACK_TRACE(%s, 1024);" % self.stacks_name \
297 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800298 data_fields = ""
299 for i, field_type in enumerate(self.types):
300 data_fields += " " + \
301 self._generate_field_decl(i)
302
Teng Qin6b0ed372016-09-29 21:30:13 -0700303 kernel_stack_str = " int kernel_stack_id;" \
304 if self.kernel_stack else ""
305 user_stack_str = " int user_stack_id;" \
306 if self.user_stack else ""
307
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800308 text = """
309struct %s
310{
311 u64 timestamp_ns;
312 u32 pid;
313 char comm[TASK_COMM_LEN];
314%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700315%s
316%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800317};
318
319BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700320%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800321"""
Teng Qin6b0ed372016-09-29 21:30:13 -0700322 return text % (self.struct_name, data_fields,
323 kernel_stack_str, user_stack_str,
324 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800325
326 def _generate_field_assign(self, idx):
327 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300328 expr = self.values[idx].strip()
329 text = ""
330 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshteinb6db17f2016-10-04 19:50:50 +0300331 text = (" u64 %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300332 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
333 % (expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300334
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800335 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300336 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800337 if (%s != 0) {
338 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), (void *)%s);
339 }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300340 """ % (expr, idx, idx, expr)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800341 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300342 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800343 (idx, Probe.c_type[field_type], expr)
344 self._bail("unrecognized field type %s" % field_type)
345
Teng Qin0615bff2016-09-28 08:19:40 -0700346 def _generate_usdt_filter_read(self):
347 text = ""
348 if self.probe_type == "u":
349 for arg, _ in Probe.aliases.items():
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300350 if not (arg.startswith("arg") and
351 (arg in self.filter)):
Teng Qin0615bff2016-09-28 08:19:40 -0700352 continue
353 arg_index = int(arg.replace("arg", ""))
354 arg_ctype = self.usdt.get_probe_arg_ctype(
355 self.usdt_name, arg_index)
356 if not arg_ctype:
357 self._bail("Unable to determine type of {} "
358 "in the filter".format(arg))
359 text += """
360 {} {}_filter;
361 bpf_usdt_readarg({}, ctx, &{}_filter);
362 """.format(arg_ctype, arg, arg_index, arg)
363 self.filter = self.filter.replace(
364 arg, "{}_filter".format(arg))
365 return text
366
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700367 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800368 data_decl = self._generate_data_decl()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800369 # kprobes don't have built-in pid filters, so we have to add
370 # it to the function body:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700371 if len(self.library) == 0 and Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800372 pid_filter = """
373 u32 __pid = bpf_get_current_pid_tgid();
374 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300375 """ % Probe.pid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800376 elif not include_self:
377 pid_filter = """
378 u32 __pid = bpf_get_current_pid_tgid();
379 if (__pid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300380 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800381 else:
382 pid_filter = ""
383
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700384 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700385 signature = "struct pt_regs *ctx"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700386
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800387 data_fields = ""
388 for i, expr in enumerate(self.values):
389 data_fields += self._generate_field_assign(i)
390
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300391 if self.probe_type == "t":
392 heading = "TRACEPOINT_PROBE(%s, %s)" % \
393 (self.tp_category, self.tp_event)
394 ctx_name = "args"
395 else:
396 heading = "int %s(%s)" % (self.probe_name, signature)
397 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300398
399 stack_trace = ""
400 if self.user_stack:
401 stack_trace += """
402 __data.user_stack_id = %s.get_stackid(
403 %s, BPF_F_REUSE_STACKID | BPF_F_USER_STACK
404 );""" % (self.stacks_name, ctx_name)
405 if self.kernel_stack:
406 stack_trace += """
407 __data.kernel_stack_id = %s.get_stackid(
408 %s, BPF_F_REUSE_STACKID
409 );""" % (self.stacks_name, ctx_name)
410
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300411 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800412{
413 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800414 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700415 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800416 if (!(%s)) return 0;
417
418 struct %s __data = {0};
419 __data.timestamp_ns = bpf_ktime_get_ns();
420 __data.pid = bpf_get_current_pid_tgid();
421 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
422%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700423%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300424 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800425 return 0;
426}
427"""
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300428 text = text % (pid_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700429 self._generate_usdt_filter_read(), self.filter,
Teng Qin6b0ed372016-09-29 21:30:13 -0700430 self.struct_name, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300431 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700432
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700433 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800434
435 @classmethod
436 def _time_off_str(cls, timestamp_ns):
437 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
438
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800439 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700440 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800441 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700442 elif self.probe_type == 'u':
443 return self.usdt_name
444 else: # self.probe_type == 't'
445 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800446
Teng Qin6b0ed372016-09-29 21:30:13 -0700447 def print_stack(self, bpf, stack_id, pid):
448 if stack_id < 0:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700449 print(" %d" % stack_id)
450 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700451
452 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
453 for addr in stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700454 print(" %016x %s" % (addr, bpf.sym(addr, pid)))
455
456 def _format_message(self, bpf, pid, values):
457 # Replace each %K with kernel sym and %U with user sym in pid
458 kernel_placeholders = [i for i in xrange(0, len(self.types))
459 if self.types[i] == 'K']
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300460 user_placeholders = [i for i in xrange(0, len(self.types))
461 if self.types[i] == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700462 for kp in kernel_placeholders:
463 values[kp] = bpf.ksymaddr(values[kp])
464 for up in user_placeholders:
465 values[up] = bpf.symaddr(values[up], pid)
466 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700467
468 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800469 # Cast as the generated structure type and display
470 # according to the format string in the probe.
471 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
472 values = map(lambda i: getattr(event, "v%d" % i),
473 range(0, len(self.values)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700474 msg = self._format_message(bpf, event.pid, values)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800475 time = strftime("%H:%M:%S") if Probe.use_localtime else \
476 Probe._time_off_str(event.timestamp_ns)
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300477 print("%-8s %-6d %-12s %-16s %s" %
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800478 (time[:8], event.pid, event.comm[:12],
479 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800480
Teng Qin6b0ed372016-09-29 21:30:13 -0700481 if self.user_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700482 print(" User Stack Trace:")
483 self.print_stack(bpf, event.user_stack_id, event.pid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700484 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700485 print(" Kernel Stack Trace:")
486 self.print_stack(bpf, event.kernel_stack_id, -1)
Teng Qin6b0ed372016-09-29 21:30:13 -0700487 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700488 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700489
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800490 Probe.event_count += 1
491 if Probe.max_events is not None and \
492 Probe.event_count >= Probe.max_events:
493 exit()
494
495 def attach(self, bpf, verbose):
496 if len(self.library) == 0:
497 self._attach_k(bpf)
498 else:
499 self._attach_u(bpf)
500 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700501 callback = partial(self.print_event, bpf)
502 bpf[self.events_name].open_perf_buffer(callback)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800503
504 def _attach_k(self, bpf):
505 if self.probe_type == "r":
506 bpf.attach_kretprobe(event=self.function,
507 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300508 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800509 bpf.attach_kprobe(event=self.function,
510 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300511 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800512
513 def _attach_u(self, bpf):
514 libpath = BPF.find_library(self.library)
515 if libpath is None:
516 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300517 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800518 if libpath is None or len(libpath) == 0:
519 self._bail("unable to find library %s" % self.library)
520
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700521 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300522 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700523 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800524 bpf.attach_uretprobe(name=libpath,
525 sym=self.function,
526 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700527 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800528 else:
529 bpf.attach_uprobe(name=libpath,
530 sym=self.function,
531 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700532 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800533
534class Tool(object):
535 examples = """
536EXAMPLES:
537
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800538trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800539 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800540trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800541 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800542trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800543 Trace the read syscall and print a message for reads >20000 bytes
544trace 'r::do_sys_return "%llx", retval'
545 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800546trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800547 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800548trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800549 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800550trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
551 Trace the write() call from libc to monitor writes to STDOUT
552trace 'r::__kmalloc (retval == 0) "kmalloc failed!"
553 Trace returns from __kmalloc which returned a null pointer
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700554trace 'r:c:malloc (retval) "allocated = %x", retval
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800555 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300556trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800557 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700558trace 'u:pthread:pthread_create (arg4 != 0)'
559 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800560"""
561
562 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300563 parser = argparse.ArgumentParser(description="Attach to " +
564 "functions and print trace messages.",
565 formatter_class=argparse.RawDescriptionHelpFormatter,
566 epilog=Tool.examples)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800567 parser.add_argument("-p", "--pid", type=int,
568 help="id of the process to trace (optional)")
569 parser.add_argument("-v", "--verbose", action="store_true",
570 help="print resulting BPF program code before executing")
571 parser.add_argument("-Z", "--string-size", type=int,
572 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300573 parser.add_argument("-S", "--include-self",
574 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800575 help="do not filter trace's own pid from the trace")
576 parser.add_argument("-M", "--max-events", type=int,
577 help="number of events to print before quitting")
578 parser.add_argument("-o", "--offset", action="store_true",
579 help="use relative time from first traced message")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300580 parser.add_argument("-K", "--kernel-stack",
581 action="store_true", help="output kernel stack trace")
582 parser.add_argument("-U", "--user-stack",
583 action="store_true", help="output user stack trace")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800584 parser.add_argument(metavar="probe", dest="probes", nargs="+",
585 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300586 parser.add_argument("-I", "--include", action="append",
587 metavar="header",
588 help="additional header files to include in the BPF program")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800589 self.args = parser.parse_args()
590
591 def _create_probes(self):
592 Probe.configure(self.args)
593 self.probes = []
594 for probe_spec in self.args.probes:
595 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700596 probe_spec, self.args.string_size,
597 self.args.kernel_stack, self.args.user_stack))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800598
599 def _generate_program(self):
600 self.program = """
601#include <linux/ptrace.h>
602#include <linux/sched.h> /* For TASK_COMM_LEN */
603
604"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300605 for include in (self.args.include or []):
606 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700607 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800608 map(lambda p: p.raw_probe, self.probes))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800609 for probe in self.probes:
610 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700611 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800612
613 if self.args.verbose:
614 print(self.program)
615
616 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300617 usdt_contexts = []
618 for probe in self.probes:
619 if probe.usdt:
620 # USDT probes must be enabled before the BPF object
621 # is initialized, because that's where the actual
622 # uprobe is being attached.
623 probe.usdt.enable_probe(
624 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300625 if self.args.verbose:
626 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300627 usdt_contexts.append(probe.usdt)
628 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800629 for probe in self.probes:
630 if self.args.verbose:
631 print(probe)
632 probe.attach(self.bpf, self.args.verbose)
633
634 def _main_loop(self):
635 all_probes_trivial = all(map(Probe.is_default_action,
636 self.probes))
637
638 # Print header
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300639 print("%-8s %-6s %-12s %-16s %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800640 ("TIME", "PID", "COMM", "FUNC",
641 "-" if not all_probes_trivial else ""))
642
643 while True:
644 self.bpf.kprobe_poll()
645
646 def run(self):
647 try:
648 self._create_probes()
649 self._generate_program()
650 self._attach_probes()
651 self._main_loop()
652 except:
653 if self.args.verbose:
654 traceback.print_exc()
Brenden Blancode14f4f2016-04-08 15:52:55 -0700655 elif sys.exc_info()[0] is not SystemExit:
656 print(sys.exc_info()[1])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800657
658if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300659 Tool().run()