blob: c5ec39c0e47c5dd68f933c9fa92da242d546cf34 [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 Goldshtein3e39a082016-03-24 08:39:47 -070012from bcc import BPF, Tracepoint, Perf, 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 = {
205 "retval": "ctx->ax",
206 "arg1": "ctx->di",
207 "arg2": "ctx->si",
208 "arg3": "ctx->dx",
209 "arg4": "ctx->cx",
210 "arg5": "ctx->r8",
211 "arg6": "ctx->r9",
212 "$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"
334 prefix = self.usdt.generate_usdt_cases()
335 qualifier = "static inline"
336
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800337 data_fields = ""
338 for i, expr in enumerate(self.values):
339 data_fields += self._generate_field_assign(i)
340
341 text = """
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700342%s int %s(%s)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800343{
344 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800345 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800346 if (!(%s)) return 0;
347
348 struct %s __data = {0};
349 __data.timestamp_ns = bpf_ktime_get_ns();
350 __data.pid = bpf_get_current_pid_tgid();
351 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
352%s
353 %s.perf_submit(ctx, &__data, sizeof(__data));
354 return 0;
355}
356"""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700357 text = text % (qualifier, self.probe_name, signature,
358 pid_filter, prefix, self.filter,
359 self.struct_name, data_fields, self.events_name)
360
361 if self.probe_type == "u":
362 self.usdt_thunk_names = []
363 text += self.usdt.generate_usdt_thunks(
364 self.probe_name, self.usdt_thunk_names)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800365
366 return data_decl + "\n" + text
367
368 @classmethod
369 def _time_off_str(cls, timestamp_ns):
370 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
371
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800372 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700373 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800374 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700375 elif self.probe_type == 'u':
376 return self.usdt_name
377 else: # self.probe_type == 't'
378 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800379
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800380 def print_event(self, cpu, data, size):
381 # Cast as the generated structure type and display
382 # according to the format string in the probe.
383 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
384 values = map(lambda i: getattr(event, "v%d" % i),
385 range(0, len(self.values)))
386 msg = self.python_format % tuple(values)
387 time = strftime("%H:%M:%S") if Probe.use_localtime else \
388 Probe._time_off_str(event.timestamp_ns)
389 print("%-8s %-6d %-12s %-16s %s" % \
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800390 (time[:8], event.pid, event.comm[:12],
391 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800392
393 Probe.event_count += 1
394 if Probe.max_events is not None and \
395 Probe.event_count >= Probe.max_events:
396 exit()
397
398 def attach(self, bpf, verbose):
399 if len(self.library) == 0:
400 self._attach_k(bpf)
401 else:
402 self._attach_u(bpf)
403 self.python_struct = self._generate_python_data_decl()
404 bpf[self.events_name].open_perf_buffer(self.print_event)
405
406 def _attach_k(self, bpf):
407 if self.probe_type == "r":
408 bpf.attach_kretprobe(event=self.function,
409 fn_name=self.probe_name)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800410 elif self.probe_type == "p" or self.probe_type == "t":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800411 bpf.attach_kprobe(event=self.function,
412 fn_name=self.probe_name)
413
414 def _attach_u(self, bpf):
415 libpath = BPF.find_library(self.library)
416 if libpath is None:
417 # This might be an executable (e.g. 'bash')
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700418 with os.popen(
419 "/usr/bin/which --skip-alias %s 2>/dev/null" %
420 self.library) as w:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800421 libpath = w.read().strip()
422 if libpath is None or len(libpath) == 0:
423 self._bail("unable to find library %s" % self.library)
424
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700425 if self.probe_type == "u":
426 for i, location in enumerate(self.usdt.locations):
427 bpf.attach_uprobe(name=libpath,
428 addr=location.address,
429 fn_name=self.usdt_thunk_names[i],
430 pid=Probe.pid)
431 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800432 bpf.attach_uretprobe(name=libpath,
433 sym=self.function,
434 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700435 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800436 else:
437 bpf.attach_uprobe(name=libpath,
438 sym=self.function,
439 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700440 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800441
442class Tool(object):
443 examples = """
444EXAMPLES:
445
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800446trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800447 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800448trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800449 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800450trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800451 Trace the read syscall and print a message for reads >20000 bytes
452trace 'r::do_sys_return "%llx", retval'
453 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800454trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800455 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800456trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800457 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800458trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
459 Trace the write() call from libc to monitor writes to STDOUT
460trace 'r::__kmalloc (retval == 0) "kmalloc failed!"
461 Trace returns from __kmalloc which returned a null pointer
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800462trace 'r:c:malloc (retval) "allocated = %p", retval
463 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800464trace 't:block:block_rq_complete "sectors=%d", tp.nr_sector'
465 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700466trace 'u:pthread:pthread_create (arg4 != 0)'
467 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800468"""
469
470 def __init__(self):
471 parser = argparse.ArgumentParser(description=
472 "Attach to functions and print trace messages.",
473 formatter_class=argparse.RawDescriptionHelpFormatter,
474 epilog=Tool.examples)
475 parser.add_argument("-p", "--pid", type=int,
476 help="id of the process to trace (optional)")
477 parser.add_argument("-v", "--verbose", action="store_true",
478 help="print resulting BPF program code before executing")
479 parser.add_argument("-Z", "--string-size", type=int,
480 default=80, help="maximum size to read from strings")
481 parser.add_argument("-S", "--include-self", action="store_true",
482 help="do not filter trace's own pid from the trace")
483 parser.add_argument("-M", "--max-events", type=int,
484 help="number of events to print before quitting")
485 parser.add_argument("-o", "--offset", action="store_true",
486 help="use relative time from first traced message")
487 parser.add_argument(metavar="probe", dest="probes", nargs="+",
488 help="probe specifier (see examples)")
489 self.args = parser.parse_args()
490
491 def _create_probes(self):
492 Probe.configure(self.args)
493 self.probes = []
494 for probe_spec in self.args.probes:
495 self.probes.append(Probe(
496 probe_spec, self.args.string_size))
497
498 def _generate_program(self):
499 self.program = """
500#include <linux/ptrace.h>
501#include <linux/sched.h> /* For TASK_COMM_LEN */
502
503"""
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700504 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800505 map(lambda p: p.raw_probe, self.probes))
506 self.program += Tracepoint.generate_decl()
507 self.program += Tracepoint.generate_entry_probe()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800508 for probe in self.probes:
509 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700510 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800511
512 if self.args.verbose:
513 print(self.program)
514
515 def _attach_probes(self):
516 self.bpf = BPF(text=self.program)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800517 Tracepoint.attach(self.bpf)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800518 for probe in self.probes:
519 if self.args.verbose:
520 print(probe)
521 probe.attach(self.bpf, self.args.verbose)
522
523 def _main_loop(self):
524 all_probes_trivial = all(map(Probe.is_default_action,
525 self.probes))
526
527 # Print header
528 print("%-8s %-6s %-12s %-16s %s" % \
529 ("TIME", "PID", "COMM", "FUNC",
530 "-" if not all_probes_trivial else ""))
531
532 while True:
533 self.bpf.kprobe_poll()
534
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700535 def _close_probes(self):
536 for probe in self.probes:
537 probe.close()
538 if self.args.verbose:
539 print("closed probe: " + str(probe))
540
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800541 def run(self):
542 try:
543 self._create_probes()
544 self._generate_program()
545 self._attach_probes()
546 self._main_loop()
547 except:
548 if self.args.verbose:
549 traceback.print_exc()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800550 elif sys.exc_type is not SystemExit:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800551 print(sys.exc_value)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700552 self._close_probes()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800553
554if __name__ == "__main__":
555 Tool().run()