blob: 9840233f79744fb56c1800c48f405d9ec424a8c8 [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 Goldshtein435839a2016-03-30 13:25:09 -070012from bcc import BPF, Tracepoint, Perf, ProcUtils, USDTReader
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):
62 self.raw_probe = probe
63 self.string_size = string_size
64 Probe.probe_count += 1
65 self._parse_probe()
66 self.probe_num = Probe.probe_count
67 self.probe_name = "probe_%s_%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070068 (self._display_function(), self.probe_num)
Sasha Goldshtein38847f02016-02-22 02:19:24 -080069
70 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070071 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
72 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080073 self.types, self.values)
74
75 def is_default_action(self):
76 return self.python_format == ""
77
78 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070079 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080080 (self.raw_probe, error))
81
82 def _parse_probe(self):
83 text = self.raw_probe
84
85 # Everything until the first space is the probe specifier
86 first_space = text.find(' ')
87 spec = text[:first_space] if first_space >= 0 else text
88 self._parse_spec(spec)
89 if first_space >= 0:
90 text = text[first_space:].lstrip()
91 else:
92 text = ""
93
94 # If we now have a (, wait for the balanced closing ) and that
95 # will be the predicate
96 self.filter = None
97 if len(text) > 0 and text[0] == "(":
98 balance = 1
99 for i in range(1, len(text)):
100 if text[i] == "(":
101 balance += 1
102 if text[i] == ")":
103 balance -= 1
104 if balance == 0:
105 self._parse_filter(text[:i+1])
106 text = text[i+1:]
107 break
108 if self.filter is None:
109 self._bail("unmatched end of predicate")
110
111 if self.filter is None:
112 self.filter = "1"
113
114 # The remainder of the text is the printf action
115 self._parse_action(text.lstrip())
116
117 def _parse_spec(self, spec):
118 parts = spec.split(":")
119 # Two special cases: 'func' means 'p::func', 'lib:func' means
120 # 'p:lib:func'. Other combinations need to provide an empty
121 # value between delimiters, e.g. 'r::func' for a kretprobe on
122 # the function func.
123 if len(parts) == 1:
124 parts = ["p", "", parts[0]]
125 elif len(parts) == 2:
126 parts = ["p", parts[0], parts[1]]
127 if len(parts[0]) == 0:
128 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700129 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800130 self.probe_type = parts[0]
131 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700132 self._bail("probe type must be '', 'p', 't', 'r', " +
133 "or 'u', but got '%s'" % parts[0])
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800134 if self.probe_type == "t":
135 self.tp_category = parts[1]
136 self.tp_event = parts[2]
Sasha Goldshteinc08c4312016-03-21 03:52:09 -0700137 self.tp = Tracepoint.enable_tracepoint(
138 self.tp_category, self.tp_event)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800139 self.library = "" # kernel
140 self.function = "perf_trace_%s" % self.tp_event
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700141 elif self.probe_type == "u":
142 self.library = parts[1]
143 self.usdt_name = parts[2]
144 self.function = "" # no function, just address
145 # We will discover the USDT provider by matching on
146 # the USDT name in the specified library
147 self._find_usdt_probe()
148 self._enable_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 _enable_usdt_probe(self):
154 if self.usdt.need_enable():
155 if Probe.pid == -1:
156 self._bail("probe needs pid to enable")
157 self.usdt.enable(Probe.pid)
158
159 def _disable_usdt_probe(self):
160 if self.probe_type == "u" and self.usdt.need_enable():
161 self.usdt.disable(Probe.pid)
162
163 def close(self):
164 self._disable_usdt_probe()
165
166 def _find_usdt_probe(self):
167 reader = USDTReader(bin_path=self.library)
168 for probe in reader.probes:
169 if probe.name == self.usdt_name:
170 self.usdt = probe
171 return
172 self._bail("unrecognized USDT probe %s" % self.usdt_name)
173
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800174 def _parse_filter(self, filt):
175 self.filter = self._replace_args(filt)
176
177 def _parse_types(self, fmt):
178 for match in re.finditer(
179 r'[^%]%(s|u|d|llu|lld|hu|hd|x|llx|c)', fmt):
180 self.types.append(match.group(1))
181 fmt = re.sub(r'([^%]%)(u|d|llu|lld|hu|hd)', r'\1d', fmt)
182 fmt = re.sub(r'([^%]%)(x|llx)', r'\1x', fmt)
183 self.python_format = fmt.strip('"')
184
185 def _parse_action(self, action):
186 self.values = []
187 self.types = []
188 self.python_format = ""
189 if len(action) == 0:
190 return
191
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800192 action = action.strip()
193 match = re.search(r'(\".*\"),?(.*)', action)
194 if match is None:
195 self._bail("expected format string in \"s")
196
197 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800198 self._parse_types(self.raw_format)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800199 for part in match.group(2).split(','):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800200 part = self._replace_args(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800201 if len(part) > 0:
202 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800203
204 aliases = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530205 "retval": "PT_REGS_RC(ctx)",
206 "arg1": "PT_REGS_PARM1(ctx)",
207 "arg2": "PT_REGS_PARM2(ctx)",
208 "arg3": "PT_REGS_PARM3(ctx)",
209 "arg4": "PT_REGS_PARM4(ctx)",
210 "arg5": "PT_REGS_PARM5(ctx)",
211 "arg6": "PT_REGS_PARM6(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800212 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
213 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
214 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
215 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
216 "$cpu": "bpf_get_smp_processor_id()"
217 }
218
219 def _replace_args(self, expr):
220 for alias, replacement in Probe.aliases.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700221 # For USDT probes, we replace argN values with the
222 # actual arguments for that probe.
223 if alias.startswith("arg") and self.probe_type == "u":
224 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800225 expr = expr.replace(alias, replacement)
226 return expr
227
228 p_type = { "u": ct.c_uint, "d": ct.c_int,
229 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
230 "hu": ct.c_ushort, "hd": ct.c_short,
231 "x": ct.c_uint, "llx": ct.c_ulonglong,
232 "c": ct.c_ubyte }
233
234 def _generate_python_field_decl(self, idx, fields):
235 field_type = self.types[idx]
236 if field_type == "s":
237 ptype = ct.c_char * self.string_size
238 else:
239 ptype = Probe.p_type[field_type]
240 fields.append(("v%d" % idx, ptype))
241
242 def _generate_python_data_decl(self):
243 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700244 (self._display_function(), self.probe_num)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800245 fields = [
246 ("timestamp_ns", ct.c_ulonglong),
247 ("pid", ct.c_uint),
248 ("comm", ct.c_char * 16) # TASK_COMM_LEN
249 ]
250 for i in range(0, len(self.types)):
251 self._generate_python_field_decl(i, fields)
252 return type(self.python_struct_name, (ct.Structure,),
253 dict(_fields_=fields))
254
255 c_type = { "u": "unsigned int", "d": "int",
256 "llu": "unsigned long long", "lld": "long long",
257 "hu": "unsigned short", "hd": "short",
258 "x": "unsigned int", "llx": "unsigned long long",
259 "c": "char" }
260 fmt_types = c_type.keys()
261
262 def _generate_field_decl(self, idx):
263 field_type = self.types[idx]
264 if field_type == "s":
265 return "char v%d[%d];\n" % (idx, self.string_size)
266 if field_type in Probe.fmt_types:
267 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
268 self._bail("unrecognized format specifier %s" % field_type)
269
270 def _generate_data_decl(self):
271 # The BPF program will populate values into the struct
272 # according to the format string, and the Python program will
273 # construct the final display string.
274 self.events_name = "%s_events" % self.probe_name
275 self.struct_name = "%s_data_t" % self.probe_name
276
277 data_fields = ""
278 for i, field_type in enumerate(self.types):
279 data_fields += " " + \
280 self._generate_field_decl(i)
281
282 text = """
283struct %s
284{
285 u64 timestamp_ns;
286 u32 pid;
287 char comm[TASK_COMM_LEN];
288%s
289};
290
291BPF_PERF_OUTPUT(%s);
292"""
293 return text % (self.struct_name, data_fields, self.events_name)
294
295 def _generate_field_assign(self, idx):
296 field_type = self.types[idx]
297 expr = self.values[idx]
298 if field_type == "s":
299 return """
300 if (%s != 0) {
301 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), (void *)%s);
302 }
303""" % (expr, idx, idx, expr)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800304 if field_type in Probe.fmt_types:
305 return " __data.v%d = (%s)%s;\n" % \
306 (idx, Probe.c_type[field_type], expr)
307 self._bail("unrecognized field type %s" % field_type)
308
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700309 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800310 data_decl = self._generate_data_decl()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800311 # kprobes don't have built-in pid filters, so we have to add
312 # it to the function body:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700313 if len(self.library) == 0 and Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800314 pid_filter = """
315 u32 __pid = bpf_get_current_pid_tgid();
316 if (__pid != %d) { return 0; }
317""" % pid
318 elif not include_self:
319 pid_filter = """
320 u32 __pid = bpf_get_current_pid_tgid();
321 if (__pid == %d) { return 0; }
322""" % os.getpid()
323 else:
324 pid_filter = ""
325
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700326 prefix = ""
327 qualifier = ""
328 signature = "struct pt_regs *ctx"
329 if self.probe_type == "t":
330 data_decl += self.tp.generate_struct()
331 prefix = self.tp.generate_get_struct()
332 elif self.probe_type == "u":
333 signature += ", int __loc_id"
Sasha Goldshtein5a1d2e32016-03-30 08:14:44 -0700334 prefix = self.usdt.generate_usdt_cases(
335 pid=Probe.pid if Probe.pid != -1 else None)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700336 qualifier = "static inline"
337
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800338 data_fields = ""
339 for i, expr in enumerate(self.values):
340 data_fields += self._generate_field_assign(i)
341
342 text = """
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700343%s int %s(%s)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800344{
345 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800346 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800347 if (!(%s)) return 0;
348
349 struct %s __data = {0};
350 __data.timestamp_ns = bpf_ktime_get_ns();
351 __data.pid = bpf_get_current_pid_tgid();
352 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
353%s
354 %s.perf_submit(ctx, &__data, sizeof(__data));
355 return 0;
356}
357"""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700358 text = text % (qualifier, self.probe_name, signature,
359 pid_filter, prefix, self.filter,
360 self.struct_name, data_fields, self.events_name)
361
362 if self.probe_type == "u":
363 self.usdt_thunk_names = []
364 text += self.usdt.generate_usdt_thunks(
365 self.probe_name, self.usdt_thunk_names)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800366
367 return data_decl + "\n" + text
368
369 @classmethod
370 def _time_off_str(cls, timestamp_ns):
371 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
372
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800373 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700374 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800375 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700376 elif self.probe_type == 'u':
377 return self.usdt_name
378 else: # self.probe_type == 't'
379 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800380
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800381 def print_event(self, cpu, data, size):
382 # Cast as the generated structure type and display
383 # according to the format string in the probe.
384 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
385 values = map(lambda i: getattr(event, "v%d" % i),
386 range(0, len(self.values)))
387 msg = self.python_format % tuple(values)
388 time = strftime("%H:%M:%S") if Probe.use_localtime else \
389 Probe._time_off_str(event.timestamp_ns)
390 print("%-8s %-6d %-12s %-16s %s" % \
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800391 (time[:8], event.pid, event.comm[:12],
392 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800393
394 Probe.event_count += 1
395 if Probe.max_events is not None and \
396 Probe.event_count >= Probe.max_events:
397 exit()
398
399 def attach(self, bpf, verbose):
400 if len(self.library) == 0:
401 self._attach_k(bpf)
402 else:
403 self._attach_u(bpf)
404 self.python_struct = self._generate_python_data_decl()
405 bpf[self.events_name].open_perf_buffer(self.print_event)
406
407 def _attach_k(self, bpf):
408 if self.probe_type == "r":
409 bpf.attach_kretprobe(event=self.function,
410 fn_name=self.probe_name)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800411 elif self.probe_type == "p" or self.probe_type == "t":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800412 bpf.attach_kprobe(event=self.function,
413 fn_name=self.probe_name)
414
415 def _attach_u(self, bpf):
416 libpath = BPF.find_library(self.library)
417 if libpath is None:
418 # This might be an executable (e.g. 'bash')
Sasha Goldshtein435839a2016-03-30 13:25:09 -0700419 libpath = ProcUtils.which(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800420 if libpath is None or len(libpath) == 0:
421 self._bail("unable to find library %s" % self.library)
422
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700423 if self.probe_type == "u":
424 for i, location in enumerate(self.usdt.locations):
425 bpf.attach_uprobe(name=libpath,
426 addr=location.address,
427 fn_name=self.usdt_thunk_names[i],
428 pid=Probe.pid)
429 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):
514 self.bpf = BPF(text=self.program)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800515 Tracepoint.attach(self.bpf)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800516 for probe in self.probes:
517 if self.args.verbose:
518 print(probe)
519 probe.attach(self.bpf, self.args.verbose)
520
521 def _main_loop(self):
522 all_probes_trivial = all(map(Probe.is_default_action,
523 self.probes))
524
525 # Print header
526 print("%-8s %-6s %-12s %-16s %s" % \
527 ("TIME", "PID", "COMM", "FUNC",
528 "-" if not all_probes_trivial else ""))
529
530 while True:
531 self.bpf.kprobe_poll()
532
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700533 def _close_probes(self):
534 for probe in self.probes:
535 probe.close()
536 if self.args.verbose:
537 print("closed probe: " + str(probe))
538
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800539 def run(self):
540 try:
541 self._create_probes()
542 self._generate_program()
543 self._attach_probes()
544 self._main_loop()
545 except:
546 if self.args.verbose:
547 traceback.print_exc()
Brenden Blancode14f4f2016-04-08 15:52:55 -0700548 elif sys.exc_info()[0] is not SystemExit:
549 print(sys.exc_info()[1])
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700550 self._close_probes()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800551
552if __name__ == "__main__":
553 Tool().run()