blob: 0cb1c3e90c36dd071336842671589f99b4712c09 [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(
166 r'[^%]%(s|u|d|llu|lld|hu|hd|x|llx|c)', fmt):
167 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)
170 self.python_format = fmt.strip('"')
171
172 def _parse_action(self, action):
173 self.values = []
174 self.types = []
175 self.python_format = ""
176 if len(action) == 0:
177 return
178
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800179 action = action.strip()
180 match = re.search(r'(\".*\"),?(.*)', action)
181 if match is None:
182 self._bail("expected format string in \"s")
183
184 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800185 self._parse_types(self.raw_format)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800186 for part in match.group(2).split(','):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800187 part = self._replace_args(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800188 if len(part) > 0:
189 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800190
191 aliases = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530192 "retval": "PT_REGS_RC(ctx)",
193 "arg1": "PT_REGS_PARM1(ctx)",
194 "arg2": "PT_REGS_PARM2(ctx)",
195 "arg3": "PT_REGS_PARM3(ctx)",
196 "arg4": "PT_REGS_PARM4(ctx)",
197 "arg5": "PT_REGS_PARM5(ctx)",
198 "arg6": "PT_REGS_PARM6(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800199 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
200 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
201 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
202 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
203 "$cpu": "bpf_get_smp_processor_id()"
204 }
205
206 def _replace_args(self, expr):
207 for alias, replacement in Probe.aliases.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700208 # For USDT probes, we replace argN values with the
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300209 # actual arguments for that probe obtained using special
210 # bpf_readarg_N macros emitted at BPF construction.
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700211 if alias.startswith("arg") and self.probe_type == "u":
212 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800213 expr = expr.replace(alias, replacement)
214 return expr
215
216 p_type = { "u": ct.c_uint, "d": ct.c_int,
217 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
218 "hu": ct.c_ushort, "hd": ct.c_short,
219 "x": ct.c_uint, "llx": ct.c_ulonglong,
220 "c": ct.c_ubyte }
221
222 def _generate_python_field_decl(self, idx, fields):
223 field_type = self.types[idx]
224 if field_type == "s":
225 ptype = ct.c_char * self.string_size
226 else:
227 ptype = Probe.p_type[field_type]
228 fields.append(("v%d" % idx, ptype))
229
230 def _generate_python_data_decl(self):
231 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700232 (self._display_function(), self.probe_num)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800233 fields = [
234 ("timestamp_ns", ct.c_ulonglong),
235 ("pid", ct.c_uint),
236 ("comm", ct.c_char * 16) # TASK_COMM_LEN
237 ]
238 for i in range(0, len(self.types)):
239 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700240 if self.kernel_stack:
241 fields.append(("kernel_stack_id", ct.c_int))
242 if self.user_stack:
243 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800244 return type(self.python_struct_name, (ct.Structure,),
245 dict(_fields_=fields))
246
247 c_type = { "u": "unsigned int", "d": "int",
248 "llu": "unsigned long long", "lld": "long long",
249 "hu": "unsigned short", "hd": "short",
250 "x": "unsigned int", "llx": "unsigned long long",
251 "c": "char" }
252 fmt_types = c_type.keys()
253
254 def _generate_field_decl(self, idx):
255 field_type = self.types[idx]
256 if field_type == "s":
257 return "char v%d[%d];\n" % (idx, self.string_size)
258 if field_type in Probe.fmt_types:
259 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
260 self._bail("unrecognized format specifier %s" % field_type)
261
262 def _generate_data_decl(self):
263 # The BPF program will populate values into the struct
264 # according to the format string, and the Python program will
265 # construct the final display string.
266 self.events_name = "%s_events" % self.probe_name
267 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700268 self.stacks_name = "%s_stacks" % self.probe_name
269 stack_table = "BPF_STACK_TRACE(%s, 1024);" % self.stacks_name \
270 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800271 data_fields = ""
272 for i, field_type in enumerate(self.types):
273 data_fields += " " + \
274 self._generate_field_decl(i)
275
Teng Qin6b0ed372016-09-29 21:30:13 -0700276 kernel_stack_str = " int kernel_stack_id;" \
277 if self.kernel_stack else ""
278 user_stack_str = " int user_stack_id;" \
279 if self.user_stack else ""
280
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800281 text = """
282struct %s
283{
284 u64 timestamp_ns;
285 u32 pid;
286 char comm[TASK_COMM_LEN];
287%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700288%s
289%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800290};
291
292BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700293%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800294"""
Teng Qin6b0ed372016-09-29 21:30:13 -0700295 return text % (self.struct_name, data_fields,
296 kernel_stack_str, user_stack_str,
297 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800298
299 def _generate_field_assign(self, idx):
300 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300301 expr = self.values[idx].strip()
302 text = ""
303 if self.probe_type == "u" and expr[0:3] == "arg":
304 text = (" u64 %s;\n" +
305 " bpf_usdt_readarg(%s, ctx, &%s);\n") % \
306 (expr, expr[3], expr)
307
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800308 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300309 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800310 if (%s != 0) {
311 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), (void *)%s);
312 }
313""" % (expr, idx, idx, expr)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800314 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300315 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800316 (idx, Probe.c_type[field_type], expr)
317 self._bail("unrecognized field type %s" % field_type)
318
Teng Qin0615bff2016-09-28 08:19:40 -0700319 def _generate_usdt_filter_read(self):
320 text = ""
321 if self.probe_type == "u":
322 for arg, _ in Probe.aliases.items():
323 if not (arg.startswith("arg") and (arg in self.filter)):
324 continue
325 arg_index = int(arg.replace("arg", ""))
326 arg_ctype = self.usdt.get_probe_arg_ctype(
327 self.usdt_name, arg_index)
328 if not arg_ctype:
329 self._bail("Unable to determine type of {} "
330 "in the filter".format(arg))
331 text += """
332 {} {}_filter;
333 bpf_usdt_readarg({}, ctx, &{}_filter);
334 """.format(arg_ctype, arg, arg_index, arg)
335 self.filter = self.filter.replace(
336 arg, "{}_filter".format(arg))
337 return text
338
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700339 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800340 data_decl = self._generate_data_decl()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800341 # kprobes don't have built-in pid filters, so we have to add
342 # it to the function body:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700343 if len(self.library) == 0 and Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800344 pid_filter = """
345 u32 __pid = bpf_get_current_pid_tgid();
346 if (__pid != %d) { return 0; }
Sasha Goldshteinde34c252016-06-30 12:16:39 +0300347""" % Probe.pid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800348 elif not include_self:
349 pid_filter = """
350 u32 __pid = bpf_get_current_pid_tgid();
351 if (__pid == %d) { return 0; }
352""" % os.getpid()
353 else:
354 pid_filter = ""
355
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700356 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700357 signature = "struct pt_regs *ctx"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700358
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800359 data_fields = ""
360 for i, expr in enumerate(self.values):
361 data_fields += self._generate_field_assign(i)
362
Teng Qin6b0ed372016-09-29 21:30:13 -0700363 stack_trace = ""
364 if self.user_stack:
365 stack_trace += """
366 __data.user_stack_id = %s.get_stackid(
367 ctx, BPF_F_REUSE_STACKID | BPF_F_USER_STACK
368 );""" % self.stacks_name
369 if self.kernel_stack:
370 stack_trace += """
371 __data.kernel_stack_id = %s.get_stackid(
372 ctx, BPF_F_REUSE_STACKID
373 );""" % self.stacks_name
374
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300375 if self.probe_type == "t":
376 heading = "TRACEPOINT_PROBE(%s, %s)" % \
377 (self.tp_category, self.tp_event)
378 ctx_name = "args"
379 else:
380 heading = "int %s(%s)" % (self.probe_name, signature)
381 ctx_name = "ctx"
382 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800383{
384 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800385 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700386 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800387 if (!(%s)) return 0;
388
389 struct %s __data = {0};
390 __data.timestamp_ns = bpf_ktime_get_ns();
391 __data.pid = bpf_get_current_pid_tgid();
392 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
393%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700394%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300395 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800396 return 0;
397}
398"""
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300399 text = text % (pid_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700400 self._generate_usdt_filter_read(), self.filter,
Teng Qin6b0ed372016-09-29 21:30:13 -0700401 self.struct_name, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300402 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700403
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800404 return data_decl + "\n" + text
405
406 @classmethod
407 def _time_off_str(cls, timestamp_ns):
408 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
409
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800410 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700411 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800412 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700413 elif self.probe_type == 'u':
414 return self.usdt_name
415 else: # self.probe_type == 't'
416 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800417
Teng Qin6b0ed372016-09-29 21:30:13 -0700418 def print_stack(self, bpf, stack_id, pid):
419 if stack_id < 0:
420 print(" %d" % stack_id)
421 return
422
423 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
424 for addr in stack:
425 print(" %016x %s" % (addr, bpf.sym(addr, pid)))
426
427 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800428 # Cast as the generated structure type and display
429 # according to the format string in the probe.
430 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
431 values = map(lambda i: getattr(event, "v%d" % i),
432 range(0, len(self.values)))
433 msg = self.python_format % tuple(values)
434 time = strftime("%H:%M:%S") if Probe.use_localtime else \
435 Probe._time_off_str(event.timestamp_ns)
436 print("%-8s %-6d %-12s %-16s %s" % \
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800437 (time[:8], event.pid, event.comm[:12],
438 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800439
Teng Qin6b0ed372016-09-29 21:30:13 -0700440 if self.user_stack:
441 print(" User Stack Trace:")
442 self.print_stack(bpf, event.user_stack_id, event.pid)
443 if self.kernel_stack:
444 print(" Kernel Stack Trace:")
445 self.print_stack(bpf, event.kernel_stack_id, -1)
446 if self.user_stack or self.kernel_stack:
447 print("")
448
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800449 Probe.event_count += 1
450 if Probe.max_events is not None and \
451 Probe.event_count >= Probe.max_events:
452 exit()
453
454 def attach(self, bpf, verbose):
455 if len(self.library) == 0:
456 self._attach_k(bpf)
457 else:
458 self._attach_u(bpf)
459 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700460 callback = partial(self.print_event, bpf)
461 bpf[self.events_name].open_perf_buffer(callback)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800462
463 def _attach_k(self, bpf):
464 if self.probe_type == "r":
465 bpf.attach_kretprobe(event=self.function,
466 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300467 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800468 bpf.attach_kprobe(event=self.function,
469 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300470 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800471
472 def _attach_u(self, bpf):
473 libpath = BPF.find_library(self.library)
474 if libpath is None:
475 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300476 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800477 if libpath is None or len(libpath) == 0:
478 self._bail("unable to find library %s" % self.library)
479
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700480 if self.probe_type == "u":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300481 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700482 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800483 bpf.attach_uretprobe(name=libpath,
484 sym=self.function,
485 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700486 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800487 else:
488 bpf.attach_uprobe(name=libpath,
489 sym=self.function,
490 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700491 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800492
493class Tool(object):
494 examples = """
495EXAMPLES:
496
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800497trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800498 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800499trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800500 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800501trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800502 Trace the read syscall and print a message for reads >20000 bytes
503trace 'r::do_sys_return "%llx", retval'
504 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800505trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800506 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800507trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800508 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800509trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
510 Trace the write() call from libc to monitor writes to STDOUT
511trace 'r::__kmalloc (retval == 0) "kmalloc failed!"
512 Trace returns from __kmalloc which returned a null pointer
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800513trace 'r:c:malloc (retval) "allocated = %p", retval
514 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300515trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800516 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700517trace 'u:pthread:pthread_create (arg4 != 0)'
518 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800519"""
520
521 def __init__(self):
522 parser = argparse.ArgumentParser(description=
523 "Attach to functions and print trace messages.",
524 formatter_class=argparse.RawDescriptionHelpFormatter,
525 epilog=Tool.examples)
526 parser.add_argument("-p", "--pid", type=int,
527 help="id of the process to trace (optional)")
528 parser.add_argument("-v", "--verbose", action="store_true",
529 help="print resulting BPF program code before executing")
530 parser.add_argument("-Z", "--string-size", type=int,
531 default=80, help="maximum size to read from strings")
532 parser.add_argument("-S", "--include-self", action="store_true",
533 help="do not filter trace's own pid from the trace")
534 parser.add_argument("-M", "--max-events", type=int,
535 help="number of events to print before quitting")
536 parser.add_argument("-o", "--offset", action="store_true",
537 help="use relative time from first traced message")
Teng Qin6b0ed372016-09-29 21:30:13 -0700538 parser.add_argument("-K", "--kernel-stack", action="store_true",
539 help="output kernel stack trace")
540 parser.add_argument("-U", "--user_stack", action="store_true",
541 help="output user stack trace")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800542 parser.add_argument(metavar="probe", dest="probes", nargs="+",
543 help="probe specifier (see examples)")
544 self.args = parser.parse_args()
545
546 def _create_probes(self):
547 Probe.configure(self.args)
548 self.probes = []
549 for probe_spec in self.args.probes:
550 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700551 probe_spec, self.args.string_size,
552 self.args.kernel_stack, self.args.user_stack))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800553
554 def _generate_program(self):
555 self.program = """
556#include <linux/ptrace.h>
557#include <linux/sched.h> /* For TASK_COMM_LEN */
558
559"""
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700560 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800561 map(lambda p: p.raw_probe, self.probes))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800562 for probe in self.probes:
563 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700564 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800565
566 if self.args.verbose:
567 print(self.program)
568
569 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300570 usdt_contexts = []
571 for probe in self.probes:
572 if probe.usdt:
573 # USDT probes must be enabled before the BPF object
574 # is initialized, because that's where the actual
575 # uprobe is being attached.
576 probe.usdt.enable_probe(
577 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300578 if self.args.verbose:
579 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300580 usdt_contexts.append(probe.usdt)
581 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800582 for probe in self.probes:
583 if self.args.verbose:
584 print(probe)
585 probe.attach(self.bpf, self.args.verbose)
586
587 def _main_loop(self):
588 all_probes_trivial = all(map(Probe.is_default_action,
589 self.probes))
590
591 # Print header
592 print("%-8s %-6s %-12s %-16s %s" % \
593 ("TIME", "PID", "COMM", "FUNC",
594 "-" if not all_probes_trivial else ""))
595
596 while True:
597 self.bpf.kprobe_poll()
598
599 def run(self):
600 try:
601 self._create_probes()
602 self._generate_program()
603 self._attach_probes()
604 self._main_loop()
605 except:
606 if self.args.verbose:
607 traceback.print_exc()
Brenden Blancode14f4f2016-04-08 15:52:55 -0700608 elif sys.exc_info()[0] is not SystemExit:
609 print(sys.exc_info()[1])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800610
611if __name__ == "__main__":
612 Tool().run()