blob: 6915fc0b96183a02be21b5cc9acee63b129f86ee [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]
7# 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:
109 self._parse_filter(text[:i+1])
110 text = text[i+1:]
111 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 Goldshtein376ae5c2016-10-04 19:49:57 +0300142 self.function = "" # generated 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 Goldshtein69e361a2016-09-27 19:40:00 +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 Goldshteinaccd4cf2016-10-11 07:56:13 -0700166 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 Goldshtein69e361a2016-09-27 19:40:00 +0300210 # actual arguments for that probe obtained using special
211 # 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
217 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,
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700220 "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
248 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",
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700252 "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 Goldshtein69e361a2016-09-27 19:40:00 +0300307 " bpf_usdt_readarg(%s, ctx, &%s);\n") % \
308 (expr, expr[3], expr)
309
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 }
315""" % (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():
325 if not (arg.startswith("arg") and (arg in self.filter)):
326 continue
327 arg_index = int(arg.replace("arg", ""))
328 arg_ctype = self.usdt.get_probe_arg_ctype(
329 self.usdt_name, arg_index)
330 if not arg_ctype:
331 self._bail("Unable to determine type of {} "
332 "in the filter".format(arg))
333 text += """
334 {} {}_filter;
335 bpf_usdt_readarg({}, ctx, &{}_filter);
336 """.format(arg_ctype, arg, arg_index, arg)
337 self.filter = self.filter.replace(
338 arg, "{}_filter".format(arg))
339 return text
340
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700341 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800342 data_decl = self._generate_data_decl()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800343 # kprobes don't have built-in pid filters, so we have to add
344 # it to the function body:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700345 if len(self.library) == 0 and Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800346 pid_filter = """
347 u32 __pid = bpf_get_current_pid_tgid();
348 if (__pid != %d) { return 0; }
Sasha Goldshteinde34c252016-06-30 12:16:39 +0300349""" % Probe.pid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800350 elif not include_self:
351 pid_filter = """
352 u32 __pid = bpf_get_current_pid_tgid();
353 if (__pid == %d) { return 0; }
354""" % os.getpid()
355 else:
356 pid_filter = ""
357
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700358 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700359 signature = "struct pt_regs *ctx"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700360
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800361 data_fields = ""
362 for i, expr in enumerate(self.values):
363 data_fields += self._generate_field_assign(i)
364
Teng Qin6b0ed372016-09-29 21:30:13 -0700365 stack_trace = ""
366 if self.user_stack:
367 stack_trace += """
368 __data.user_stack_id = %s.get_stackid(
369 ctx, BPF_F_REUSE_STACKID | BPF_F_USER_STACK
370 );""" % self.stacks_name
371 if self.kernel_stack:
372 stack_trace += """
373 __data.kernel_stack_id = %s.get_stackid(
374 ctx, BPF_F_REUSE_STACKID
375 );""" % self.stacks_name
376
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300377 if self.probe_type == "t":
378 heading = "TRACEPOINT_PROBE(%s, %s)" % \
379 (self.tp_category, self.tp_event)
380 ctx_name = "args"
381 else:
382 heading = "int %s(%s)" % (self.probe_name, signature)
383 ctx_name = "ctx"
384 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800385{
386 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800387 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700388 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800389 if (!(%s)) return 0;
390
391 struct %s __data = {0};
392 __data.timestamp_ns = bpf_ktime_get_ns();
393 __data.pid = bpf_get_current_pid_tgid();
394 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
395%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700396%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300397 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800398 return 0;
399}
400"""
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300401 text = text % (pid_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700402 self._generate_usdt_filter_read(), self.filter,
Teng Qin6b0ed372016-09-29 21:30:13 -0700403 self.struct_name, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300404 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700405
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800406 return data_decl + "\n" + text
407
408 @classmethod
409 def _time_off_str(cls, timestamp_ns):
410 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
411
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800412 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700413 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800414 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700415 elif self.probe_type == 'u':
416 return self.usdt_name
417 else: # self.probe_type == 't'
418 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800419
Teng Qin6b0ed372016-09-29 21:30:13 -0700420 def print_stack(self, bpf, stack_id, pid):
421 if stack_id < 0:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700422 print(" %d" % stack_id)
423 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700424
425 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
426 for addr in stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700427 print(" %016x %s" % (addr, bpf.sym(addr, pid)))
428
429 def _format_message(self, bpf, pid, values):
430 # Replace each %K with kernel sym and %U with user sym in pid
431 kernel_placeholders = [i for i in xrange(0, len(self.types))
432 if self.types[i] == 'K']
433 user_placeholders = [i for i in xrange(0, len(self.types))
434 if self.types[i] == 'U']
435 for kp in kernel_placeholders:
436 values[kp] = bpf.ksymaddr(values[kp])
437 for up in user_placeholders:
438 values[up] = bpf.symaddr(values[up], pid)
439 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700440
441 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800442 # Cast as the generated structure type and display
443 # according to the format string in the probe.
444 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
445 values = map(lambda i: getattr(event, "v%d" % i),
446 range(0, len(self.values)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700447 msg = self._format_message(bpf, event.pid, values)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800448 time = strftime("%H:%M:%S") if Probe.use_localtime else \
449 Probe._time_off_str(event.timestamp_ns)
450 print("%-8s %-6d %-12s %-16s %s" % \
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800451 (time[:8], event.pid, event.comm[:12],
452 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800453
Teng Qin6b0ed372016-09-29 21:30:13 -0700454 if self.user_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700455 print(" User Stack Trace:")
456 self.print_stack(bpf, event.user_stack_id, event.pid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700457 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700458 print(" Kernel Stack Trace:")
459 self.print_stack(bpf, event.kernel_stack_id, -1)
Teng Qin6b0ed372016-09-29 21:30:13 -0700460 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700461 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700462
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800463 Probe.event_count += 1
464 if Probe.max_events is not None and \
465 Probe.event_count >= Probe.max_events:
466 exit()
467
468 def attach(self, bpf, verbose):
469 if len(self.library) == 0:
470 self._attach_k(bpf)
471 else:
472 self._attach_u(bpf)
473 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700474 callback = partial(self.print_event, bpf)
475 bpf[self.events_name].open_perf_buffer(callback)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800476
477 def _attach_k(self, bpf):
478 if self.probe_type == "r":
479 bpf.attach_kretprobe(event=self.function,
480 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300481 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800482 bpf.attach_kprobe(event=self.function,
483 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300484 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800485
486 def _attach_u(self, bpf):
487 libpath = BPF.find_library(self.library)
488 if libpath is None:
489 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300490 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800491 if libpath is None or len(libpath) == 0:
492 self._bail("unable to find library %s" % self.library)
493
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700494 if self.probe_type == "u":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300495 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700496 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800497 bpf.attach_uretprobe(name=libpath,
498 sym=self.function,
499 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700500 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800501 else:
502 bpf.attach_uprobe(name=libpath,
503 sym=self.function,
504 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700505 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800506
507class Tool(object):
508 examples = """
509EXAMPLES:
510
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800511trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800512 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800513trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800514 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800515trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800516 Trace the read syscall and print a message for reads >20000 bytes
517trace 'r::do_sys_return "%llx", retval'
518 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800519trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800520 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800521trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800522 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800523trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
524 Trace the write() call from libc to monitor writes to STDOUT
525trace 'r::__kmalloc (retval == 0) "kmalloc failed!"
526 Trace returns from __kmalloc which returned a null pointer
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800527trace 'r:c:malloc (retval) "allocated = %p", retval
528 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300529trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800530 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700531trace 'u:pthread:pthread_create (arg4 != 0)'
532 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800533"""
534
535 def __init__(self):
536 parser = argparse.ArgumentParser(description=
537 "Attach to functions and print trace messages.",
538 formatter_class=argparse.RawDescriptionHelpFormatter,
539 epilog=Tool.examples)
540 parser.add_argument("-p", "--pid", type=int,
541 help="id of the process to trace (optional)")
542 parser.add_argument("-v", "--verbose", action="store_true",
543 help="print resulting BPF program code before executing")
544 parser.add_argument("-Z", "--string-size", type=int,
545 default=80, help="maximum size to read from strings")
546 parser.add_argument("-S", "--include-self", action="store_true",
547 help="do not filter trace's own pid from the trace")
548 parser.add_argument("-M", "--max-events", type=int,
549 help="number of events to print before quitting")
550 parser.add_argument("-o", "--offset", action="store_true",
551 help="use relative time from first traced message")
Teng Qin6b0ed372016-09-29 21:30:13 -0700552 parser.add_argument("-K", "--kernel-stack", action="store_true",
553 help="output kernel stack trace")
554 parser.add_argument("-U", "--user_stack", action="store_true",
555 help="output user stack trace")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800556 parser.add_argument(metavar="probe", dest="probes", nargs="+",
557 help="probe specifier (see examples)")
558 self.args = parser.parse_args()
559
560 def _create_probes(self):
561 Probe.configure(self.args)
562 self.probes = []
563 for probe_spec in self.args.probes:
564 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700565 probe_spec, self.args.string_size,
566 self.args.kernel_stack, self.args.user_stack))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800567
568 def _generate_program(self):
569 self.program = """
570#include <linux/ptrace.h>
571#include <linux/sched.h> /* For TASK_COMM_LEN */
572
573"""
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700574 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800575 map(lambda p: p.raw_probe, self.probes))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800576 for probe in self.probes:
577 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700578 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800579
580 if self.args.verbose:
581 print(self.program)
582
583 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300584 usdt_contexts = []
585 for probe in self.probes:
586 if probe.usdt:
587 # USDT probes must be enabled before the BPF object
588 # is initialized, because that's where the actual
589 # uprobe is being attached.
590 probe.usdt.enable_probe(
591 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300592 if self.args.verbose:
593 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300594 usdt_contexts.append(probe.usdt)
595 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800596 for probe in self.probes:
597 if self.args.verbose:
598 print(probe)
599 probe.attach(self.bpf, self.args.verbose)
600
601 def _main_loop(self):
602 all_probes_trivial = all(map(Probe.is_default_action,
603 self.probes))
604
605 # Print header
606 print("%-8s %-6s %-12s %-16s %s" % \
607 ("TIME", "PID", "COMM", "FUNC",
608 "-" if not all_probes_trivial else ""))
609
610 while True:
611 self.bpf.kprobe_poll()
612
613 def run(self):
614 try:
615 self._create_probes()
616 self._generate_program()
617 self._attach_probes()
618 self._main_loop()
619 except:
620 if self.args.verbose:
621 traceback.print_exc()
Brenden Blancode14f4f2016-04-08 15:52:55 -0700622 elif sys.exc_info()[0] is not SystemExit:
623 print(sys.exc_info()[1])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800624
625if __name__ == "__main__":
626 Tool().run()