blob: 73f626cf5f96f277fda59cabb9a4adc53d21af68 [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#
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +00006# usage: trace [-h] [-p PID] [-L TID] [-v] [-Z STRING_SIZE] [-S]
Mirek Klimose5382282018-01-26 14:52:50 -08007# [-M MAX_EVENTS] [-T] [-t] [-K] [-U] [-a] [-I header]
Mark Draytonaa6c9162016-11-03 15:36:29 +00008# 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
Teng Qinc200b6c2017-12-16 00:15:55 -080013from __future__ import print_function
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +030014from bcc import BPF, USDT
Teng Qin6b0ed372016-09-29 21:30:13 -070015from functools import partial
Sasha Goldshtein38847f02016-02-22 02:19:24 -080016from time import sleep, strftime
17import argparse
18import re
19import ctypes as ct
20import os
21import traceback
22import sys
23
Sasha Goldshtein38847f02016-02-22 02:19:24 -080024class Probe(object):
25 probe_count = 0
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070026 streq_index = 0
Sasha Goldshtein38847f02016-02-22 02:19:24 -080027 max_events = None
28 event_count = 0
29 first_ts = 0
Teng Qinc200b6c2017-12-16 00:15:55 -080030 print_time = False
Sasha Goldshtein38847f02016-02-22 02:19:24 -080031 use_localtime = True
Teng Qinc200b6c2017-12-16 00:15:55 -080032 time_field = False
33 print_cpu = False
Mirek Klimose5382282018-01-26 14:52:50 -080034 print_address = False
Mark Draytonaa6c9162016-11-03 15:36:29 +000035 tgid = -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070036 pid = -1
Mark Drayton5f5687e2017-02-20 18:13:03 +000037 page_cnt = None
Sasha Goldshtein38847f02016-02-22 02:19:24 -080038
39 @classmethod
40 def configure(cls, args):
41 cls.max_events = args.max_events
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +000042 cls.print_time = args.timestamp or args.time
43 cls.use_localtime = not args.timestamp
Teng Qinc200b6c2017-12-16 00:15:55 -080044 cls.time_field = cls.print_time and (not cls.use_localtime)
45 cls.print_cpu = args.print_cpu
Mirek Klimose5382282018-01-26 14:52:50 -080046 cls.print_address = args.address
Sasha Goldshtein60c41922017-02-09 04:19:53 -050047 cls.first_ts = BPF.monotonic_time()
Mark Draytonaa6c9162016-11-03 15:36:29 +000048 cls.tgid = args.tgid or -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070049 cls.pid = args.pid or -1
Mark Drayton5f5687e2017-02-20 18:13:03 +000050 cls.page_cnt = args.buffer_pages
Sasha Goldshtein38847f02016-02-22 02:19:24 -080051
Teng Qin6b0ed372016-09-29 21:30:13 -070052 def __init__(self, probe, string_size, kernel_stack, user_stack):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +030053 self.usdt = None
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070054 self.streq_functions = ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -080055 self.raw_probe = probe
56 self.string_size = string_size
Teng Qin6b0ed372016-09-29 21:30:13 -070057 self.kernel_stack = kernel_stack
58 self.user_stack = user_stack
Sasha Goldshtein38847f02016-02-22 02:19:24 -080059 Probe.probe_count += 1
60 self._parse_probe()
61 self.probe_num = Probe.probe_count
62 self.probe_name = "probe_%s_%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070063 (self._display_function(), self.probe_num)
Paul Chaignon956ca1c2017-03-04 20:07:56 +010064 self.probe_name = re.sub(r'[^A-Za-z0-9_]', '_',
65 self.probe_name)
Sasha Goldshtein38847f02016-02-22 02:19:24 -080066
67 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070068 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
69 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080070 self.types, self.values)
71
72 def is_default_action(self):
73 return self.python_format == ""
74
75 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070076 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080077 (self.raw_probe, error))
78
79 def _parse_probe(self):
80 text = self.raw_probe
81
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000082 # There might be a function signature preceding the actual
83 # filter/print part, or not. Find the probe specifier first --
84 # it ends with either a space or an open paren ( for the
85 # function signature part.
86 # opt. signature
87 # probespec | rest
88 # --------- ---------- --
89 (spec, sig, rest) = re.match(r'([^ \t\(]+)(\([^\(]*\))?(.*)',
90 text).groups()
Sasha Goldshtein38847f02016-02-22 02:19:24 -080091
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000092 self._parse_spec(spec)
Paul Chaignon956ca1c2017-03-04 20:07:56 +010093 # Remove the parens
94 self.signature = sig[1:-1] if sig else None
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000095 if self.signature and self.probe_type in ['u', 't']:
96 self._bail("USDT and tracepoint probes can't have " +
97 "a function signature; use arg1, arg2, " +
98 "... instead")
99
100 text = rest.lstrip()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800101 # If we now have a (, wait for the balanced closing ) and that
102 # will be the predicate
103 self.filter = None
104 if len(text) > 0 and text[0] == "(":
105 balance = 1
106 for i in range(1, len(text)):
107 if text[i] == "(":
108 balance += 1
109 if text[i] == ")":
110 balance -= 1
111 if balance == 0:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300112 self._parse_filter(text[:i + 1])
113 text = text[i + 1:]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800114 break
115 if self.filter is None:
116 self._bail("unmatched end of predicate")
117
118 if self.filter is None:
119 self.filter = "1"
120
121 # The remainder of the text is the printf action
122 self._parse_action(text.lstrip())
123
124 def _parse_spec(self, spec):
125 parts = spec.split(":")
126 # Two special cases: 'func' means 'p::func', 'lib:func' means
127 # 'p:lib:func'. Other combinations need to provide an empty
128 # value between delimiters, e.g. 'r::func' for a kretprobe on
129 # the function func.
130 if len(parts) == 1:
131 parts = ["p", "", parts[0]]
132 elif len(parts) == 2:
133 parts = ["p", parts[0], parts[1]]
134 if len(parts[0]) == 0:
135 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700136 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800137 self.probe_type = parts[0]
138 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700139 self._bail("probe type must be '', 'p', 't', 'r', " +
140 "or 'u', but got '%s'" % parts[0])
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800141 if self.probe_type == "t":
142 self.tp_category = parts[1]
143 self.tp_event = parts[2]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800144 self.library = "" # kernel
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300145 self.function = "" # from TRACEPOINT_PROBE
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700146 elif self.probe_type == "u":
vkhromov5a2b39e2017-07-14 20:42:29 +0100147 self.library = ':'.join(parts[1:-1])
148 self.usdt_name = parts[-1]
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700149 self.function = "" # no function, just address
150 # We will discover the USDT provider by matching on
151 # the USDT name in the specified library
152 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800153 else:
vkhromov5a2b39e2017-07-14 20:42:29 +0100154 self.library = ':'.join(parts[1:-1])
155 self.function = parts[-1]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800156
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700157 def _find_usdt_probe(self):
Sasha Goldshteindd045362016-11-13 05:07:38 -0800158 target = Probe.pid if Probe.pid and Probe.pid != -1 \
159 else Probe.tgid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000160 self.usdt = USDT(path=self.library, pid=target)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300161 for probe in self.usdt.enumerate_probes():
Javier Honduvilla Coto1ef82e22018-04-19 14:14:24 +0200162 if probe.name == self.usdt_name.encode('ascii'):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300163 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700164 self._bail("unrecognized USDT probe %s" % self.usdt_name)
165
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800166 def _parse_filter(self, filt):
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700167 self.filter = self._rewrite_expr(filt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800168
169 def _parse_types(self, fmt):
170 for match in re.finditer(
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300171 r'[^%]%(s|u|d|llu|lld|hu|hd|x|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800172 self.types.append(match.group(1))
173 fmt = re.sub(r'([^%]%)(u|d|llu|lld|hu|hd)', r'\1d', fmt)
174 fmt = re.sub(r'([^%]%)(x|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700175 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800176 self.python_format = fmt.strip('"')
177
178 def _parse_action(self, action):
179 self.values = []
180 self.types = []
181 self.python_format = ""
182 if len(action) == 0:
183 return
184
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800185 action = action.strip()
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700186 match = re.search(r'(\".*?\"),?(.*)', action)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800187 if match is None:
188 self._bail("expected format string in \"s")
189
190 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800191 self._parse_types(self.raw_format)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700192 for part in re.split('(?<!"),', match.group(2)):
193 part = self._rewrite_expr(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800194 if len(part) > 0:
195 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800196
197 aliases = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530198 "retval": "PT_REGS_RC(ctx)",
199 "arg1": "PT_REGS_PARM1(ctx)",
200 "arg2": "PT_REGS_PARM2(ctx)",
201 "arg3": "PT_REGS_PARM3(ctx)",
202 "arg4": "PT_REGS_PARM4(ctx)",
203 "arg5": "PT_REGS_PARM5(ctx)",
204 "arg6": "PT_REGS_PARM6(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800205 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
206 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
207 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
208 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
Yonghong Songf92fef22018-01-24 20:51:46 -0800209 "$cpu": "bpf_get_smp_processor_id()",
210 "$task" : "((struct task_struct *)bpf_get_current_task())"
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800211 }
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 += """
Sasha Goldshteinb9aec342017-01-16 18:41:22 +0000217static inline bool %s(char const *ignored, uintptr_t str) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700218 char needle[] = %s;
219 char haystack[sizeof(needle)];
220 bpf_probe_read(&haystack, sizeof(haystack), (void *)str);
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000221 for (int i = 0; i < sizeof(needle) - 1; ++i) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700222 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)
Teng Qinc200b6c2017-12-16 00:15:55 -0800263 fields = []
264 if self.time_field:
265 fields.append(("timestamp_ns", ct.c_ulonglong))
266 if self.print_cpu:
267 fields.append(("cpu", ct.c_int))
268 fields.extend([
Mark Draytonaa6c9162016-11-03 15:36:29 +0000269 ("tgid", ct.c_uint),
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800270 ("pid", ct.c_uint),
271 ("comm", ct.c_char * 16) # TASK_COMM_LEN
Teng Qinc200b6c2017-12-16 00:15:55 -0800272 ])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800273 for i in range(0, len(self.types)):
274 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700275 if self.kernel_stack:
276 fields.append(("kernel_stack_id", ct.c_int))
277 if self.user_stack:
278 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800279 return type(self.python_struct_name, (ct.Structure,),
280 dict(_fields_=fields))
281
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300282 c_type = {"u": "unsigned int", "d": "int",
283 "llu": "unsigned long long", "lld": "long long",
284 "hu": "unsigned short", "hd": "short",
285 "x": "unsigned int", "llx": "unsigned long long",
286 "c": "char", "K": "unsigned long long",
287 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800288 fmt_types = c_type.keys()
289
290 def _generate_field_decl(self, idx):
291 field_type = self.types[idx]
292 if field_type == "s":
293 return "char v%d[%d];\n" % (idx, self.string_size)
294 if field_type in Probe.fmt_types:
295 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
296 self._bail("unrecognized format specifier %s" % field_type)
297
298 def _generate_data_decl(self):
299 # The BPF program will populate values into the struct
300 # according to the format string, and the Python program will
301 # construct the final display string.
302 self.events_name = "%s_events" % self.probe_name
303 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700304 self.stacks_name = "%s_stacks" % self.probe_name
305 stack_table = "BPF_STACK_TRACE(%s, 1024);" % self.stacks_name \
306 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800307 data_fields = ""
308 for i, field_type in enumerate(self.types):
309 data_fields += " " + \
310 self._generate_field_decl(i)
Teng Qinc200b6c2017-12-16 00:15:55 -0800311 time_str = "u64 timestamp_ns;" if self.time_field else ""
312 cpu_str = "int cpu;" if self.print_cpu else ""
Teng Qin6b0ed372016-09-29 21:30:13 -0700313 kernel_stack_str = " int kernel_stack_id;" \
314 if self.kernel_stack else ""
315 user_stack_str = " int user_stack_id;" \
316 if self.user_stack else ""
317
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800318 text = """
319struct %s
320{
Teng Qinc200b6c2017-12-16 00:15:55 -0800321%s
322%s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000323 u32 tgid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800324 u32 pid;
325 char comm[TASK_COMM_LEN];
326%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700327%s
328%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800329};
330
331BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700332%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800333"""
Teng Qinc200b6c2017-12-16 00:15:55 -0800334 return text % (self.struct_name, time_str, cpu_str, data_fields,
Teng Qin6b0ed372016-09-29 21:30:13 -0700335 kernel_stack_str, user_stack_str,
336 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800337
338 def _generate_field_assign(self, idx):
339 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300340 expr = self.values[idx].strip()
341 text = ""
342 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000343 arg_index = int(expr[3])
344 arg_ctype = self.usdt.get_probe_arg_ctype(
345 self.usdt_name, arg_index - 1)
346 text = (" %s %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300347 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000348 % (arg_ctype, expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300349
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800350 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300351 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800352 if (%s != 0) {
353 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), (void *)%s);
354 }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300355 """ % (expr, idx, idx, expr)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800356 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300357 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800358 (idx, Probe.c_type[field_type], expr)
359 self._bail("unrecognized field type %s" % field_type)
360
Teng Qin0615bff2016-09-28 08:19:40 -0700361 def _generate_usdt_filter_read(self):
362 text = ""
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000363 if self.probe_type != "u":
364 return text
365 for arg, _ in Probe.aliases.items():
366 if not (arg.startswith("arg") and
367 (arg in self.filter)):
368 continue
369 arg_index = int(arg.replace("arg", ""))
370 arg_ctype = self.usdt.get_probe_arg_ctype(
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000371 self.usdt_name, arg_index - 1)
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000372 if not arg_ctype:
373 self._bail("Unable to determine type of {} "
374 "in the filter".format(arg))
375 text += """
Teng Qin0615bff2016-09-28 08:19:40 -0700376 {} {}_filter;
377 bpf_usdt_readarg({}, ctx, &{}_filter);
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000378 """.format(arg_ctype, arg, arg_index, arg)
379 self.filter = self.filter.replace(
380 arg, "{}_filter".format(arg))
Teng Qin0615bff2016-09-28 08:19:40 -0700381 return text
382
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700383 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800384 data_decl = self._generate_data_decl()
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000385 if Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800386 pid_filter = """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800387 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300388 """ % Probe.pid
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000389 # uprobes can have a built-in tgid filter passed to
390 # attach_uprobe, hence the check here -- for kprobes, we
391 # need to do the tgid test by hand:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000392 elif len(self.library) == 0 and Probe.tgid != -1:
393 pid_filter = """
394 if (__tgid != %d) { return 0; }
395 """ % Probe.tgid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800396 elif not include_self:
397 pid_filter = """
Mark Draytonaa6c9162016-11-03 15:36:29 +0000398 if (__tgid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300399 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800400 else:
401 pid_filter = ""
402
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700403 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700404 signature = "struct pt_regs *ctx"
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000405 if self.signature:
406 signature += ", " + self.signature
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700407
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800408 data_fields = ""
409 for i, expr in enumerate(self.values):
410 data_fields += self._generate_field_assign(i)
411
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300412 if self.probe_type == "t":
413 heading = "TRACEPOINT_PROBE(%s, %s)" % \
414 (self.tp_category, self.tp_event)
415 ctx_name = "args"
416 else:
417 heading = "int %s(%s)" % (self.probe_name, signature)
418 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300419
Teng Qinc200b6c2017-12-16 00:15:55 -0800420 time_str = """
421 __data.timestamp_ns = bpf_ktime_get_ns();""" if self.time_field else ""
422 cpu_str = """
423 __data.cpu = bpf_get_smp_processor_id();""" if self.print_cpu else ""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300424 stack_trace = ""
425 if self.user_stack:
426 stack_trace += """
427 __data.user_stack_id = %s.get_stackid(
428 %s, BPF_F_REUSE_STACKID | BPF_F_USER_STACK
429 );""" % (self.stacks_name, ctx_name)
430 if self.kernel_stack:
431 stack_trace += """
432 __data.kernel_stack_id = %s.get_stackid(
433 %s, BPF_F_REUSE_STACKID
434 );""" % (self.stacks_name, ctx_name)
435
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300436 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800437{
Mark Draytonaa6c9162016-11-03 15:36:29 +0000438 u64 __pid_tgid = bpf_get_current_pid_tgid();
439 u32 __tgid = __pid_tgid >> 32;
440 u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800441 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800442 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700443 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800444 if (!(%s)) return 0;
445
446 struct %s __data = {0};
Teng Qinc200b6c2017-12-16 00:15:55 -0800447 %s
448 %s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000449 __data.tgid = __tgid;
450 __data.pid = __pid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800451 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
452%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700453%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300454 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800455 return 0;
456}
457"""
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300458 text = text % (pid_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700459 self._generate_usdt_filter_read(), self.filter,
Teng Qinc200b6c2017-12-16 00:15:55 -0800460 self.struct_name, time_str, cpu_str, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300461 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700462
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700463 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800464
465 @classmethod
466 def _time_off_str(cls, timestamp_ns):
467 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
468
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800469 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700470 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800471 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700472 elif self.probe_type == 'u':
473 return self.usdt_name
474 else: # self.probe_type == 't'
475 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800476
Mark Draytonaa6c9162016-11-03 15:36:29 +0000477 def print_stack(self, bpf, stack_id, tgid):
Teng Qin6b0ed372016-09-29 21:30:13 -0700478 if stack_id < 0:
Mirek Klimose5382282018-01-26 14:52:50 -0800479 print(" %d" % stack_id)
480 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700481
482 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
483 for addr in stack:
Mirek Klimose5382282018-01-26 14:52:50 -0800484 print(" ", end="")
485 if Probe.print_address:
486 print("%16x " % addr, end="")
487 print("%s" % (bpf.sym(addr, tgid,
488 show_module=True, show_offset=True)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700489
Mark Draytonaa6c9162016-11-03 15:36:29 +0000490 def _format_message(self, bpf, tgid, values):
491 # Replace each %K with kernel sym and %U with user sym in tgid
Rafael Fonsecaaee5ecf2017-02-08 16:14:31 +0100492 kernel_placeholders = [i for i, t in enumerate(self.types)
493 if t == 'K']
494 user_placeholders = [i for i, t in enumerate(self.types)
495 if t == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700496 for kp in kernel_placeholders:
Sasha Goldshtein01553852017-02-09 03:58:09 -0500497 values[kp] = bpf.ksym(values[kp], show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700498 for up in user_placeholders:
Sasha Goldshtein1e34f4e2017-02-09 00:21:49 -0500499 values[up] = bpf.sym(values[up], tgid,
Sasha Goldshtein01553852017-02-09 03:58:09 -0500500 show_module=True, show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700501 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700502
503 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800504 # Cast as the generated structure type and display
505 # according to the format string in the probe.
506 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
507 values = map(lambda i: getattr(event, "v%d" % i),
508 range(0, len(self.values)))
Mark Draytonaa6c9162016-11-03 15:36:29 +0000509 msg = self._format_message(bpf, event.tgid, values)
Teng Qinc200b6c2017-12-16 00:15:55 -0800510 if Probe.print_time:
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000511 time = strftime("%H:%M:%S") if Probe.use_localtime else \
512 Probe._time_off_str(event.timestamp_ns)
Teng Qinc200b6c2017-12-16 00:15:55 -0800513 print("%-8s " % time[:8], end="")
514 if Probe.print_cpu:
515 print("%-3s " % event.cpu, end="")
516 print("%-7d %-7d %-15s %-16s %s" %
517 (event.tgid, event.pid, event.comm.decode(),
518 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800519
Teng Qin6b0ed372016-09-29 21:30:13 -0700520 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700521 self.print_stack(bpf, event.kernel_stack_id, -1)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000522 if self.user_stack:
523 self.print_stack(bpf, event.user_stack_id, event.tgid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700524 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700525 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700526
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800527 Probe.event_count += 1
528 if Probe.max_events is not None and \
529 Probe.event_count >= Probe.max_events:
530 exit()
531
532 def attach(self, bpf, verbose):
533 if len(self.library) == 0:
534 self._attach_k(bpf)
535 else:
536 self._attach_u(bpf)
537 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700538 callback = partial(self.print_event, bpf)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000539 bpf[self.events_name].open_perf_buffer(callback,
540 page_cnt=self.page_cnt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800541
542 def _attach_k(self, bpf):
543 if self.probe_type == "r":
544 bpf.attach_kretprobe(event=self.function,
545 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300546 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800547 bpf.attach_kprobe(event=self.function,
548 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300549 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800550
551 def _attach_u(self, bpf):
552 libpath = BPF.find_library(self.library)
553 if libpath is None:
554 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300555 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800556 if libpath is None or len(libpath) == 0:
557 self._bail("unable to find library %s" % self.library)
558
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700559 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300560 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700561 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800562 bpf.attach_uretprobe(name=libpath,
563 sym=self.function,
564 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000565 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800566 else:
567 bpf.attach_uprobe(name=libpath,
568 sym=self.function,
569 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000570 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800571
572class Tool(object):
Mark Drayton5f5687e2017-02-20 18:13:03 +0000573 DEFAULT_PERF_BUFFER_PAGES = 64
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800574 examples = """
575EXAMPLES:
576
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800577trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800578 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800579trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800580 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800581trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800582 Trace the read syscall and print a message for reads >20000 bytes
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000583trace 'r::do_sys_open "%llx", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800584 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800585trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800586 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800587trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800588 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800589trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
590 Trace the write() call from libc to monitor writes to STDOUT
Mark Draytonaa6c9162016-11-03 15:36:29 +0000591trace 'r::__kmalloc (retval == 0) "kmalloc failed!"'
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800592 Trace returns from __kmalloc which returned a null pointer
Mark Draytonaa6c9162016-11-03 15:36:29 +0000593trace 'r:c:malloc (retval) "allocated = %x", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800594 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300595trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800596 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700597trace 'u:pthread:pthread_create (arg4 != 0)'
598 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000599trace 'p::SyS_nanosleep(struct timespec *ts) "sleep for %lld ns", ts->tv_nsec'
600 Trace the nanosleep syscall and print the sleep duration in ns
Yonghong Songf4470dc2017-12-13 14:12:13 -0800601trace -I 'linux/fs.h' \\
602 'p::uprobe_register(struct inode *inode) "a_ops = %llx", inode->i_mapping->a_ops'
603 Trace the uprobe_register inode mapping ops, and the symbol can be found
604 in /proc/kallsyms
605trace -I 'kernel/sched/sched.h' \\
606 'p::__account_cfs_rq_runtime(struct cfs_rq *cfs_rq) "%d", cfs_rq->runtime_remaining'
607 Trace the cfs scheduling runqueue remaining runtime. The struct cfs_rq is defined
608 in kernel/sched/sched.h which is in kernel source tree and not in kernel-devel
609 package. So this command needs to run at the kernel source tree root directory
610 so that the added header file can be found by the compiler.
tehnerd86293f02018-01-23 21:21:58 -0800611trace -I 'net/sock.h' \\
612 'udpv6_sendmsg(struct sock *sk) (sk->sk_dport == 13568)'
613 Trace udpv6 sendmsg calls only if socket's destination port is equal
614 to 53 (DNS; 13568 in big endian order)
Yonghong Songf92fef22018-01-24 20:51:46 -0800615trace -I 'linux/fs_struct.h' 'mntns_install "users = %d", $task->fs->users'
616 Trace the number of users accessing the file system of the current task
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800617"""
618
619 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300620 parser = argparse.ArgumentParser(description="Attach to " +
621 "functions and print trace messages.",
622 formatter_class=argparse.RawDescriptionHelpFormatter,
623 epilog=Tool.examples)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000624 parser.add_argument("-b", "--buffer-pages", type=int,
625 default=Tool.DEFAULT_PERF_BUFFER_PAGES,
626 help="number of pages to use for perf_events ring buffer "
627 "(default: %(default)d)")
Mark Draytonaa6c9162016-11-03 15:36:29 +0000628 # we'll refer to the userspace concepts of "pid" and "tid" by
629 # their kernel names -- tgid and pid -- inside the script
630 parser.add_argument("-p", "--pid", type=int, metavar="PID",
631 dest="tgid", help="id of the process to trace (optional)")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000632 parser.add_argument("-L", "--tid", type=int, metavar="TID",
Mark Draytonaa6c9162016-11-03 15:36:29 +0000633 dest="pid", help="id of the thread to trace (optional)")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800634 parser.add_argument("-v", "--verbose", action="store_true",
635 help="print resulting BPF program code before executing")
636 parser.add_argument("-Z", "--string-size", type=int,
637 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300638 parser.add_argument("-S", "--include-self",
639 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800640 help="do not filter trace's own pid from the trace")
641 parser.add_argument("-M", "--max-events", type=int,
642 help="number of events to print before quitting")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000643 parser.add_argument("-t", "--timestamp", action="store_true",
644 help="print timestamp column (offset from trace start)")
645 parser.add_argument("-T", "--time", action="store_true",
646 help="print time column")
Teng Qinc200b6c2017-12-16 00:15:55 -0800647 parser.add_argument("-C", "--print_cpu", action="store_true",
648 help="print CPU id")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300649 parser.add_argument("-K", "--kernel-stack",
650 action="store_true", help="output kernel stack trace")
651 parser.add_argument("-U", "--user-stack",
652 action="store_true", help="output user stack trace")
Mirek Klimose5382282018-01-26 14:52:50 -0800653 parser.add_argument("-a", "--address", action="store_true",
654 help="print virtual address in stacks")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800655 parser.add_argument(metavar="probe", dest="probes", nargs="+",
656 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300657 parser.add_argument("-I", "--include", action="append",
658 metavar="header",
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300659 help="additional header files to include in the BPF program "
Yonghong Songf4470dc2017-12-13 14:12:13 -0800660 "as either full path, "
661 "or relative to current working directory, "
662 "or relative to default kernel header search path")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100663 parser.add_argument("--ebpf", action="store_true",
664 help=argparse.SUPPRESS)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800665 self.args = parser.parse_args()
Mark Draytonaa6c9162016-11-03 15:36:29 +0000666 if self.args.tgid and self.args.pid:
Yonghong Songf4470dc2017-12-13 14:12:13 -0800667 parser.error("only one of -p and -L may be specified")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800668
669 def _create_probes(self):
670 Probe.configure(self.args)
671 self.probes = []
672 for probe_spec in self.args.probes:
673 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700674 probe_spec, self.args.string_size,
675 self.args.kernel_stack, self.args.user_stack))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800676
677 def _generate_program(self):
678 self.program = """
679#include <linux/ptrace.h>
680#include <linux/sched.h> /* For TASK_COMM_LEN */
681
682"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300683 for include in (self.args.include or []):
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300684 if include.startswith((".", "/")):
685 include = os.path.abspath(include)
686 self.program += "#include \"%s\"\n" % include
687 else:
688 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700689 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800690 map(lambda p: p.raw_probe, self.probes))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800691 for probe in self.probes:
692 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700693 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800694
Nathan Scottcf0792f2018-02-02 16:56:50 +1100695 if self.args.verbose or self.args.ebpf:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800696 print(self.program)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100697 if self.args.ebpf:
698 exit()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800699
700 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300701 usdt_contexts = []
702 for probe in self.probes:
703 if probe.usdt:
704 # USDT probes must be enabled before the BPF object
705 # is initialized, because that's where the actual
706 # uprobe is being attached.
707 probe.usdt.enable_probe(
708 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300709 if self.args.verbose:
710 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300711 usdt_contexts.append(probe.usdt)
712 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800713 for probe in self.probes:
714 if self.args.verbose:
715 print(probe)
716 probe.attach(self.bpf, self.args.verbose)
717
718 def _main_loop(self):
719 all_probes_trivial = all(map(Probe.is_default_action,
720 self.probes))
721
722 # Print header
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000723 if self.args.timestamp or self.args.time:
Teng Qinc200b6c2017-12-16 00:15:55 -0800724 print("%-8s " % "TIME", end="");
725 if self.args.print_cpu:
726 print("%-3s " % "CPU", end="");
727 print("%-7s %-7s %-15s %-16s %s" %
728 ("PID", "TID", "COMM", "FUNC",
729 "-" if not all_probes_trivial else ""))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800730
731 while True:
Teng Qindbf00292018-02-28 21:47:50 -0800732 self.bpf.perf_buffer_poll()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800733
734 def run(self):
735 try:
736 self._create_probes()
737 self._generate_program()
738 self._attach_probes()
739 self._main_loop()
740 except:
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500741 exc_info = sys.exc_info()
742 sys_exit = exc_info[0] is SystemExit
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800743 if self.args.verbose:
744 traceback.print_exc()
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500745 elif not sys_exit:
746 print(exc_info[1])
747 exit(0 if sys_exit else 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800748
749if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300750 Tool().run()