blob: d37c60d8751eeffd8ac7b96657958652a3f7db63 [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
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700302 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800303 data_decl = self._generate_data_decl()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800304 # kprobes don't have built-in pid filters, so we have to add
305 # it to the function body:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700306 if len(self.library) == 0 and Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800307 pid_filter = """
308 u32 __pid = bpf_get_current_pid_tgid();
309 if (__pid != %d) { return 0; }
Sasha Goldshteinde34c252016-06-30 12:16:39 +0300310""" % Probe.pid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800311 elif not include_self:
312 pid_filter = """
313 u32 __pid = bpf_get_current_pid_tgid();
314 if (__pid == %d) { return 0; }
315""" % os.getpid()
316 else:
317 pid_filter = ""
318
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700319 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700320 signature = "struct pt_regs *ctx"
321 if self.probe_type == "t":
322 data_decl += self.tp.generate_struct()
323 prefix = self.tp.generate_get_struct()
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700324
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800325 data_fields = ""
326 for i, expr in enumerate(self.values):
327 data_fields += self._generate_field_assign(i)
328
329 text = """
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300330int %s(%s)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800331{
332 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800333 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800334 if (!(%s)) return 0;
335
336 struct %s __data = {0};
337 __data.timestamp_ns = bpf_ktime_get_ns();
338 __data.pid = bpf_get_current_pid_tgid();
339 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
340%s
341 %s.perf_submit(ctx, &__data, sizeof(__data));
342 return 0;
343}
344"""
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300345 text = text % (self.probe_name, signature,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700346 pid_filter, prefix, self.filter,
347 self.struct_name, data_fields, self.events_name)
348
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800349 return data_decl + "\n" + text
350
351 @classmethod
352 def _time_off_str(cls, timestamp_ns):
353 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
354
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800355 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700356 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800357 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700358 elif self.probe_type == 'u':
359 return self.usdt_name
360 else: # self.probe_type == 't'
361 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800362
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800363 def print_event(self, cpu, data, size):
364 # Cast as the generated structure type and display
365 # according to the format string in the probe.
366 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
367 values = map(lambda i: getattr(event, "v%d" % i),
368 range(0, len(self.values)))
369 msg = self.python_format % tuple(values)
370 time = strftime("%H:%M:%S") if Probe.use_localtime else \
371 Probe._time_off_str(event.timestamp_ns)
372 print("%-8s %-6d %-12s %-16s %s" % \
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800373 (time[:8], event.pid, event.comm[:12],
374 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800375
376 Probe.event_count += 1
377 if Probe.max_events is not None and \
378 Probe.event_count >= Probe.max_events:
379 exit()
380
381 def attach(self, bpf, verbose):
382 if len(self.library) == 0:
383 self._attach_k(bpf)
384 else:
385 self._attach_u(bpf)
386 self.python_struct = self._generate_python_data_decl()
387 bpf[self.events_name].open_perf_buffer(self.print_event)
388
389 def _attach_k(self, bpf):
390 if self.probe_type == "r":
391 bpf.attach_kretprobe(event=self.function,
392 fn_name=self.probe_name)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800393 elif self.probe_type == "p" or self.probe_type == "t":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800394 bpf.attach_kprobe(event=self.function,
395 fn_name=self.probe_name)
396
397 def _attach_u(self, bpf):
398 libpath = BPF.find_library(self.library)
399 if libpath is None:
400 # This might be an executable (e.g. 'bash')
Teng Qin9b04a6f2016-07-31 10:17:07 -0700401 libpath = BPF._find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800402 if libpath is None or len(libpath) == 0:
403 self._bail("unable to find library %s" % self.library)
404
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700405 if self.probe_type == "u":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300406 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700407 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800408 bpf.attach_uretprobe(name=libpath,
409 sym=self.function,
410 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700411 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800412 else:
413 bpf.attach_uprobe(name=libpath,
414 sym=self.function,
415 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700416 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800417
418class Tool(object):
419 examples = """
420EXAMPLES:
421
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800422trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800423 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800424trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800425 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800426trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800427 Trace the read syscall and print a message for reads >20000 bytes
428trace 'r::do_sys_return "%llx", retval'
429 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800430trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800431 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800432trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800433 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800434trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
435 Trace the write() call from libc to monitor writes to STDOUT
436trace 'r::__kmalloc (retval == 0) "kmalloc failed!"
437 Trace returns from __kmalloc which returned a null pointer
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800438trace 'r:c:malloc (retval) "allocated = %p", retval
439 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800440trace 't:block:block_rq_complete "sectors=%d", tp.nr_sector'
441 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700442trace 'u:pthread:pthread_create (arg4 != 0)'
443 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800444"""
445
446 def __init__(self):
447 parser = argparse.ArgumentParser(description=
448 "Attach to functions and print trace messages.",
449 formatter_class=argparse.RawDescriptionHelpFormatter,
450 epilog=Tool.examples)
451 parser.add_argument("-p", "--pid", type=int,
452 help="id of the process to trace (optional)")
453 parser.add_argument("-v", "--verbose", action="store_true",
454 help="print resulting BPF program code before executing")
455 parser.add_argument("-Z", "--string-size", type=int,
456 default=80, help="maximum size to read from strings")
457 parser.add_argument("-S", "--include-self", action="store_true",
458 help="do not filter trace's own pid from the trace")
459 parser.add_argument("-M", "--max-events", type=int,
460 help="number of events to print before quitting")
461 parser.add_argument("-o", "--offset", action="store_true",
462 help="use relative time from first traced message")
463 parser.add_argument(metavar="probe", dest="probes", nargs="+",
464 help="probe specifier (see examples)")
465 self.args = parser.parse_args()
466
467 def _create_probes(self):
468 Probe.configure(self.args)
469 self.probes = []
470 for probe_spec in self.args.probes:
471 self.probes.append(Probe(
472 probe_spec, self.args.string_size))
473
474 def _generate_program(self):
475 self.program = """
476#include <linux/ptrace.h>
477#include <linux/sched.h> /* For TASK_COMM_LEN */
478
479"""
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700480 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800481 map(lambda p: p.raw_probe, self.probes))
482 self.program += Tracepoint.generate_decl()
483 self.program += Tracepoint.generate_entry_probe()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800484 for probe in self.probes:
485 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700486 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800487
488 if self.args.verbose:
489 print(self.program)
490
491 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300492 usdt_contexts = []
493 for probe in self.probes:
494 if probe.usdt:
495 # USDT probes must be enabled before the BPF object
496 # is initialized, because that's where the actual
497 # uprobe is being attached.
498 probe.usdt.enable_probe(
499 probe.usdt_name, probe.probe_name)
500 usdt_contexts.append(probe.usdt)
501 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800502 Tracepoint.attach(self.bpf)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800503 for probe in self.probes:
504 if self.args.verbose:
505 print(probe)
506 probe.attach(self.bpf, self.args.verbose)
507
508 def _main_loop(self):
509 all_probes_trivial = all(map(Probe.is_default_action,
510 self.probes))
511
512 # Print header
513 print("%-8s %-6s %-12s %-16s %s" % \
514 ("TIME", "PID", "COMM", "FUNC",
515 "-" if not all_probes_trivial else ""))
516
517 while True:
518 self.bpf.kprobe_poll()
519
520 def run(self):
521 try:
522 self._create_probes()
523 self._generate_program()
524 self._attach_probes()
525 self._main_loop()
526 except:
527 if self.args.verbose:
528 traceback.print_exc()
Brenden Blancode14f4f2016-04-08 15:52:55 -0700529 elif sys.exc_info()[0] is not SystemExit:
530 print(sys.exc_info()[1])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800531
532if __name__ == "__main__":
533 Tool().run()