blob: d1169d36f53906d27ce6ac62aa944255d47c54d2 [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
49 max_events = None
50 event_count = 0
51 first_ts = 0
52 use_localtime = True
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070053 pid = -1
Sasha Goldshtein38847f02016-02-22 02:19:24 -080054
55 @classmethod
56 def configure(cls, args):
57 cls.max_events = args.max_events
58 cls.use_localtime = not args.offset
59 cls.first_ts = Time.monotonic_time()
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070060 cls.pid = args.pid or -1
Sasha Goldshtein38847f02016-02-22 02:19:24 -080061
Teng Qin6b0ed372016-09-29 21:30:13 -070062 def __init__(self, probe, string_size, kernel_stack, user_stack):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +030063 self.usdt = None
Sasha Goldshtein38847f02016-02-22 02:19:24 -080064 self.raw_probe = probe
65 self.string_size = string_size
Teng Qin6b0ed372016-09-29 21:30:13 -070066 self.kernel_stack = kernel_stack
67 self.user_stack = user_stack
Sasha Goldshtein38847f02016-02-22 02:19:24 -080068 Probe.probe_count += 1
69 self._parse_probe()
70 self.probe_num = Probe.probe_count
71 self.probe_name = "probe_%s_%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070072 (self._display_function(), self.probe_num)
Sasha Goldshtein38847f02016-02-22 02:19:24 -080073
74 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070075 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
76 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080077 self.types, self.values)
78
79 def is_default_action(self):
80 return self.python_format == ""
81
82 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070083 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080084 (self.raw_probe, error))
85
86 def _parse_probe(self):
87 text = self.raw_probe
88
89 # Everything until the first space is the probe specifier
90 first_space = text.find(' ')
91 spec = text[:first_space] if first_space >= 0 else text
92 self._parse_spec(spec)
93 if first_space >= 0:
94 text = text[first_space:].lstrip()
95 else:
96 text = ""
97
98 # If we now have a (, wait for the balanced closing ) and that
99 # will be the predicate
100 self.filter = None
101 if len(text) > 0 and text[0] == "(":
102 balance = 1
103 for i in range(1, len(text)):
104 if text[i] == "(":
105 balance += 1
106 if text[i] == ")":
107 balance -= 1
108 if balance == 0:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300109 self._parse_filter(text[:i + 1])
110 text = text[i + 1:]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800111 break
112 if self.filter is None:
113 self._bail("unmatched end of predicate")
114
115 if self.filter is None:
116 self.filter = "1"
117
118 # The remainder of the text is the printf action
119 self._parse_action(text.lstrip())
120
121 def _parse_spec(self, spec):
122 parts = spec.split(":")
123 # Two special cases: 'func' means 'p::func', 'lib:func' means
124 # 'p:lib:func'. Other combinations need to provide an empty
125 # value between delimiters, e.g. 'r::func' for a kretprobe on
126 # the function func.
127 if len(parts) == 1:
128 parts = ["p", "", parts[0]]
129 elif len(parts) == 2:
130 parts = ["p", parts[0], parts[1]]
131 if len(parts[0]) == 0:
132 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700133 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800134 self.probe_type = parts[0]
135 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700136 self._bail("probe type must be '', 'p', 't', 'r', " +
137 "or 'u', but got '%s'" % parts[0])
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800138 if self.probe_type == "t":
139 self.tp_category = parts[1]
140 self.tp_event = parts[2]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800141 self.library = "" # kernel
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300142 self.function = "" # from TRACEPOINT_PROBE
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700143 elif self.probe_type == "u":
144 self.library = parts[1]
145 self.usdt_name = parts[2]
146 self.function = "" # no function, just address
147 # We will discover the USDT provider by matching on
148 # the USDT name in the specified library
149 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800150 else:
151 self.library = parts[1]
152 self.function = parts[2]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800153
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700154 def _find_usdt_probe(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300155 self.usdt = USDT(path=self.library, pid=Probe.pid)
156 for probe in self.usdt.enumerate_probes():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700157 if probe.name == self.usdt_name:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300158 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700159 self._bail("unrecognized USDT probe %s" % self.usdt_name)
160
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800161 def _parse_filter(self, filt):
162 self.filter = self._replace_args(filt)
163
164 def _parse_types(self, fmt):
165 for match in re.finditer(
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300166 r'[^%]%(s|u|d|llu|lld|hu|hd|x|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800167 self.types.append(match.group(1))
168 fmt = re.sub(r'([^%]%)(u|d|llu|lld|hu|hd)', r'\1d', fmt)
169 fmt = re.sub(r'([^%]%)(x|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700170 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800171 self.python_format = fmt.strip('"')
172
173 def _parse_action(self, action):
174 self.values = []
175 self.types = []
176 self.python_format = ""
177 if len(action) == 0:
178 return
179
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800180 action = action.strip()
181 match = re.search(r'(\".*\"),?(.*)', action)
182 if match is None:
183 self._bail("expected format string in \"s")
184
185 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800186 self._parse_types(self.raw_format)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800187 for part in match.group(2).split(','):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800188 part = self._replace_args(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800189 if len(part) > 0:
190 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800191
192 aliases = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530193 "retval": "PT_REGS_RC(ctx)",
194 "arg1": "PT_REGS_PARM1(ctx)",
195 "arg2": "PT_REGS_PARM2(ctx)",
196 "arg3": "PT_REGS_PARM3(ctx)",
197 "arg4": "PT_REGS_PARM4(ctx)",
198 "arg5": "PT_REGS_PARM5(ctx)",
199 "arg6": "PT_REGS_PARM6(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800200 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
201 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
202 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
203 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
204 "$cpu": "bpf_get_smp_processor_id()"
205 }
206
207 def _replace_args(self, expr):
208 for alias, replacement in Probe.aliases.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700209 # For USDT probes, we replace argN values with the
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300210 # actual arguments for that probe obtained using
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300211 # bpf_readarg_N macros emitted at BPF construction.
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700212 if alias.startswith("arg") and self.probe_type == "u":
213 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800214 expr = expr.replace(alias, replacement)
215 return expr
216
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300217 p_type = {"u": ct.c_uint, "d": ct.c_int,
218 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
219 "hu": ct.c_ushort, "hd": ct.c_short,
220 "x": ct.c_uint, "llx": ct.c_ulonglong, "c": ct.c_ubyte,
221 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800222
223 def _generate_python_field_decl(self, idx, fields):
224 field_type = self.types[idx]
225 if field_type == "s":
226 ptype = ct.c_char * self.string_size
227 else:
228 ptype = Probe.p_type[field_type]
229 fields.append(("v%d" % idx, ptype))
230
231 def _generate_python_data_decl(self):
232 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700233 (self._display_function(), self.probe_num)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800234 fields = [
235 ("timestamp_ns", ct.c_ulonglong),
236 ("pid", ct.c_uint),
237 ("comm", ct.c_char * 16) # TASK_COMM_LEN
238 ]
239 for i in range(0, len(self.types)):
240 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700241 if self.kernel_stack:
242 fields.append(("kernel_stack_id", ct.c_int))
243 if self.user_stack:
244 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800245 return type(self.python_struct_name, (ct.Structure,),
246 dict(_fields_=fields))
247
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300248 c_type = {"u": "unsigned int", "d": "int",
249 "llu": "unsigned long long", "lld": "long long",
250 "hu": "unsigned short", "hd": "short",
251 "x": "unsigned int", "llx": "unsigned long long",
252 "c": "char", "K": "unsigned long long",
253 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800254 fmt_types = c_type.keys()
255
256 def _generate_field_decl(self, idx):
257 field_type = self.types[idx]
258 if field_type == "s":
259 return "char v%d[%d];\n" % (idx, self.string_size)
260 if field_type in Probe.fmt_types:
261 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
262 self._bail("unrecognized format specifier %s" % field_type)
263
264 def _generate_data_decl(self):
265 # The BPF program will populate values into the struct
266 # according to the format string, and the Python program will
267 # construct the final display string.
268 self.events_name = "%s_events" % self.probe_name
269 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700270 self.stacks_name = "%s_stacks" % self.probe_name
271 stack_table = "BPF_STACK_TRACE(%s, 1024);" % self.stacks_name \
272 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800273 data_fields = ""
274 for i, field_type in enumerate(self.types):
275 data_fields += " " + \
276 self._generate_field_decl(i)
277
Teng Qin6b0ed372016-09-29 21:30:13 -0700278 kernel_stack_str = " int kernel_stack_id;" \
279 if self.kernel_stack else ""
280 user_stack_str = " int user_stack_id;" \
281 if self.user_stack else ""
282
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800283 text = """
284struct %s
285{
286 u64 timestamp_ns;
287 u32 pid;
288 char comm[TASK_COMM_LEN];
289%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700290%s
291%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800292};
293
294BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700295%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800296"""
Teng Qin6b0ed372016-09-29 21:30:13 -0700297 return text % (self.struct_name, data_fields,
298 kernel_stack_str, user_stack_str,
299 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800300
301 def _generate_field_assign(self, idx):
302 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300303 expr = self.values[idx].strip()
304 text = ""
305 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshteinb6db17f2016-10-04 19:50:50 +0300306 text = (" u64 %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300307 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
308 % (expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300309
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800310 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300311 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800312 if (%s != 0) {
313 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), (void *)%s);
314 }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300315 """ % (expr, idx, idx, expr)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800316 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300317 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800318 (idx, Probe.c_type[field_type], expr)
319 self._bail("unrecognized field type %s" % field_type)
320
Teng Qin0615bff2016-09-28 08:19:40 -0700321 def _generate_usdt_filter_read(self):
322 text = ""
323 if self.probe_type == "u":
324 for arg, _ in Probe.aliases.items():
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300325 if not (arg.startswith("arg") and
326 (arg in self.filter)):
Teng Qin0615bff2016-09-28 08:19:40 -0700327 continue
328 arg_index = int(arg.replace("arg", ""))
329 arg_ctype = self.usdt.get_probe_arg_ctype(
330 self.usdt_name, arg_index)
331 if not arg_ctype:
332 self._bail("Unable to determine type of {} "
333 "in the filter".format(arg))
334 text += """
335 {} {}_filter;
336 bpf_usdt_readarg({}, ctx, &{}_filter);
337 """.format(arg_ctype, arg, arg_index, arg)
338 self.filter = self.filter.replace(
339 arg, "{}_filter".format(arg))
340 return text
341
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700342 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800343 data_decl = self._generate_data_decl()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800344 # kprobes don't have built-in pid filters, so we have to add
345 # it to the function body:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700346 if len(self.library) == 0 and Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800347 pid_filter = """
348 u32 __pid = bpf_get_current_pid_tgid();
349 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300350 """ % Probe.pid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800351 elif not include_self:
352 pid_filter = """
353 u32 __pid = bpf_get_current_pid_tgid();
354 if (__pid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300355 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800356 else:
357 pid_filter = ""
358
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700359 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700360 signature = "struct pt_regs *ctx"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700361
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800362 data_fields = ""
363 for i, expr in enumerate(self.values):
364 data_fields += self._generate_field_assign(i)
365
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300366 if self.probe_type == "t":
367 heading = "TRACEPOINT_PROBE(%s, %s)" % \
368 (self.tp_category, self.tp_event)
369 ctx_name = "args"
370 else:
371 heading = "int %s(%s)" % (self.probe_name, signature)
372 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300373
374 stack_trace = ""
375 if self.user_stack:
376 stack_trace += """
377 __data.user_stack_id = %s.get_stackid(
378 %s, BPF_F_REUSE_STACKID | BPF_F_USER_STACK
379 );""" % (self.stacks_name, ctx_name)
380 if self.kernel_stack:
381 stack_trace += """
382 __data.kernel_stack_id = %s.get_stackid(
383 %s, BPF_F_REUSE_STACKID
384 );""" % (self.stacks_name, ctx_name)
385
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300386 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800387{
388 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800389 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700390 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800391 if (!(%s)) return 0;
392
393 struct %s __data = {0};
394 __data.timestamp_ns = bpf_ktime_get_ns();
395 __data.pid = bpf_get_current_pid_tgid();
396 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
397%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700398%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300399 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800400 return 0;
401}
402"""
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300403 text = text % (pid_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700404 self._generate_usdt_filter_read(), self.filter,
Teng Qin6b0ed372016-09-29 21:30:13 -0700405 self.struct_name, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300406 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700407
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800408 return data_decl + "\n" + text
409
410 @classmethod
411 def _time_off_str(cls, timestamp_ns):
412 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
413
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800414 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700415 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800416 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700417 elif self.probe_type == 'u':
418 return self.usdt_name
419 else: # self.probe_type == 't'
420 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800421
Teng Qin6b0ed372016-09-29 21:30:13 -0700422 def print_stack(self, bpf, stack_id, pid):
423 if stack_id < 0:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700424 print(" %d" % stack_id)
425 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700426
427 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
428 for addr in stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700429 print(" %016x %s" % (addr, bpf.sym(addr, pid)))
430
431 def _format_message(self, bpf, pid, values):
432 # Replace each %K with kernel sym and %U with user sym in pid
433 kernel_placeholders = [i for i in xrange(0, len(self.types))
434 if self.types[i] == 'K']
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300435 user_placeholders = [i for i in xrange(0, len(self.types))
436 if self.types[i] == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700437 for kp in kernel_placeholders:
438 values[kp] = bpf.ksymaddr(values[kp])
439 for up in user_placeholders:
440 values[up] = bpf.symaddr(values[up], pid)
441 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700442
443 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800444 # Cast as the generated structure type and display
445 # according to the format string in the probe.
446 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
447 values = map(lambda i: getattr(event, "v%d" % i),
448 range(0, len(self.values)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700449 msg = self._format_message(bpf, event.pid, values)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800450 time = strftime("%H:%M:%S") if Probe.use_localtime else \
451 Probe._time_off_str(event.timestamp_ns)
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300452 print("%-8s %-6d %-12s %-16s %s" %
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800453 (time[:8], event.pid, event.comm[:12],
454 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800455
Teng Qin6b0ed372016-09-29 21:30:13 -0700456 if self.user_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700457 print(" User Stack Trace:")
458 self.print_stack(bpf, event.user_stack_id, event.pid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700459 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700460 print(" Kernel Stack Trace:")
461 self.print_stack(bpf, event.kernel_stack_id, -1)
Teng Qin6b0ed372016-09-29 21:30:13 -0700462 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700463 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700464
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800465 Probe.event_count += 1
466 if Probe.max_events is not None and \
467 Probe.event_count >= Probe.max_events:
468 exit()
469
470 def attach(self, bpf, verbose):
471 if len(self.library) == 0:
472 self._attach_k(bpf)
473 else:
474 self._attach_u(bpf)
475 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700476 callback = partial(self.print_event, bpf)
477 bpf[self.events_name].open_perf_buffer(callback)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800478
479 def _attach_k(self, bpf):
480 if self.probe_type == "r":
481 bpf.attach_kretprobe(event=self.function,
482 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300483 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800484 bpf.attach_kprobe(event=self.function,
485 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300486 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800487
488 def _attach_u(self, bpf):
489 libpath = BPF.find_library(self.library)
490 if libpath is None:
491 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300492 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800493 if libpath is None or len(libpath) == 0:
494 self._bail("unable to find library %s" % self.library)
495
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700496 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300497 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700498 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800499 bpf.attach_uretprobe(name=libpath,
500 sym=self.function,
501 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700502 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800503 else:
504 bpf.attach_uprobe(name=libpath,
505 sym=self.function,
506 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700507 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800508
509class Tool(object):
510 examples = """
511EXAMPLES:
512
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800513trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800514 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800515trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800516 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800517trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800518 Trace the read syscall and print a message for reads >20000 bytes
519trace 'r::do_sys_return "%llx", retval'
520 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800521trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800522 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800523trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800524 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800525trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
526 Trace the write() call from libc to monitor writes to STDOUT
527trace 'r::__kmalloc (retval == 0) "kmalloc failed!"
528 Trace returns from __kmalloc which returned a null pointer
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800529trace 'r:c:malloc (retval) "allocated = %p", retval
530 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300531trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800532 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700533trace 'u:pthread:pthread_create (arg4 != 0)'
534 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800535"""
536
537 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300538 parser = argparse.ArgumentParser(description="Attach to " +
539 "functions and print trace messages.",
540 formatter_class=argparse.RawDescriptionHelpFormatter,
541 epilog=Tool.examples)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800542 parser.add_argument("-p", "--pid", type=int,
543 help="id of the process to trace (optional)")
544 parser.add_argument("-v", "--verbose", action="store_true",
545 help="print resulting BPF program code before executing")
546 parser.add_argument("-Z", "--string-size", type=int,
547 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300548 parser.add_argument("-S", "--include-self",
549 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800550 help="do not filter trace's own pid from the trace")
551 parser.add_argument("-M", "--max-events", type=int,
552 help="number of events to print before quitting")
553 parser.add_argument("-o", "--offset", action="store_true",
554 help="use relative time from first traced message")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300555 parser.add_argument("-K", "--kernel-stack",
556 action="store_true", help="output kernel stack trace")
557 parser.add_argument("-U", "--user-stack",
558 action="store_true", help="output user stack trace")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800559 parser.add_argument(metavar="probe", dest="probes", nargs="+",
560 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300561 parser.add_argument("-I", "--include", action="append",
562 metavar="header",
563 help="additional header files to include in the BPF program")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800564 self.args = parser.parse_args()
565
566 def _create_probes(self):
567 Probe.configure(self.args)
568 self.probes = []
569 for probe_spec in self.args.probes:
570 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700571 probe_spec, self.args.string_size,
572 self.args.kernel_stack, self.args.user_stack))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800573
574 def _generate_program(self):
575 self.program = """
576#include <linux/ptrace.h>
577#include <linux/sched.h> /* For TASK_COMM_LEN */
578
579"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300580 for include in (self.args.include or []):
581 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700582 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800583 map(lambda p: p.raw_probe, self.probes))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800584 for probe in self.probes:
585 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700586 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800587
588 if self.args.verbose:
589 print(self.program)
590
591 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300592 usdt_contexts = []
593 for probe in self.probes:
594 if probe.usdt:
595 # USDT probes must be enabled before the BPF object
596 # is initialized, because that's where the actual
597 # uprobe is being attached.
598 probe.usdt.enable_probe(
599 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300600 if self.args.verbose:
601 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300602 usdt_contexts.append(probe.usdt)
603 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800604 for probe in self.probes:
605 if self.args.verbose:
606 print(probe)
607 probe.attach(self.bpf, self.args.verbose)
608
609 def _main_loop(self):
610 all_probes_trivial = all(map(Probe.is_default_action,
611 self.probes))
612
613 # Print header
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300614 print("%-8s %-6s %-12s %-16s %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800615 ("TIME", "PID", "COMM", "FUNC",
616 "-" if not all_probes_trivial else ""))
617
618 while True:
619 self.bpf.kprobe_poll()
620
621 def run(self):
622 try:
623 self._create_probes()
624 self._generate_program()
625 self._attach_probes()
626 self._main_loop()
627 except:
628 if self.args.verbose:
629 traceback.print_exc()
Brenden Blancode14f4f2016-04-08 15:52:55 -0700630 elif sys.exc_info()[0] is not SystemExit:
631 print(sys.exc_info()[1])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800632
633if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300634 Tool().run()