blob: 2e168b0f5636def819506a9fd508957924aec8b2 [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
Teng Qin9b04a6f2016-07-31 10:17:07 -070012from bcc import BPF, Tracepoint, Perf, USDT
Sasha Goldshtein38847f02016-02-22 02:19:24 -080013from time import sleep, strftime
14import argparse
15import re
16import ctypes as ct
17import os
18import traceback
19import sys
20
21class Time(object):
22 # BPF timestamps come from the monotonic clock. To be able to filter
23 # and compare them from Python, we need to invoke clock_gettime.
24 # Adapted from http://stackoverflow.com/a/1205762
25 CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h>
26
27 class timespec(ct.Structure):
28 _fields_ = [
29 ('tv_sec', ct.c_long),
30 ('tv_nsec', ct.c_long)
31 ]
32
33 librt = ct.CDLL('librt.so.1', use_errno=True)
34 clock_gettime = librt.clock_gettime
35 clock_gettime.argtypes = [ct.c_int, ct.POINTER(timespec)]
36
37 @staticmethod
38 def monotonic_time():
39 t = Time.timespec()
40 if Time.clock_gettime(
41 Time.CLOCK_MONOTONIC_RAW, ct.pointer(t)) != 0:
42 errno_ = ct.get_errno()
43 raise OSError(errno_, os.strerror(errno_))
44 return t.tv_sec * 1e9 + t.tv_nsec
45
46class Probe(object):
47 probe_count = 0
48 max_events = None
49 event_count = 0
50 first_ts = 0
51 use_localtime = True
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070052 pid = -1
Sasha Goldshtein38847f02016-02-22 02:19:24 -080053
54 @classmethod
55 def configure(cls, args):
56 cls.max_events = args.max_events
57 cls.use_localtime = not args.offset
58 cls.first_ts = Time.monotonic_time()
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070059 cls.pid = args.pid or -1
Sasha Goldshtein38847f02016-02-22 02:19:24 -080060
61 def __init__(self, probe, string_size):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +030062 self.usdt = None
Sasha Goldshtein38847f02016-02-22 02:19:24 -080063 self.raw_probe = probe
64 self.string_size = string_size
65 Probe.probe_count += 1
66 self._parse_probe()
67 self.probe_num = Probe.probe_count
68 self.probe_name = "probe_%s_%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070069 (self._display_function(), self.probe_num)
Sasha Goldshtein38847f02016-02-22 02:19:24 -080070
71 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070072 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
73 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080074 self.types, self.values)
75
76 def is_default_action(self):
77 return self.python_format == ""
78
79 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070080 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080081 (self.raw_probe, error))
82
83 def _parse_probe(self):
84 text = self.raw_probe
85
86 # Everything until the first space is the probe specifier
87 first_space = text.find(' ')
88 spec = text[:first_space] if first_space >= 0 else text
89 self._parse_spec(spec)
90 if first_space >= 0:
91 text = text[first_space:].lstrip()
92 else:
93 text = ""
94
95 # If we now have a (, wait for the balanced closing ) and that
96 # will be the predicate
97 self.filter = None
98 if len(text) > 0 and text[0] == "(":
99 balance = 1
100 for i in range(1, len(text)):
101 if text[i] == "(":
102 balance += 1
103 if text[i] == ")":
104 balance -= 1
105 if balance == 0:
106 self._parse_filter(text[:i+1])
107 text = text[i+1:]
108 break
109 if self.filter is None:
110 self._bail("unmatched end of predicate")
111
112 if self.filter is None:
113 self.filter = "1"
114
115 # The remainder of the text is the printf action
116 self._parse_action(text.lstrip())
117
118 def _parse_spec(self, spec):
119 parts = spec.split(":")
120 # Two special cases: 'func' means 'p::func', 'lib:func' means
121 # 'p:lib:func'. Other combinations need to provide an empty
122 # value between delimiters, e.g. 'r::func' for a kretprobe on
123 # the function func.
124 if len(parts) == 1:
125 parts = ["p", "", parts[0]]
126 elif len(parts) == 2:
127 parts = ["p", parts[0], parts[1]]
128 if len(parts[0]) == 0:
129 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700130 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800131 self.probe_type = parts[0]
132 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700133 self._bail("probe type must be '', 'p', 't', 'r', " +
134 "or 'u', but got '%s'" % parts[0])
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800135 if self.probe_type == "t":
136 self.tp_category = parts[1]
137 self.tp_event = parts[2]
Sasha Goldshteinc08c4312016-03-21 03:52:09 -0700138 self.tp = Tracepoint.enable_tracepoint(
139 self.tp_category, self.tp_event)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800140 self.library = "" # kernel
141 self.function = "perf_trace_%s" % self.tp_event
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700142 elif self.probe_type == "u":
143 self.library = parts[1]
144 self.usdt_name = parts[2]
145 self.function = "" # no function, just address
146 # We will discover the USDT provider by matching on
147 # the USDT name in the specified library
148 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800149 else:
150 self.library = parts[1]
151 self.function = parts[2]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800152
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700153 def _find_usdt_probe(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300154 self.usdt = USDT(path=self.library, pid=Probe.pid)
155 for probe in self.usdt.enumerate_probes():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700156 if probe.name == self.usdt_name:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300157 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700158 self._bail("unrecognized USDT probe %s" % self.usdt_name)
159
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800160 def _parse_filter(self, filt):
161 self.filter = self._replace_args(filt)
162
163 def _parse_types(self, fmt):
164 for match in re.finditer(
165 r'[^%]%(s|u|d|llu|lld|hu|hd|x|llx|c)', fmt):
166 self.types.append(match.group(1))
167 fmt = re.sub(r'([^%]%)(u|d|llu|lld|hu|hd)', r'\1d', fmt)
168 fmt = re.sub(r'([^%]%)(x|llx)', r'\1x', fmt)
169 self.python_format = fmt.strip('"')
170
171 def _parse_action(self, action):
172 self.values = []
173 self.types = []
174 self.python_format = ""
175 if len(action) == 0:
176 return
177
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800178 action = action.strip()
179 match = re.search(r'(\".*\"),?(.*)', action)
180 if match is None:
181 self._bail("expected format string in \"s")
182
183 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800184 self._parse_types(self.raw_format)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800185 for part in match.group(2).split(','):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800186 part = self._replace_args(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800187 if len(part) > 0:
188 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800189
190 aliases = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530191 "retval": "PT_REGS_RC(ctx)",
192 "arg1": "PT_REGS_PARM1(ctx)",
193 "arg2": "PT_REGS_PARM2(ctx)",
194 "arg3": "PT_REGS_PARM3(ctx)",
195 "arg4": "PT_REGS_PARM4(ctx)",
196 "arg5": "PT_REGS_PARM5(ctx)",
197 "arg6": "PT_REGS_PARM6(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800198 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
199 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
200 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
201 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
202 "$cpu": "bpf_get_smp_processor_id()"
203 }
204
205 def _replace_args(self, expr):
206 for alias, replacement in Probe.aliases.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700207 # For USDT probes, we replace argN values with the
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300208 # actual arguments for that probe obtained using special
209 # bpf_readarg_N macros emitted at BPF construction.
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700210 if alias.startswith("arg") and self.probe_type == "u":
211 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800212 expr = expr.replace(alias, replacement)
213 return expr
214
215 p_type = { "u": ct.c_uint, "d": ct.c_int,
216 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
217 "hu": ct.c_ushort, "hd": ct.c_short,
218 "x": ct.c_uint, "llx": ct.c_ulonglong,
219 "c": ct.c_ubyte }
220
221 def _generate_python_field_decl(self, idx, fields):
222 field_type = self.types[idx]
223 if field_type == "s":
224 ptype = ct.c_char * self.string_size
225 else:
226 ptype = Probe.p_type[field_type]
227 fields.append(("v%d" % idx, ptype))
228
229 def _generate_python_data_decl(self):
230 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700231 (self._display_function(), self.probe_num)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800232 fields = [
233 ("timestamp_ns", ct.c_ulonglong),
234 ("pid", ct.c_uint),
235 ("comm", ct.c_char * 16) # TASK_COMM_LEN
236 ]
237 for i in range(0, len(self.types)):
238 self._generate_python_field_decl(i, fields)
239 return type(self.python_struct_name, (ct.Structure,),
240 dict(_fields_=fields))
241
242 c_type = { "u": "unsigned int", "d": "int",
243 "llu": "unsigned long long", "lld": "long long",
244 "hu": "unsigned short", "hd": "short",
245 "x": "unsigned int", "llx": "unsigned long long",
246 "c": "char" }
247 fmt_types = c_type.keys()
248
249 def _generate_field_decl(self, idx):
250 field_type = self.types[idx]
251 if field_type == "s":
252 return "char v%d[%d];\n" % (idx, self.string_size)
253 if field_type in Probe.fmt_types:
254 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
255 self._bail("unrecognized format specifier %s" % field_type)
256
257 def _generate_data_decl(self):
258 # The BPF program will populate values into the struct
259 # according to the format string, and the Python program will
260 # construct the final display string.
261 self.events_name = "%s_events" % self.probe_name
262 self.struct_name = "%s_data_t" % self.probe_name
263
264 data_fields = ""
265 for i, field_type in enumerate(self.types):
266 data_fields += " " + \
267 self._generate_field_decl(i)
268
269 text = """
270struct %s
271{
272 u64 timestamp_ns;
273 u32 pid;
274 char comm[TASK_COMM_LEN];
275%s
276};
277
278BPF_PERF_OUTPUT(%s);
279"""
280 return text % (self.struct_name, data_fields, self.events_name)
281
282 def _generate_field_assign(self, idx):
283 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300284 expr = self.values[idx].strip()
285 text = ""
286 if self.probe_type == "u" and expr[0:3] == "arg":
287 text = (" u64 %s;\n" +
288 " bpf_usdt_readarg(%s, ctx, &%s);\n") % \
289 (expr, expr[3], expr)
290
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800291 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300292 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800293 if (%s != 0) {
294 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), (void *)%s);
295 }
296""" % (expr, idx, idx, expr)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800297 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300298 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800299 (idx, Probe.c_type[field_type], expr)
300 self._bail("unrecognized field type %s" % field_type)
301
Teng Qin0615bff2016-09-28 08:19:40 -0700302 def _generate_usdt_filter_read(self):
303 text = ""
304 if self.probe_type == "u":
305 for arg, _ in Probe.aliases.items():
306 if not (arg.startswith("arg") and (arg in self.filter)):
307 continue
308 arg_index = int(arg.replace("arg", ""))
309 arg_ctype = self.usdt.get_probe_arg_ctype(
310 self.usdt_name, arg_index)
311 if not arg_ctype:
312 self._bail("Unable to determine type of {} "
313 "in the filter".format(arg))
314 text += """
315 {} {}_filter;
316 bpf_usdt_readarg({}, ctx, &{}_filter);
317 """.format(arg_ctype, arg, arg_index, arg)
318 self.filter = self.filter.replace(
319 arg, "{}_filter".format(arg))
320 return text
321
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700322 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800323 data_decl = self._generate_data_decl()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800324 # kprobes don't have built-in pid filters, so we have to add
325 # it to the function body:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700326 if len(self.library) == 0 and Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800327 pid_filter = """
328 u32 __pid = bpf_get_current_pid_tgid();
329 if (__pid != %d) { return 0; }
Sasha Goldshteinde34c252016-06-30 12:16:39 +0300330""" % Probe.pid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800331 elif not include_self:
332 pid_filter = """
333 u32 __pid = bpf_get_current_pid_tgid();
334 if (__pid == %d) { return 0; }
335""" % os.getpid()
336 else:
337 pid_filter = ""
338
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700339 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700340 signature = "struct pt_regs *ctx"
341 if self.probe_type == "t":
342 data_decl += self.tp.generate_struct()
343 prefix = self.tp.generate_get_struct()
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700344
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800345 data_fields = ""
346 for i, expr in enumerate(self.values):
347 data_fields += self._generate_field_assign(i)
348
349 text = """
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300350int %s(%s)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800351{
352 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800353 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700354 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800355 if (!(%s)) return 0;
356
357 struct %s __data = {0};
358 __data.timestamp_ns = bpf_ktime_get_ns();
359 __data.pid = bpf_get_current_pid_tgid();
360 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
361%s
362 %s.perf_submit(ctx, &__data, sizeof(__data));
363 return 0;
364}
365"""
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300366 text = text % (self.probe_name, signature,
Teng Qin0615bff2016-09-28 08:19:40 -0700367 pid_filter, prefix,
368 self._generate_usdt_filter_read(), self.filter,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700369 self.struct_name, data_fields, self.events_name)
370
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800371 return data_decl + "\n" + text
372
373 @classmethod
374 def _time_off_str(cls, timestamp_ns):
375 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
376
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800377 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700378 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800379 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700380 elif self.probe_type == 'u':
381 return self.usdt_name
382 else: # self.probe_type == 't'
383 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800384
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800385 def print_event(self, cpu, data, size):
386 # Cast as the generated structure type and display
387 # according to the format string in the probe.
388 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
389 values = map(lambda i: getattr(event, "v%d" % i),
390 range(0, len(self.values)))
391 msg = self.python_format % tuple(values)
392 time = strftime("%H:%M:%S") if Probe.use_localtime else \
393 Probe._time_off_str(event.timestamp_ns)
394 print("%-8s %-6d %-12s %-16s %s" % \
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800395 (time[:8], event.pid, event.comm[:12],
396 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800397
398 Probe.event_count += 1
399 if Probe.max_events is not None and \
400 Probe.event_count >= Probe.max_events:
401 exit()
402
403 def attach(self, bpf, verbose):
404 if len(self.library) == 0:
405 self._attach_k(bpf)
406 else:
407 self._attach_u(bpf)
408 self.python_struct = self._generate_python_data_decl()
409 bpf[self.events_name].open_perf_buffer(self.print_event)
410
411 def _attach_k(self, bpf):
412 if self.probe_type == "r":
413 bpf.attach_kretprobe(event=self.function,
414 fn_name=self.probe_name)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800415 elif self.probe_type == "p" or self.probe_type == "t":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800416 bpf.attach_kprobe(event=self.function,
417 fn_name=self.probe_name)
418
419 def _attach_u(self, bpf):
420 libpath = BPF.find_library(self.library)
421 if libpath is None:
422 # This might be an executable (e.g. 'bash')
Teng Qin9b04a6f2016-07-31 10:17:07 -0700423 libpath = BPF._find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800424 if libpath is None or len(libpath) == 0:
425 self._bail("unable to find library %s" % self.library)
426
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700427 if self.probe_type == "u":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300428 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700429 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800430 bpf.attach_uretprobe(name=libpath,
431 sym=self.function,
432 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700433 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800434 else:
435 bpf.attach_uprobe(name=libpath,
436 sym=self.function,
437 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700438 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800439
440class Tool(object):
441 examples = """
442EXAMPLES:
443
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800444trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800445 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800446trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800447 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800448trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800449 Trace the read syscall and print a message for reads >20000 bytes
450trace 'r::do_sys_return "%llx", retval'
451 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800452trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800453 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800454trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800455 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800456trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
457 Trace the write() call from libc to monitor writes to STDOUT
458trace 'r::__kmalloc (retval == 0) "kmalloc failed!"
459 Trace returns from __kmalloc which returned a null pointer
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800460trace 'r:c:malloc (retval) "allocated = %p", retval
461 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800462trace 't:block:block_rq_complete "sectors=%d", tp.nr_sector'
463 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700464trace 'u:pthread:pthread_create (arg4 != 0)'
465 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800466"""
467
468 def __init__(self):
469 parser = argparse.ArgumentParser(description=
470 "Attach to functions and print trace messages.",
471 formatter_class=argparse.RawDescriptionHelpFormatter,
472 epilog=Tool.examples)
473 parser.add_argument("-p", "--pid", type=int,
474 help="id of the process to trace (optional)")
475 parser.add_argument("-v", "--verbose", action="store_true",
476 help="print resulting BPF program code before executing")
477 parser.add_argument("-Z", "--string-size", type=int,
478 default=80, help="maximum size to read from strings")
479 parser.add_argument("-S", "--include-self", action="store_true",
480 help="do not filter trace's own pid from the trace")
481 parser.add_argument("-M", "--max-events", type=int,
482 help="number of events to print before quitting")
483 parser.add_argument("-o", "--offset", action="store_true",
484 help="use relative time from first traced message")
485 parser.add_argument(metavar="probe", dest="probes", nargs="+",
486 help="probe specifier (see examples)")
487 self.args = parser.parse_args()
488
489 def _create_probes(self):
490 Probe.configure(self.args)
491 self.probes = []
492 for probe_spec in self.args.probes:
493 self.probes.append(Probe(
494 probe_spec, self.args.string_size))
495
496 def _generate_program(self):
497 self.program = """
498#include <linux/ptrace.h>
499#include <linux/sched.h> /* For TASK_COMM_LEN */
500
501"""
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700502 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800503 map(lambda p: p.raw_probe, self.probes))
504 self.program += Tracepoint.generate_decl()
505 self.program += Tracepoint.generate_entry_probe()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800506 for probe in self.probes:
507 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700508 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800509
510 if self.args.verbose:
511 print(self.program)
512
513 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300514 usdt_contexts = []
515 for probe in self.probes:
516 if probe.usdt:
517 # USDT probes must be enabled before the BPF object
518 # is initialized, because that's where the actual
519 # uprobe is being attached.
520 probe.usdt.enable_probe(
521 probe.usdt_name, probe.probe_name)
522 usdt_contexts.append(probe.usdt)
523 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800524 Tracepoint.attach(self.bpf)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800525 for probe in self.probes:
526 if self.args.verbose:
527 print(probe)
528 probe.attach(self.bpf, self.args.verbose)
529
530 def _main_loop(self):
531 all_probes_trivial = all(map(Probe.is_default_action,
532 self.probes))
533
534 # Print header
535 print("%-8s %-6s %-12s %-16s %s" % \
536 ("TIME", "PID", "COMM", "FUNC",
537 "-" if not all_probes_trivial else ""))
538
539 while True:
540 self.bpf.kprobe_poll()
541
542 def run(self):
543 try:
544 self._create_probes()
545 self._generate_program()
546 self._attach_probes()
547 self._main_loop()
548 except:
549 if self.args.verbose:
550 traceback.print_exc()
Brenden Blancode14f4f2016-04-08 15:52:55 -0700551 elif sys.exc_info()[0] is not SystemExit:
552 print(sys.exc_info()[1])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800553
554if __name__ == "__main__":
555 Tool().run()