blob: 0466b47bfa6e7e0886e312db1de3a8dcbb59eb1b [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#
Mark Draytonaa6c9162016-11-03 15:36:29 +00006# usage: trace [-h] [-p PID] [-t TID] [-v] [-Z STRING_SIZE] [-S]
7# [-M MAX_EVENTS] [-o] [-K] [-U] [-I header]
8# probe [probe ...]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -08009#
Sasha Goldshtein38847f02016-02-22 02:19:24 -080010# Licensed under the Apache License, Version 2.0 (the "License")
11# Copyright (C) 2016 Sasha Goldshtein.
12
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +030013from bcc import BPF, USDT
Teng Qin6b0ed372016-09-29 21:30:13 -070014from functools import partial
Sasha Goldshtein38847f02016-02-22 02:19:24 -080015from time import sleep, strftime
16import argparse
17import re
18import ctypes as ct
19import os
20import traceback
21import sys
22
23class Time(object):
24 # BPF timestamps come from the monotonic clock. To be able to filter
25 # and compare them from Python, we need to invoke clock_gettime.
26 # Adapted from http://stackoverflow.com/a/1205762
27 CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h>
28
29 class timespec(ct.Structure):
30 _fields_ = [
31 ('tv_sec', ct.c_long),
32 ('tv_nsec', ct.c_long)
33 ]
34
35 librt = ct.CDLL('librt.so.1', use_errno=True)
36 clock_gettime = librt.clock_gettime
37 clock_gettime.argtypes = [ct.c_int, ct.POINTER(timespec)]
38
39 @staticmethod
40 def monotonic_time():
41 t = Time.timespec()
42 if Time.clock_gettime(
43 Time.CLOCK_MONOTONIC_RAW, ct.pointer(t)) != 0:
44 errno_ = ct.get_errno()
45 raise OSError(errno_, os.strerror(errno_))
46 return t.tv_sec * 1e9 + t.tv_nsec
47
48class Probe(object):
49 probe_count = 0
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070050 streq_index = 0
Sasha Goldshtein38847f02016-02-22 02:19:24 -080051 max_events = None
52 event_count = 0
53 first_ts = 0
54 use_localtime = True
Mark Draytonaa6c9162016-11-03 15:36:29 +000055 tgid = -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070056 pid = -1
Sasha Goldshtein38847f02016-02-22 02:19:24 -080057
58 @classmethod
59 def configure(cls, args):
60 cls.max_events = args.max_events
61 cls.use_localtime = not args.offset
62 cls.first_ts = Time.monotonic_time()
Mark Draytonaa6c9162016-11-03 15:36:29 +000063 cls.tgid = args.tgid or -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070064 cls.pid = args.pid or -1
Sasha Goldshtein38847f02016-02-22 02:19:24 -080065
Teng Qin6b0ed372016-09-29 21:30:13 -070066 def __init__(self, probe, string_size, kernel_stack, user_stack):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +030067 self.usdt = None
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070068 self.streq_functions = ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -080069 self.raw_probe = probe
70 self.string_size = string_size
Teng Qin6b0ed372016-09-29 21:30:13 -070071 self.kernel_stack = kernel_stack
72 self.user_stack = user_stack
Sasha Goldshtein38847f02016-02-22 02:19:24 -080073 Probe.probe_count += 1
74 self._parse_probe()
75 self.probe_num = Probe.probe_count
76 self.probe_name = "probe_%s_%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070077 (self._display_function(), self.probe_num)
Sasha Goldshtein38847f02016-02-22 02:19:24 -080078
79 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070080 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
81 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080082 self.types, self.values)
83
84 def is_default_action(self):
85 return self.python_format == ""
86
87 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070088 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080089 (self.raw_probe, error))
90
91 def _parse_probe(self):
92 text = self.raw_probe
93
94 # Everything until the first space is the probe specifier
95 first_space = text.find(' ')
96 spec = text[:first_space] if first_space >= 0 else text
97 self._parse_spec(spec)
98 if first_space >= 0:
99 text = text[first_space:].lstrip()
100 else:
101 text = ""
102
103 # If we now have a (, wait for the balanced closing ) and that
104 # will be the predicate
105 self.filter = None
106 if len(text) > 0 and text[0] == "(":
107 balance = 1
108 for i in range(1, len(text)):
109 if text[i] == "(":
110 balance += 1
111 if text[i] == ")":
112 balance -= 1
113 if balance == 0:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300114 self._parse_filter(text[:i + 1])
115 text = text[i + 1:]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800116 break
117 if self.filter is None:
118 self._bail("unmatched end of predicate")
119
120 if self.filter is None:
121 self.filter = "1"
122
123 # The remainder of the text is the printf action
124 self._parse_action(text.lstrip())
125
126 def _parse_spec(self, spec):
127 parts = spec.split(":")
128 # Two special cases: 'func' means 'p::func', 'lib:func' means
129 # 'p:lib:func'. Other combinations need to provide an empty
130 # value between delimiters, e.g. 'r::func' for a kretprobe on
131 # the function func.
132 if len(parts) == 1:
133 parts = ["p", "", parts[0]]
134 elif len(parts) == 2:
135 parts = ["p", parts[0], parts[1]]
136 if len(parts[0]) == 0:
137 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700138 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800139 self.probe_type = parts[0]
140 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700141 self._bail("probe type must be '', 'p', 't', 'r', " +
142 "or 'u', but got '%s'" % parts[0])
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800143 if self.probe_type == "t":
144 self.tp_category = parts[1]
145 self.tp_event = parts[2]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800146 self.library = "" # kernel
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300147 self.function = "" # from TRACEPOINT_PROBE
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700148 elif self.probe_type == "u":
149 self.library = parts[1]
150 self.usdt_name = parts[2]
151 self.function = "" # no function, just address
152 # We will discover the USDT provider by matching on
153 # the USDT name in the specified library
154 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800155 else:
156 self.library = parts[1]
157 self.function = parts[2]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800158
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700159 def _find_usdt_probe(self):
Mark Draytonaa6c9162016-11-03 15:36:29 +0000160 target = Probe.pid if Probe.pid else Probe.tgid
161 self.usdt = USDT(path=self.library, pid=target)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300162 for probe in self.usdt.enumerate_probes():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700163 if probe.name == self.usdt_name:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300164 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700165 self._bail("unrecognized USDT probe %s" % self.usdt_name)
166
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800167 def _parse_filter(self, filt):
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700168 self.filter = self._rewrite_expr(filt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800169
170 def _parse_types(self, fmt):
171 for match in re.finditer(
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300172 r'[^%]%(s|u|d|llu|lld|hu|hd|x|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800173 self.types.append(match.group(1))
174 fmt = re.sub(r'([^%]%)(u|d|llu|lld|hu|hd)', r'\1d', fmt)
175 fmt = re.sub(r'([^%]%)(x|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700176 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800177 self.python_format = fmt.strip('"')
178
179 def _parse_action(self, action):
180 self.values = []
181 self.types = []
182 self.python_format = ""
183 if len(action) == 0:
184 return
185
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800186 action = action.strip()
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700187 match = re.search(r'(\".*?\"),?(.*)', action)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800188 if match is None:
189 self._bail("expected format string in \"s")
190
191 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800192 self._parse_types(self.raw_format)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700193 for part in re.split('(?<!"),', match.group(2)):
194 part = self._rewrite_expr(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800195 if len(part) > 0:
196 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800197
198 aliases = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530199 "retval": "PT_REGS_RC(ctx)",
200 "arg1": "PT_REGS_PARM1(ctx)",
201 "arg2": "PT_REGS_PARM2(ctx)",
202 "arg3": "PT_REGS_PARM3(ctx)",
203 "arg4": "PT_REGS_PARM4(ctx)",
204 "arg5": "PT_REGS_PARM5(ctx)",
205 "arg6": "PT_REGS_PARM6(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800206 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
207 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
208 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
209 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
210 "$cpu": "bpf_get_smp_processor_id()"
211 }
212
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700213 def _generate_streq_function(self, string):
214 fname = "streq_%d" % Probe.streq_index
215 Probe.streq_index += 1
216 self.streq_functions += """
217static inline bool %s(char const *ignored, unsigned long str) {
218 char needle[] = %s;
219 char haystack[sizeof(needle)];
220 bpf_probe_read(&haystack, sizeof(haystack), (void *)str);
221 for (int i = 0; i < sizeof(needle); ++i) {
222 if (needle[i] != haystack[i]) {
223 return false;
224 }
225 }
226 return true;
227}
228 """ % (fname, string)
229 return fname
230
231 def _rewrite_expr(self, expr):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800232 for alias, replacement in Probe.aliases.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700233 # For USDT probes, we replace argN values with the
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300234 # actual arguments for that probe obtained using
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300235 # bpf_readarg_N macros emitted at BPF construction.
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700236 if alias.startswith("arg") and self.probe_type == "u":
237 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800238 expr = expr.replace(alias, replacement)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700239 matches = re.finditer('STRCMP\\(("[^"]+\\")', expr)
240 for match in matches:
241 string = match.group(1)
242 fname = self._generate_streq_function(string)
243 expr = expr.replace("STRCMP", fname, 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800244 return expr
245
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300246 p_type = {"u": ct.c_uint, "d": ct.c_int,
247 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
248 "hu": ct.c_ushort, "hd": ct.c_short,
249 "x": ct.c_uint, "llx": ct.c_ulonglong, "c": ct.c_ubyte,
250 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800251
252 def _generate_python_field_decl(self, idx, fields):
253 field_type = self.types[idx]
254 if field_type == "s":
255 ptype = ct.c_char * self.string_size
256 else:
257 ptype = Probe.p_type[field_type]
258 fields.append(("v%d" % idx, ptype))
259
260 def _generate_python_data_decl(self):
261 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700262 (self._display_function(), self.probe_num)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800263 fields = [
264 ("timestamp_ns", ct.c_ulonglong),
Mark Draytonaa6c9162016-11-03 15:36:29 +0000265 ("tgid", ct.c_uint),
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800266 ("pid", ct.c_uint),
267 ("comm", ct.c_char * 16) # TASK_COMM_LEN
268 ]
269 for i in range(0, len(self.types)):
270 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700271 if self.kernel_stack:
272 fields.append(("kernel_stack_id", ct.c_int))
273 if self.user_stack:
274 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800275 return type(self.python_struct_name, (ct.Structure,),
276 dict(_fields_=fields))
277
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300278 c_type = {"u": "unsigned int", "d": "int",
279 "llu": "unsigned long long", "lld": "long long",
280 "hu": "unsigned short", "hd": "short",
281 "x": "unsigned int", "llx": "unsigned long long",
282 "c": "char", "K": "unsigned long long",
283 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800284 fmt_types = c_type.keys()
285
286 def _generate_field_decl(self, idx):
287 field_type = self.types[idx]
288 if field_type == "s":
289 return "char v%d[%d];\n" % (idx, self.string_size)
290 if field_type in Probe.fmt_types:
291 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
292 self._bail("unrecognized format specifier %s" % field_type)
293
294 def _generate_data_decl(self):
295 # The BPF program will populate values into the struct
296 # according to the format string, and the Python program will
297 # construct the final display string.
298 self.events_name = "%s_events" % self.probe_name
299 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700300 self.stacks_name = "%s_stacks" % self.probe_name
301 stack_table = "BPF_STACK_TRACE(%s, 1024);" % self.stacks_name \
302 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800303 data_fields = ""
304 for i, field_type in enumerate(self.types):
305 data_fields += " " + \
306 self._generate_field_decl(i)
307
Teng Qin6b0ed372016-09-29 21:30:13 -0700308 kernel_stack_str = " int kernel_stack_id;" \
309 if self.kernel_stack else ""
310 user_stack_str = " int user_stack_id;" \
311 if self.user_stack else ""
312
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800313 text = """
314struct %s
315{
316 u64 timestamp_ns;
Mark Draytonaa6c9162016-11-03 15:36:29 +0000317 u32 tgid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800318 u32 pid;
319 char comm[TASK_COMM_LEN];
320%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700321%s
322%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800323};
324
325BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700326%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800327"""
Teng Qin6b0ed372016-09-29 21:30:13 -0700328 return text % (self.struct_name, data_fields,
329 kernel_stack_str, user_stack_str,
330 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800331
332 def _generate_field_assign(self, idx):
333 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300334 expr = self.values[idx].strip()
335 text = ""
336 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshteinb6db17f2016-10-04 19:50:50 +0300337 text = (" u64 %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300338 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
339 % (expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300340
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800341 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300342 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800343 if (%s != 0) {
344 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), (void *)%s);
345 }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300346 """ % (expr, idx, idx, expr)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800347 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300348 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800349 (idx, Probe.c_type[field_type], expr)
350 self._bail("unrecognized field type %s" % field_type)
351
Teng Qin0615bff2016-09-28 08:19:40 -0700352 def _generate_usdt_filter_read(self):
353 text = ""
354 if self.probe_type == "u":
355 for arg, _ in Probe.aliases.items():
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300356 if not (arg.startswith("arg") and
357 (arg in self.filter)):
Teng Qin0615bff2016-09-28 08:19:40 -0700358 continue
359 arg_index = int(arg.replace("arg", ""))
360 arg_ctype = self.usdt.get_probe_arg_ctype(
361 self.usdt_name, arg_index)
362 if not arg_ctype:
363 self._bail("Unable to determine type of {} "
364 "in the filter".format(arg))
365 text += """
366 {} {}_filter;
367 bpf_usdt_readarg({}, ctx, &{}_filter);
368 """.format(arg_ctype, arg, arg_index, arg)
369 self.filter = self.filter.replace(
370 arg, "{}_filter".format(arg))
371 return text
372
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700373 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800374 data_decl = self._generate_data_decl()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800375 # kprobes don't have built-in pid filters, so we have to add
376 # it to the function body:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700377 if len(self.library) == 0 and Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800378 pid_filter = """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800379 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300380 """ % Probe.pid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000381 elif len(self.library) == 0 and Probe.tgid != -1:
382 pid_filter = """
383 if (__tgid != %d) { return 0; }
384 """ % Probe.tgid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800385 elif not include_self:
386 pid_filter = """
Mark Draytonaa6c9162016-11-03 15:36:29 +0000387 if (__tgid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300388 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800389 else:
390 pid_filter = ""
391
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700392 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700393 signature = "struct pt_regs *ctx"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700394
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800395 data_fields = ""
396 for i, expr in enumerate(self.values):
397 data_fields += self._generate_field_assign(i)
398
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300399 if self.probe_type == "t":
400 heading = "TRACEPOINT_PROBE(%s, %s)" % \
401 (self.tp_category, self.tp_event)
402 ctx_name = "args"
403 else:
404 heading = "int %s(%s)" % (self.probe_name, signature)
405 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300406
407 stack_trace = ""
408 if self.user_stack:
409 stack_trace += """
410 __data.user_stack_id = %s.get_stackid(
411 %s, BPF_F_REUSE_STACKID | BPF_F_USER_STACK
412 );""" % (self.stacks_name, ctx_name)
413 if self.kernel_stack:
414 stack_trace += """
415 __data.kernel_stack_id = %s.get_stackid(
416 %s, BPF_F_REUSE_STACKID
417 );""" % (self.stacks_name, ctx_name)
418
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300419 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800420{
Mark Draytonaa6c9162016-11-03 15:36:29 +0000421 u64 __pid_tgid = bpf_get_current_pid_tgid();
422 u32 __tgid = __pid_tgid >> 32;
423 u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800424 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800425 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700426 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800427 if (!(%s)) return 0;
428
429 struct %s __data = {0};
430 __data.timestamp_ns = bpf_ktime_get_ns();
Mark Draytonaa6c9162016-11-03 15:36:29 +0000431 __data.tgid = __tgid;
432 __data.pid = __pid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800433 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
434%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700435%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300436 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800437 return 0;
438}
439"""
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300440 text = text % (pid_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700441 self._generate_usdt_filter_read(), self.filter,
Teng Qin6b0ed372016-09-29 21:30:13 -0700442 self.struct_name, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300443 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700444
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700445 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800446
447 @classmethod
448 def _time_off_str(cls, timestamp_ns):
449 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
450
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800451 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700452 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800453 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700454 elif self.probe_type == 'u':
455 return self.usdt_name
456 else: # self.probe_type == 't'
457 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800458
Mark Draytonaa6c9162016-11-03 15:36:29 +0000459 def print_stack(self, bpf, stack_id, tgid):
Teng Qin6b0ed372016-09-29 21:30:13 -0700460 if stack_id < 0:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700461 print(" %d" % stack_id)
462 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700463
464 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
465 for addr in stack:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000466 print(" %016x %s" % (addr, bpf.sym(addr, tgid)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700467
Mark Draytonaa6c9162016-11-03 15:36:29 +0000468 def _format_message(self, bpf, tgid, values):
469 # Replace each %K with kernel sym and %U with user sym in tgid
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700470 kernel_placeholders = [i for i in xrange(0, len(self.types))
471 if self.types[i] == 'K']
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300472 user_placeholders = [i for i in xrange(0, len(self.types))
473 if self.types[i] == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700474 for kp in kernel_placeholders:
475 values[kp] = bpf.ksymaddr(values[kp])
476 for up in user_placeholders:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000477 values[up] = bpf.symaddr(values[up], tgid)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700478 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700479
480 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800481 # Cast as the generated structure type and display
482 # according to the format string in the probe.
483 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
484 values = map(lambda i: getattr(event, "v%d" % i),
485 range(0, len(self.values)))
Mark Draytonaa6c9162016-11-03 15:36:29 +0000486 msg = self._format_message(bpf, event.tgid, values)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800487 time = strftime("%H:%M:%S") if Probe.use_localtime else \
488 Probe._time_off_str(event.timestamp_ns)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000489 print("%-8s %-6d %-6d %-12s %-16s %s" %
490 (time[:8], event.tgid, event.pid, event.comm,
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800491 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800492
Teng Qin6b0ed372016-09-29 21:30:13 -0700493 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700494 self.print_stack(bpf, event.kernel_stack_id, -1)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000495 if self.user_stack:
496 self.print_stack(bpf, event.user_stack_id, event.tgid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700497 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700498 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700499
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800500 Probe.event_count += 1
501 if Probe.max_events is not None and \
502 Probe.event_count >= Probe.max_events:
503 exit()
504
505 def attach(self, bpf, verbose):
506 if len(self.library) == 0:
507 self._attach_k(bpf)
508 else:
509 self._attach_u(bpf)
510 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700511 callback = partial(self.print_event, bpf)
512 bpf[self.events_name].open_perf_buffer(callback)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800513
514 def _attach_k(self, bpf):
515 if self.probe_type == "r":
516 bpf.attach_kretprobe(event=self.function,
517 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300518 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800519 bpf.attach_kprobe(event=self.function,
520 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300521 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800522
523 def _attach_u(self, bpf):
524 libpath = BPF.find_library(self.library)
525 if libpath is None:
526 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300527 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800528 if libpath is None or len(libpath) == 0:
529 self._bail("unable to find library %s" % self.library)
530
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700531 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300532 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700533 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800534 bpf.attach_uretprobe(name=libpath,
535 sym=self.function,
536 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700537 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800538 else:
539 bpf.attach_uprobe(name=libpath,
540 sym=self.function,
541 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700542 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800543
544class Tool(object):
545 examples = """
546EXAMPLES:
547
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800548trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800549 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800550trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800551 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800552trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800553 Trace the read syscall and print a message for reads >20000 bytes
554trace 'r::do_sys_return "%llx", retval'
555 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800556trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800557 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800558trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800559 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800560trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
561 Trace the write() call from libc to monitor writes to STDOUT
Mark Draytonaa6c9162016-11-03 15:36:29 +0000562trace 'r::__kmalloc (retval == 0) "kmalloc failed!"'
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800563 Trace returns from __kmalloc which returned a null pointer
Mark Draytonaa6c9162016-11-03 15:36:29 +0000564trace 'r:c:malloc (retval) "allocated = %x", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800565 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300566trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800567 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700568trace 'u:pthread:pthread_create (arg4 != 0)'
569 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800570"""
571
572 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300573 parser = argparse.ArgumentParser(description="Attach to " +
574 "functions and print trace messages.",
575 formatter_class=argparse.RawDescriptionHelpFormatter,
576 epilog=Tool.examples)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000577 # we'll refer to the userspace concepts of "pid" and "tid" by
578 # their kernel names -- tgid and pid -- inside the script
579 parser.add_argument("-p", "--pid", type=int, metavar="PID",
580 dest="tgid", help="id of the process to trace (optional)")
581 parser.add_argument("-t", "--tid", type=int, metavar="TID",
582 dest="pid", help="id of the thread to trace (optional)")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800583 parser.add_argument("-v", "--verbose", action="store_true",
584 help="print resulting BPF program code before executing")
585 parser.add_argument("-Z", "--string-size", type=int,
586 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300587 parser.add_argument("-S", "--include-self",
588 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800589 help="do not filter trace's own pid from the trace")
590 parser.add_argument("-M", "--max-events", type=int,
591 help="number of events to print before quitting")
592 parser.add_argument("-o", "--offset", action="store_true",
593 help="use relative time from first traced message")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300594 parser.add_argument("-K", "--kernel-stack",
595 action="store_true", help="output kernel stack trace")
596 parser.add_argument("-U", "--user-stack",
597 action="store_true", help="output user stack trace")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800598 parser.add_argument(metavar="probe", dest="probes", nargs="+",
599 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300600 parser.add_argument("-I", "--include", action="append",
601 metavar="header",
602 help="additional header files to include in the BPF program")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800603 self.args = parser.parse_args()
Mark Draytonaa6c9162016-11-03 15:36:29 +0000604 if self.args.tgid and self.args.pid:
605 parser.error("only one of -p and -t may be specified")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800606
607 def _create_probes(self):
608 Probe.configure(self.args)
609 self.probes = []
610 for probe_spec in self.args.probes:
611 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700612 probe_spec, self.args.string_size,
613 self.args.kernel_stack, self.args.user_stack))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800614
615 def _generate_program(self):
616 self.program = """
617#include <linux/ptrace.h>
618#include <linux/sched.h> /* For TASK_COMM_LEN */
619
620"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300621 for include in (self.args.include or []):
622 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700623 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800624 map(lambda p: p.raw_probe, self.probes))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800625 for probe in self.probes:
626 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700627 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800628
629 if self.args.verbose:
630 print(self.program)
631
632 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300633 usdt_contexts = []
634 for probe in self.probes:
635 if probe.usdt:
636 # USDT probes must be enabled before the BPF object
637 # is initialized, because that's where the actual
638 # uprobe is being attached.
639 probe.usdt.enable_probe(
640 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300641 if self.args.verbose:
642 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300643 usdt_contexts.append(probe.usdt)
644 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800645 for probe in self.probes:
646 if self.args.verbose:
647 print(probe)
648 probe.attach(self.bpf, self.args.verbose)
649
650 def _main_loop(self):
651 all_probes_trivial = all(map(Probe.is_default_action,
652 self.probes))
653
654 # Print header
Mark Draytonaa6c9162016-11-03 15:36:29 +0000655 print("%-8s %-6s %-6s %-12s %-16s %s" %
656 ("TIME", "PID", "TID", "COMM", "FUNC",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800657 "-" if not all_probes_trivial else ""))
658
659 while True:
660 self.bpf.kprobe_poll()
661
662 def run(self):
663 try:
664 self._create_probes()
665 self._generate_program()
666 self._attach_probes()
667 self._main_loop()
668 except:
669 if self.args.verbose:
670 traceback.print_exc()
Brenden Blancode14f4f2016-04-08 15:52:55 -0700671 elif sys.exc_info()[0] is not SystemExit:
672 print(sys.exc_info()[1])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800673
674if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300675 Tool().run()