blob: ba939987143b110a44724e94a80405a1ed08f40e [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):
Sasha Goldshteindd045362016-11-13 05:07:38 -0800160 target = Probe.pid if Probe.pid and Probe.pid != -1 \
161 else Probe.tgid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000162 self.usdt = USDT(path=self.library, pid=target)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300163 for probe in self.usdt.enumerate_probes():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700164 if probe.name == self.usdt_name:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300165 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700166 self._bail("unrecognized USDT probe %s" % self.usdt_name)
167
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800168 def _parse_filter(self, filt):
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700169 self.filter = self._rewrite_expr(filt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800170
171 def _parse_types(self, fmt):
172 for match in re.finditer(
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300173 r'[^%]%(s|u|d|llu|lld|hu|hd|x|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800174 self.types.append(match.group(1))
175 fmt = re.sub(r'([^%]%)(u|d|llu|lld|hu|hd)', r'\1d', fmt)
176 fmt = re.sub(r'([^%]%)(x|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700177 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800178 self.python_format = fmt.strip('"')
179
180 def _parse_action(self, action):
181 self.values = []
182 self.types = []
183 self.python_format = ""
184 if len(action) == 0:
185 return
186
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800187 action = action.strip()
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700188 match = re.search(r'(\".*?\"),?(.*)', action)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800189 if match is None:
190 self._bail("expected format string in \"s")
191
192 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800193 self._parse_types(self.raw_format)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700194 for part in re.split('(?<!"),', match.group(2)):
195 part = self._rewrite_expr(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800196 if len(part) > 0:
197 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800198
199 aliases = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530200 "retval": "PT_REGS_RC(ctx)",
201 "arg1": "PT_REGS_PARM1(ctx)",
202 "arg2": "PT_REGS_PARM2(ctx)",
203 "arg3": "PT_REGS_PARM3(ctx)",
204 "arg4": "PT_REGS_PARM4(ctx)",
205 "arg5": "PT_REGS_PARM5(ctx)",
206 "arg6": "PT_REGS_PARM6(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800207 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
208 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
209 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
210 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
211 "$cpu": "bpf_get_smp_processor_id()"
212 }
213
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700214 def _generate_streq_function(self, string):
215 fname = "streq_%d" % Probe.streq_index
216 Probe.streq_index += 1
217 self.streq_functions += """
218static inline bool %s(char const *ignored, unsigned long str) {
219 char needle[] = %s;
220 char haystack[sizeof(needle)];
221 bpf_probe_read(&haystack, sizeof(haystack), (void *)str);
222 for (int i = 0; i < sizeof(needle); ++i) {
223 if (needle[i] != haystack[i]) {
224 return false;
225 }
226 }
227 return true;
228}
229 """ % (fname, string)
230 return fname
231
232 def _rewrite_expr(self, expr):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800233 for alias, replacement in Probe.aliases.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700234 # For USDT probes, we replace argN values with the
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300235 # actual arguments for that probe obtained using
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300236 # bpf_readarg_N macros emitted at BPF construction.
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700237 if alias.startswith("arg") and self.probe_type == "u":
238 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800239 expr = expr.replace(alias, replacement)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700240 matches = re.finditer('STRCMP\\(("[^"]+\\")', expr)
241 for match in matches:
242 string = match.group(1)
243 fname = self._generate_streq_function(string)
244 expr = expr.replace("STRCMP", fname, 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800245 return expr
246
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300247 p_type = {"u": ct.c_uint, "d": ct.c_int,
248 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
249 "hu": ct.c_ushort, "hd": ct.c_short,
250 "x": ct.c_uint, "llx": ct.c_ulonglong, "c": ct.c_ubyte,
251 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800252
253 def _generate_python_field_decl(self, idx, fields):
254 field_type = self.types[idx]
255 if field_type == "s":
256 ptype = ct.c_char * self.string_size
257 else:
258 ptype = Probe.p_type[field_type]
259 fields.append(("v%d" % idx, ptype))
260
261 def _generate_python_data_decl(self):
262 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700263 (self._display_function(), self.probe_num)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800264 fields = [
265 ("timestamp_ns", ct.c_ulonglong),
Mark Draytonaa6c9162016-11-03 15:36:29 +0000266 ("tgid", ct.c_uint),
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800267 ("pid", ct.c_uint),
268 ("comm", ct.c_char * 16) # TASK_COMM_LEN
269 ]
270 for i in range(0, len(self.types)):
271 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700272 if self.kernel_stack:
273 fields.append(("kernel_stack_id", ct.c_int))
274 if self.user_stack:
275 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800276 return type(self.python_struct_name, (ct.Structure,),
277 dict(_fields_=fields))
278
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300279 c_type = {"u": "unsigned int", "d": "int",
280 "llu": "unsigned long long", "lld": "long long",
281 "hu": "unsigned short", "hd": "short",
282 "x": "unsigned int", "llx": "unsigned long long",
283 "c": "char", "K": "unsigned long long",
284 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800285 fmt_types = c_type.keys()
286
287 def _generate_field_decl(self, idx):
288 field_type = self.types[idx]
289 if field_type == "s":
290 return "char v%d[%d];\n" % (idx, self.string_size)
291 if field_type in Probe.fmt_types:
292 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
293 self._bail("unrecognized format specifier %s" % field_type)
294
295 def _generate_data_decl(self):
296 # The BPF program will populate values into the struct
297 # according to the format string, and the Python program will
298 # construct the final display string.
299 self.events_name = "%s_events" % self.probe_name
300 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700301 self.stacks_name = "%s_stacks" % self.probe_name
302 stack_table = "BPF_STACK_TRACE(%s, 1024);" % self.stacks_name \
303 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800304 data_fields = ""
305 for i, field_type in enumerate(self.types):
306 data_fields += " " + \
307 self._generate_field_decl(i)
308
Teng Qin6b0ed372016-09-29 21:30:13 -0700309 kernel_stack_str = " int kernel_stack_id;" \
310 if self.kernel_stack else ""
311 user_stack_str = " int user_stack_id;" \
312 if self.user_stack else ""
313
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800314 text = """
315struct %s
316{
317 u64 timestamp_ns;
Mark Draytonaa6c9162016-11-03 15:36:29 +0000318 u32 tgid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800319 u32 pid;
320 char comm[TASK_COMM_LEN];
321%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700322%s
323%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800324};
325
326BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700327%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800328"""
Teng Qin6b0ed372016-09-29 21:30:13 -0700329 return text % (self.struct_name, data_fields,
330 kernel_stack_str, user_stack_str,
331 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800332
333 def _generate_field_assign(self, idx):
334 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300335 expr = self.values[idx].strip()
336 text = ""
337 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshteinb6db17f2016-10-04 19:50:50 +0300338 text = (" u64 %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300339 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
340 % (expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300341
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800342 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300343 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800344 if (%s != 0) {
345 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), (void *)%s);
346 }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300347 """ % (expr, idx, idx, expr)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800348 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300349 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800350 (idx, Probe.c_type[field_type], expr)
351 self._bail("unrecognized field type %s" % field_type)
352
Teng Qin0615bff2016-09-28 08:19:40 -0700353 def _generate_usdt_filter_read(self):
354 text = ""
355 if self.probe_type == "u":
356 for arg, _ in Probe.aliases.items():
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300357 if not (arg.startswith("arg") and
358 (arg in self.filter)):
Teng Qin0615bff2016-09-28 08:19:40 -0700359 continue
360 arg_index = int(arg.replace("arg", ""))
361 arg_ctype = self.usdt.get_probe_arg_ctype(
362 self.usdt_name, arg_index)
363 if not arg_ctype:
364 self._bail("Unable to determine type of {} "
365 "in the filter".format(arg))
366 text += """
367 {} {}_filter;
368 bpf_usdt_readarg({}, ctx, &{}_filter);
369 """.format(arg_ctype, arg, arg_index, arg)
370 self.filter = self.filter.replace(
371 arg, "{}_filter".format(arg))
372 return text
373
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700374 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800375 data_decl = self._generate_data_decl()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800376 # kprobes don't have built-in pid filters, so we have to add
377 # it to the function body:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700378 if len(self.library) == 0 and Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800379 pid_filter = """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800380 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300381 """ % Probe.pid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000382 elif len(self.library) == 0 and Probe.tgid != -1:
383 pid_filter = """
384 if (__tgid != %d) { return 0; }
385 """ % Probe.tgid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800386 elif not include_self:
387 pid_filter = """
Mark Draytonaa6c9162016-11-03 15:36:29 +0000388 if (__tgid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300389 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800390 else:
391 pid_filter = ""
392
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700393 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700394 signature = "struct pt_regs *ctx"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700395
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800396 data_fields = ""
397 for i, expr in enumerate(self.values):
398 data_fields += self._generate_field_assign(i)
399
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300400 if self.probe_type == "t":
401 heading = "TRACEPOINT_PROBE(%s, %s)" % \
402 (self.tp_category, self.tp_event)
403 ctx_name = "args"
404 else:
405 heading = "int %s(%s)" % (self.probe_name, signature)
406 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300407
408 stack_trace = ""
409 if self.user_stack:
410 stack_trace += """
411 __data.user_stack_id = %s.get_stackid(
412 %s, BPF_F_REUSE_STACKID | BPF_F_USER_STACK
413 );""" % (self.stacks_name, ctx_name)
414 if self.kernel_stack:
415 stack_trace += """
416 __data.kernel_stack_id = %s.get_stackid(
417 %s, BPF_F_REUSE_STACKID
418 );""" % (self.stacks_name, ctx_name)
419
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300420 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800421{
Mark Draytonaa6c9162016-11-03 15:36:29 +0000422 u64 __pid_tgid = bpf_get_current_pid_tgid();
423 u32 __tgid = __pid_tgid >> 32;
424 u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800425 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800426 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700427 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800428 if (!(%s)) return 0;
429
430 struct %s __data = {0};
431 __data.timestamp_ns = bpf_ktime_get_ns();
Mark Draytonaa6c9162016-11-03 15:36:29 +0000432 __data.tgid = __tgid;
433 __data.pid = __pid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800434 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
435%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700436%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300437 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800438 return 0;
439}
440"""
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300441 text = text % (pid_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700442 self._generate_usdt_filter_read(), self.filter,
Teng Qin6b0ed372016-09-29 21:30:13 -0700443 self.struct_name, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300444 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700445
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700446 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800447
448 @classmethod
449 def _time_off_str(cls, timestamp_ns):
450 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
451
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800452 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700453 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800454 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700455 elif self.probe_type == 'u':
456 return self.usdt_name
457 else: # self.probe_type == 't'
458 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800459
Mark Draytonaa6c9162016-11-03 15:36:29 +0000460 def print_stack(self, bpf, stack_id, tgid):
Teng Qin6b0ed372016-09-29 21:30:13 -0700461 if stack_id < 0:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700462 print(" %d" % stack_id)
463 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700464
465 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
466 for addr in stack:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000467 print(" %016x %s" % (addr, bpf.sym(addr, tgid)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700468
Mark Draytonaa6c9162016-11-03 15:36:29 +0000469 def _format_message(self, bpf, tgid, values):
470 # Replace each %K with kernel sym and %U with user sym in tgid
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700471 kernel_placeholders = [i for i in xrange(0, len(self.types))
472 if self.types[i] == 'K']
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300473 user_placeholders = [i for i in xrange(0, len(self.types))
474 if self.types[i] == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700475 for kp in kernel_placeholders:
476 values[kp] = bpf.ksymaddr(values[kp])
477 for up in user_placeholders:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000478 values[up] = bpf.symaddr(values[up], tgid)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700479 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700480
481 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800482 # Cast as the generated structure type and display
483 # according to the format string in the probe.
484 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
485 values = map(lambda i: getattr(event, "v%d" % i),
486 range(0, len(self.values)))
Mark Draytonaa6c9162016-11-03 15:36:29 +0000487 msg = self._format_message(bpf, event.tgid, values)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800488 time = strftime("%H:%M:%S") if Probe.use_localtime else \
489 Probe._time_off_str(event.timestamp_ns)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000490 print("%-8s %-6d %-6d %-12s %-16s %s" %
491 (time[:8], event.tgid, event.pid, event.comm,
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800492 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800493
Teng Qin6b0ed372016-09-29 21:30:13 -0700494 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700495 self.print_stack(bpf, event.kernel_stack_id, -1)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000496 if self.user_stack:
497 self.print_stack(bpf, event.user_stack_id, event.tgid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700498 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700499 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700500
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800501 Probe.event_count += 1
502 if Probe.max_events is not None and \
503 Probe.event_count >= Probe.max_events:
504 exit()
505
506 def attach(self, bpf, verbose):
507 if len(self.library) == 0:
508 self._attach_k(bpf)
509 else:
510 self._attach_u(bpf)
511 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700512 callback = partial(self.print_event, bpf)
513 bpf[self.events_name].open_perf_buffer(callback)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800514
515 def _attach_k(self, bpf):
516 if self.probe_type == "r":
517 bpf.attach_kretprobe(event=self.function,
518 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300519 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800520 bpf.attach_kprobe(event=self.function,
521 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300522 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800523
524 def _attach_u(self, bpf):
525 libpath = BPF.find_library(self.library)
526 if libpath is None:
527 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300528 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800529 if libpath is None or len(libpath) == 0:
530 self._bail("unable to find library %s" % self.library)
531
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700532 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300533 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700534 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800535 bpf.attach_uretprobe(name=libpath,
536 sym=self.function,
537 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700538 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800539 else:
540 bpf.attach_uprobe(name=libpath,
541 sym=self.function,
542 fn_name=self.probe_name,
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700543 pid=Probe.pid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800544
545class Tool(object):
546 examples = """
547EXAMPLES:
548
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800549trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800550 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800551trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800552 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800553trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800554 Trace the read syscall and print a message for reads >20000 bytes
555trace 'r::do_sys_return "%llx", retval'
556 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800557trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800558 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800559trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800560 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800561trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
562 Trace the write() call from libc to monitor writes to STDOUT
Mark Draytonaa6c9162016-11-03 15:36:29 +0000563trace 'r::__kmalloc (retval == 0) "kmalloc failed!"'
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800564 Trace returns from __kmalloc which returned a null pointer
Mark Draytonaa6c9162016-11-03 15:36:29 +0000565trace 'r:c:malloc (retval) "allocated = %x", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800566 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300567trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800568 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700569trace 'u:pthread:pthread_create (arg4 != 0)'
570 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800571"""
572
573 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300574 parser = argparse.ArgumentParser(description="Attach to " +
575 "functions and print trace messages.",
576 formatter_class=argparse.RawDescriptionHelpFormatter,
577 epilog=Tool.examples)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000578 # we'll refer to the userspace concepts of "pid" and "tid" by
579 # their kernel names -- tgid and pid -- inside the script
580 parser.add_argument("-p", "--pid", type=int, metavar="PID",
581 dest="tgid", help="id of the process to trace (optional)")
582 parser.add_argument("-t", "--tid", type=int, metavar="TID",
583 dest="pid", help="id of the thread to trace (optional)")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800584 parser.add_argument("-v", "--verbose", action="store_true",
585 help="print resulting BPF program code before executing")
586 parser.add_argument("-Z", "--string-size", type=int,
587 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300588 parser.add_argument("-S", "--include-self",
589 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800590 help="do not filter trace's own pid from the trace")
591 parser.add_argument("-M", "--max-events", type=int,
592 help="number of events to print before quitting")
593 parser.add_argument("-o", "--offset", action="store_true",
594 help="use relative time from first traced message")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300595 parser.add_argument("-K", "--kernel-stack",
596 action="store_true", help="output kernel stack trace")
597 parser.add_argument("-U", "--user-stack",
598 action="store_true", help="output user stack trace")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800599 parser.add_argument(metavar="probe", dest="probes", nargs="+",
600 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300601 parser.add_argument("-I", "--include", action="append",
602 metavar="header",
603 help="additional header files to include in the BPF program")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800604 self.args = parser.parse_args()
Mark Draytonaa6c9162016-11-03 15:36:29 +0000605 if self.args.tgid and self.args.pid:
606 parser.error("only one of -p and -t may be specified")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800607
608 def _create_probes(self):
609 Probe.configure(self.args)
610 self.probes = []
611 for probe_spec in self.args.probes:
612 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700613 probe_spec, self.args.string_size,
614 self.args.kernel_stack, self.args.user_stack))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800615
616 def _generate_program(self):
617 self.program = """
618#include <linux/ptrace.h>
619#include <linux/sched.h> /* For TASK_COMM_LEN */
620
621"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300622 for include in (self.args.include or []):
623 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700624 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800625 map(lambda p: p.raw_probe, self.probes))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800626 for probe in self.probes:
627 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700628 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800629
630 if self.args.verbose:
631 print(self.program)
632
633 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300634 usdt_contexts = []
635 for probe in self.probes:
636 if probe.usdt:
637 # USDT probes must be enabled before the BPF object
638 # is initialized, because that's where the actual
639 # uprobe is being attached.
640 probe.usdt.enable_probe(
641 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300642 if self.args.verbose:
643 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300644 usdt_contexts.append(probe.usdt)
645 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800646 for probe in self.probes:
647 if self.args.verbose:
648 print(probe)
649 probe.attach(self.bpf, self.args.verbose)
650
651 def _main_loop(self):
652 all_probes_trivial = all(map(Probe.is_default_action,
653 self.probes))
654
655 # Print header
Mark Draytonaa6c9162016-11-03 15:36:29 +0000656 print("%-8s %-6s %-6s %-12s %-16s %s" %
657 ("TIME", "PID", "TID", "COMM", "FUNC",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800658 "-" if not all_probes_trivial else ""))
659
660 while True:
661 self.bpf.kprobe_poll()
662
663 def run(self):
664 try:
665 self._create_probes()
666 self._generate_program()
667 self._attach_probes()
668 self._main_loop()
669 except:
670 if self.args.verbose:
671 traceback.print_exc()
Brenden Blancode14f4f2016-04-08 15:52:55 -0700672 elif sys.exc_info()[0] is not SystemExit:
673 print(sys.exc_info()[1])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800674
675if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300676 Tool().run()