blob: 22333056b43dde5906cd425a3ca504f152590b16 [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
Nikita V. Shirokov3953c702018-07-27 16:13:47 -070051 cls.bin_cmp = args.bin_cmp
Sasha Goldshtein38847f02016-02-22 02:19:24 -080052
Teng Qin6b0ed372016-09-29 21:30:13 -070053 def __init__(self, probe, string_size, kernel_stack, user_stack):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +030054 self.usdt = None
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070055 self.streq_functions = ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -080056 self.raw_probe = probe
57 self.string_size = string_size
Teng Qin6b0ed372016-09-29 21:30:13 -070058 self.kernel_stack = kernel_stack
59 self.user_stack = user_stack
Sasha Goldshtein38847f02016-02-22 02:19:24 -080060 Probe.probe_count += 1
61 self._parse_probe()
62 self.probe_num = Probe.probe_count
63 self.probe_name = "probe_%s_%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070064 (self._display_function(), self.probe_num)
Paul Chaignon956ca1c2017-03-04 20:07:56 +010065 self.probe_name = re.sub(r'[^A-Za-z0-9_]', '_',
66 self.probe_name)
Sasha Goldshtein38847f02016-02-22 02:19:24 -080067
yonghong-song2da34262018-06-13 06:12:22 -070068 # compiler can generate proper codes for function
69 # signatures with "syscall__" prefix
70 if self.is_syscall_kprobe:
71 self.probe_name = "syscall__" + self.probe_name[6:]
72
Sasha Goldshtein38847f02016-02-22 02:19:24 -080073 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070074 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
75 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080076 self.types, self.values)
77
78 def is_default_action(self):
79 return self.python_format == ""
80
81 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070082 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080083 (self.raw_probe, error))
84
85 def _parse_probe(self):
86 text = self.raw_probe
87
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000088 # There might be a function signature preceding the actual
89 # filter/print part, or not. Find the probe specifier first --
90 # it ends with either a space or an open paren ( for the
91 # function signature part.
92 # opt. signature
93 # probespec | rest
94 # --------- ---------- --
95 (spec, sig, rest) = re.match(r'([^ \t\(]+)(\([^\(]*\))?(.*)',
96 text).groups()
Sasha Goldshtein38847f02016-02-22 02:19:24 -080097
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000098 self._parse_spec(spec)
Paul Chaignon956ca1c2017-03-04 20:07:56 +010099 # Remove the parens
100 self.signature = sig[1:-1] if sig else None
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000101 if self.signature and self.probe_type in ['u', 't']:
102 self._bail("USDT and tracepoint probes can't have " +
103 "a function signature; use arg1, arg2, " +
104 "... instead")
105
106 text = rest.lstrip()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800107 # If we now have a (, wait for the balanced closing ) and that
108 # will be the predicate
109 self.filter = None
110 if len(text) > 0 and text[0] == "(":
111 balance = 1
112 for i in range(1, len(text)):
113 if text[i] == "(":
114 balance += 1
115 if text[i] == ")":
116 balance -= 1
117 if balance == 0:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300118 self._parse_filter(text[:i + 1])
119 text = text[i + 1:]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800120 break
121 if self.filter is None:
122 self._bail("unmatched end of predicate")
123
124 if self.filter is None:
125 self.filter = "1"
126
127 # The remainder of the text is the printf action
128 self._parse_action(text.lstrip())
129
130 def _parse_spec(self, spec):
131 parts = spec.split(":")
132 # Two special cases: 'func' means 'p::func', 'lib:func' means
133 # 'p:lib:func'. Other combinations need to provide an empty
134 # value between delimiters, e.g. 'r::func' for a kretprobe on
135 # the function func.
136 if len(parts) == 1:
137 parts = ["p", "", parts[0]]
138 elif len(parts) == 2:
139 parts = ["p", parts[0], parts[1]]
140 if len(parts[0]) == 0:
141 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700142 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800143 self.probe_type = parts[0]
144 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700145 self._bail("probe type must be '', 'p', 't', 'r', " +
146 "or 'u', but got '%s'" % parts[0])
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800147 if self.probe_type == "t":
148 self.tp_category = parts[1]
149 self.tp_event = parts[2]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800150 self.library = "" # kernel
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300151 self.function = "" # from TRACEPOINT_PROBE
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700152 elif self.probe_type == "u":
vkhromov5a2b39e2017-07-14 20:42:29 +0100153 self.library = ':'.join(parts[1:-1])
154 self.usdt_name = parts[-1]
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700155 self.function = "" # no function, just address
156 # We will discover the USDT provider by matching on
157 # the USDT name in the specified library
158 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800159 else:
vkhromov5a2b39e2017-07-14 20:42:29 +0100160 self.library = ':'.join(parts[1:-1])
161 self.function = parts[-1]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800162
yonghong-song2da34262018-06-13 06:12:22 -0700163 # only x64 syscalls needs checking, no other syscall wrapper yet.
164 self.is_syscall_kprobe = False
165 if self.probe_type == "p" and len(self.library) == 0 and \
166 self.function[:10] == "__x64_sys_":
167 self.is_syscall_kprobe = True
168
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700169 def _find_usdt_probe(self):
Sasha Goldshteindd045362016-11-13 05:07:38 -0800170 target = Probe.pid if Probe.pid and Probe.pid != -1 \
171 else Probe.tgid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000172 self.usdt = USDT(path=self.library, pid=target)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300173 for probe in self.usdt.enumerate_probes():
Javier Honduvilla Coto1ef82e22018-04-19 14:14:24 +0200174 if probe.name == self.usdt_name.encode('ascii'):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300175 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700176 self._bail("unrecognized USDT probe %s" % self.usdt_name)
177
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800178 def _parse_filter(self, filt):
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700179 self.filter = self._rewrite_expr(filt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800180
181 def _parse_types(self, fmt):
182 for match in re.finditer(
yonghong-songf7202572018-09-19 08:50:59 -0700183 r'[^%]%(s|u|d|lu|llu|ld|lld|hu|hd|x|lx|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800184 self.types.append(match.group(1))
yonghong-songf7202572018-09-19 08:50:59 -0700185 fmt = re.sub(r'([^%]%)(u|d|lu|llu|ld|lld|hu|hd)', r'\1d', fmt)
186 fmt = re.sub(r'([^%]%)(x|lx|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700187 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800188 self.python_format = fmt.strip('"')
189
190 def _parse_action(self, action):
191 self.values = []
192 self.types = []
193 self.python_format = ""
194 if len(action) == 0:
195 return
196
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800197 action = action.strip()
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700198 match = re.search(r'(\".*?\"),?(.*)', action)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800199 if match is None:
200 self._bail("expected format string in \"s")
201
202 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800203 self._parse_types(self.raw_format)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700204 for part in re.split('(?<!"),', match.group(2)):
205 part = self._rewrite_expr(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800206 if len(part) > 0:
207 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800208
yonghong-song2da34262018-06-13 06:12:22 -0700209 aliases_arg = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530210 "arg1": "PT_REGS_PARM1(ctx)",
211 "arg2": "PT_REGS_PARM2(ctx)",
212 "arg3": "PT_REGS_PARM3(ctx)",
213 "arg4": "PT_REGS_PARM4(ctx)",
214 "arg5": "PT_REGS_PARM5(ctx)",
215 "arg6": "PT_REGS_PARM6(ctx)",
yonghong-song2da34262018-06-13 06:12:22 -0700216 }
217
218 aliases_indarg = {
219 "arg1": "({u64 _val; struct pt_regs *_ctx = PT_REGS_PARM1(ctx);"
220 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM1(_ctx))); _val;})",
221 "arg2": "({u64 _val; struct pt_regs *_ctx = PT_REGS_PARM2(ctx);"
222 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM2(_ctx))); _val;})",
223 "arg3": "({u64 _val; struct pt_regs *_ctx = PT_REGS_PARM3(ctx);"
224 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM3(_ctx))); _val;})",
225 "arg4": "({u64 _val; struct pt_regs *_ctx = PT_REGS_PARM4(ctx);"
226 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM4(_ctx))); _val;})",
227 "arg5": "({u64 _val; struct pt_regs *_ctx = PT_REGS_PARM5(ctx);"
228 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM5(_ctx))); _val;})",
229 "arg6": "({u64 _val; struct pt_regs *_ctx = PT_REGS_PARM6(ctx);"
230 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM6(_ctx))); _val;})",
231 }
232
233 aliases_common = {
234 "retval": "PT_REGS_RC(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800235 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
236 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
237 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
238 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
Yonghong Songf92fef22018-01-24 20:51:46 -0800239 "$cpu": "bpf_get_smp_processor_id()",
240 "$task" : "((struct task_struct *)bpf_get_current_task())"
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800241 }
242
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700243 def _generate_streq_function(self, string):
244 fname = "streq_%d" % Probe.streq_index
245 Probe.streq_index += 1
246 self.streq_functions += """
Sasha Goldshteinb9aec342017-01-16 18:41:22 +0000247static inline bool %s(char const *ignored, uintptr_t str) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700248 char needle[] = %s;
249 char haystack[sizeof(needle)];
250 bpf_probe_read(&haystack, sizeof(haystack), (void *)str);
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000251 for (int i = 0; i < sizeof(needle) - 1; ++i) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700252 if (needle[i] != haystack[i]) {
253 return false;
254 }
255 }
256 return true;
257}
258 """ % (fname, string)
259 return fname
260
261 def _rewrite_expr(self, expr):
yonghong-song2da34262018-06-13 06:12:22 -0700262 if self.is_syscall_kprobe:
263 for alias, replacement in Probe.aliases_indarg.items():
264 expr = expr.replace(alias, replacement)
265 else:
266 for alias, replacement in Probe.aliases_arg.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700267 # For USDT probes, we replace argN values with the
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300268 # actual arguments for that probe obtained using
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300269 # bpf_readarg_N macros emitted at BPF construction.
yonghong-song2da34262018-06-13 06:12:22 -0700270 if self.probe_type == "u":
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700271 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800272 expr = expr.replace(alias, replacement)
yonghong-song2da34262018-06-13 06:12:22 -0700273 for alias, replacement in Probe.aliases_common.items():
274 expr = expr.replace(alias, replacement)
Nikita V. Shirokov3953c702018-07-27 16:13:47 -0700275 if self.bin_cmp:
276 STRCMP_RE = 'STRCMP\\(\"([^"]+)\\"'
277 else:
278 STRCMP_RE = 'STRCMP\\(("[^"]+\\")'
279 matches = re.finditer(STRCMP_RE, expr)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700280 for match in matches:
281 string = match.group(1)
282 fname = self._generate_streq_function(string)
283 expr = expr.replace("STRCMP", fname, 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800284 return expr
285
yonghong-songf7202572018-09-19 08:50:59 -0700286 p_type = {"u": ct.c_uint, "d": ct.c_int, "lu": ct.c_ulong,
287 "ld": ct.c_long,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300288 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
289 "hu": ct.c_ushort, "hd": ct.c_short,
yonghong-songf7202572018-09-19 08:50:59 -0700290 "x": ct.c_uint, "lx": ct.c_ulong, "llx": ct.c_ulonglong,
291 "c": ct.c_ubyte,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300292 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800293
294 def _generate_python_field_decl(self, idx, fields):
295 field_type = self.types[idx]
296 if field_type == "s":
297 ptype = ct.c_char * self.string_size
298 else:
299 ptype = Probe.p_type[field_type]
300 fields.append(("v%d" % idx, ptype))
301
302 def _generate_python_data_decl(self):
303 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700304 (self._display_function(), self.probe_num)
Teng Qinc200b6c2017-12-16 00:15:55 -0800305 fields = []
306 if self.time_field:
307 fields.append(("timestamp_ns", ct.c_ulonglong))
308 if self.print_cpu:
309 fields.append(("cpu", ct.c_int))
310 fields.extend([
Mark Draytonaa6c9162016-11-03 15:36:29 +0000311 ("tgid", ct.c_uint),
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800312 ("pid", ct.c_uint),
313 ("comm", ct.c_char * 16) # TASK_COMM_LEN
Teng Qinc200b6c2017-12-16 00:15:55 -0800314 ])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800315 for i in range(0, len(self.types)):
316 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700317 if self.kernel_stack:
318 fields.append(("kernel_stack_id", ct.c_int))
319 if self.user_stack:
320 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800321 return type(self.python_struct_name, (ct.Structure,),
322 dict(_fields_=fields))
323
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300324 c_type = {"u": "unsigned int", "d": "int",
yonghong-songf7202572018-09-19 08:50:59 -0700325 "lu": "unsigned long", "ld": "long",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300326 "llu": "unsigned long long", "lld": "long long",
327 "hu": "unsigned short", "hd": "short",
yonghong-songf7202572018-09-19 08:50:59 -0700328 "x": "unsigned int", "lx": "unsigned long",
329 "llx": "unsigned long long",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300330 "c": "char", "K": "unsigned long long",
331 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800332 fmt_types = c_type.keys()
333
334 def _generate_field_decl(self, idx):
335 field_type = self.types[idx]
336 if field_type == "s":
337 return "char v%d[%d];\n" % (idx, self.string_size)
338 if field_type in Probe.fmt_types:
339 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
340 self._bail("unrecognized format specifier %s" % field_type)
341
342 def _generate_data_decl(self):
343 # The BPF program will populate values into the struct
344 # according to the format string, and the Python program will
345 # construct the final display string.
346 self.events_name = "%s_events" % self.probe_name
347 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700348 self.stacks_name = "%s_stacks" % self.probe_name
349 stack_table = "BPF_STACK_TRACE(%s, 1024);" % self.stacks_name \
350 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800351 data_fields = ""
352 for i, field_type in enumerate(self.types):
353 data_fields += " " + \
354 self._generate_field_decl(i)
Teng Qinc200b6c2017-12-16 00:15:55 -0800355 time_str = "u64 timestamp_ns;" if self.time_field else ""
356 cpu_str = "int cpu;" if self.print_cpu else ""
Teng Qin6b0ed372016-09-29 21:30:13 -0700357 kernel_stack_str = " int kernel_stack_id;" \
358 if self.kernel_stack else ""
359 user_stack_str = " int user_stack_id;" \
360 if self.user_stack else ""
361
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800362 text = """
363struct %s
364{
Teng Qinc200b6c2017-12-16 00:15:55 -0800365%s
366%s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000367 u32 tgid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800368 u32 pid;
369 char comm[TASK_COMM_LEN];
370%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700371%s
372%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800373};
374
375BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700376%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800377"""
Teng Qinc200b6c2017-12-16 00:15:55 -0800378 return text % (self.struct_name, time_str, cpu_str, data_fields,
Teng Qin6b0ed372016-09-29 21:30:13 -0700379 kernel_stack_str, user_stack_str,
380 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800381
382 def _generate_field_assign(self, idx):
383 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300384 expr = self.values[idx].strip()
385 text = ""
386 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000387 arg_index = int(expr[3])
388 arg_ctype = self.usdt.get_probe_arg_ctype(
389 self.usdt_name, arg_index - 1)
390 text = (" %s %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300391 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000392 % (arg_ctype, expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300393
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800394 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300395 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800396 if (%s != 0) {
yonghong-song61484e12018-09-17 22:24:31 -0700397 void *__tmp = (void *)%s;
398 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), __tmp);
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800399 }
yonghong-song61484e12018-09-17 22:24:31 -0700400 """ % (expr, expr, idx, idx)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800401 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300402 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800403 (idx, Probe.c_type[field_type], expr)
404 self._bail("unrecognized field type %s" % field_type)
405
Teng Qin0615bff2016-09-28 08:19:40 -0700406 def _generate_usdt_filter_read(self):
407 text = ""
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000408 if self.probe_type != "u":
409 return text
yonghong-song2da34262018-06-13 06:12:22 -0700410 for arg, _ in Probe.aliases_arg.items():
411 if not (arg in self.filter):
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000412 continue
413 arg_index = int(arg.replace("arg", ""))
414 arg_ctype = self.usdt.get_probe_arg_ctype(
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000415 self.usdt_name, arg_index - 1)
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000416 if not arg_ctype:
417 self._bail("Unable to determine type of {} "
418 "in the filter".format(arg))
419 text += """
Teng Qin0615bff2016-09-28 08:19:40 -0700420 {} {}_filter;
421 bpf_usdt_readarg({}, ctx, &{}_filter);
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000422 """.format(arg_ctype, arg, arg_index, arg)
423 self.filter = self.filter.replace(
424 arg, "{}_filter".format(arg))
Teng Qin0615bff2016-09-28 08:19:40 -0700425 return text
426
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700427 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800428 data_decl = self._generate_data_decl()
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000429 if Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800430 pid_filter = """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800431 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300432 """ % Probe.pid
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000433 # uprobes can have a built-in tgid filter passed to
434 # attach_uprobe, hence the check here -- for kprobes, we
435 # need to do the tgid test by hand:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000436 elif len(self.library) == 0 and Probe.tgid != -1:
437 pid_filter = """
438 if (__tgid != %d) { return 0; }
439 """ % Probe.tgid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800440 elif not include_self:
441 pid_filter = """
Mark Draytonaa6c9162016-11-03 15:36:29 +0000442 if (__tgid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300443 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800444 else:
445 pid_filter = ""
446
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700447 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700448 signature = "struct pt_regs *ctx"
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000449 if self.signature:
450 signature += ", " + self.signature
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700451
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800452 data_fields = ""
453 for i, expr in enumerate(self.values):
454 data_fields += self._generate_field_assign(i)
455
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300456 if self.probe_type == "t":
457 heading = "TRACEPOINT_PROBE(%s, %s)" % \
458 (self.tp_category, self.tp_event)
459 ctx_name = "args"
460 else:
461 heading = "int %s(%s)" % (self.probe_name, signature)
462 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300463
Teng Qinc200b6c2017-12-16 00:15:55 -0800464 time_str = """
465 __data.timestamp_ns = bpf_ktime_get_ns();""" if self.time_field else ""
466 cpu_str = """
467 __data.cpu = bpf_get_smp_processor_id();""" if self.print_cpu else ""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300468 stack_trace = ""
469 if self.user_stack:
470 stack_trace += """
471 __data.user_stack_id = %s.get_stackid(
472 %s, BPF_F_REUSE_STACKID | BPF_F_USER_STACK
473 );""" % (self.stacks_name, ctx_name)
474 if self.kernel_stack:
475 stack_trace += """
476 __data.kernel_stack_id = %s.get_stackid(
477 %s, BPF_F_REUSE_STACKID
478 );""" % (self.stacks_name, ctx_name)
479
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300480 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800481{
Mark Draytonaa6c9162016-11-03 15:36:29 +0000482 u64 __pid_tgid = bpf_get_current_pid_tgid();
483 u32 __tgid = __pid_tgid >> 32;
484 u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800485 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800486 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700487 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800488 if (!(%s)) return 0;
489
490 struct %s __data = {0};
Teng Qinc200b6c2017-12-16 00:15:55 -0800491 %s
492 %s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000493 __data.tgid = __tgid;
494 __data.pid = __pid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800495 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
496%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700497%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300498 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800499 return 0;
500}
501"""
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300502 text = text % (pid_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700503 self._generate_usdt_filter_read(), self.filter,
Teng Qinc200b6c2017-12-16 00:15:55 -0800504 self.struct_name, time_str, cpu_str, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300505 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700506
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700507 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800508
509 @classmethod
510 def _time_off_str(cls, timestamp_ns):
511 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
512
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800513 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700514 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800515 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700516 elif self.probe_type == 'u':
517 return self.usdt_name
518 else: # self.probe_type == 't'
519 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800520
Mark Draytonaa6c9162016-11-03 15:36:29 +0000521 def print_stack(self, bpf, stack_id, tgid):
Teng Qin6b0ed372016-09-29 21:30:13 -0700522 if stack_id < 0:
Mirek Klimose5382282018-01-26 14:52:50 -0800523 print(" %d" % stack_id)
524 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700525
526 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
527 for addr in stack:
Mirek Klimose5382282018-01-26 14:52:50 -0800528 print(" ", end="")
529 if Probe.print_address:
530 print("%16x " % addr, end="")
531 print("%s" % (bpf.sym(addr, tgid,
532 show_module=True, show_offset=True)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700533
Mark Draytonaa6c9162016-11-03 15:36:29 +0000534 def _format_message(self, bpf, tgid, values):
535 # Replace each %K with kernel sym and %U with user sym in tgid
Rafael Fonsecaaee5ecf2017-02-08 16:14:31 +0100536 kernel_placeholders = [i for i, t in enumerate(self.types)
537 if t == 'K']
538 user_placeholders = [i for i, t in enumerate(self.types)
539 if t == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700540 for kp in kernel_placeholders:
Sasha Goldshtein01553852017-02-09 03:58:09 -0500541 values[kp] = bpf.ksym(values[kp], show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700542 for up in user_placeholders:
Sasha Goldshtein1e34f4e2017-02-09 00:21:49 -0500543 values[up] = bpf.sym(values[up], tgid,
Sasha Goldshtein01553852017-02-09 03:58:09 -0500544 show_module=True, show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700545 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700546
547 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800548 # Cast as the generated structure type and display
549 # according to the format string in the probe.
550 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
551 values = map(lambda i: getattr(event, "v%d" % i),
552 range(0, len(self.values)))
Mark Draytonaa6c9162016-11-03 15:36:29 +0000553 msg = self._format_message(bpf, event.tgid, values)
Teng Qinc200b6c2017-12-16 00:15:55 -0800554 if Probe.print_time:
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000555 time = strftime("%H:%M:%S") if Probe.use_localtime else \
556 Probe._time_off_str(event.timestamp_ns)
Teng Qinc200b6c2017-12-16 00:15:55 -0800557 print("%-8s " % time[:8], end="")
558 if Probe.print_cpu:
559 print("%-3s " % event.cpu, end="")
560 print("%-7d %-7d %-15s %-16s %s" %
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200561 (event.tgid, event.pid,
562 event.comm.decode('utf-8', 'replace'),
Teng Qinc200b6c2017-12-16 00:15:55 -0800563 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800564
Teng Qin6b0ed372016-09-29 21:30:13 -0700565 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700566 self.print_stack(bpf, event.kernel_stack_id, -1)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000567 if self.user_stack:
568 self.print_stack(bpf, event.user_stack_id, event.tgid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700569 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700570 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700571
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800572 Probe.event_count += 1
573 if Probe.max_events is not None and \
574 Probe.event_count >= Probe.max_events:
575 exit()
576
577 def attach(self, bpf, verbose):
578 if len(self.library) == 0:
579 self._attach_k(bpf)
580 else:
581 self._attach_u(bpf)
582 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700583 callback = partial(self.print_event, bpf)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000584 bpf[self.events_name].open_perf_buffer(callback,
585 page_cnt=self.page_cnt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800586
587 def _attach_k(self, bpf):
588 if self.probe_type == "r":
589 bpf.attach_kretprobe(event=self.function,
590 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300591 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800592 bpf.attach_kprobe(event=self.function,
593 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300594 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800595
596 def _attach_u(self, bpf):
597 libpath = BPF.find_library(self.library)
598 if libpath is None:
599 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300600 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800601 if libpath is None or len(libpath) == 0:
602 self._bail("unable to find library %s" % self.library)
603
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700604 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300605 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700606 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800607 bpf.attach_uretprobe(name=libpath,
608 sym=self.function,
609 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000610 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800611 else:
612 bpf.attach_uprobe(name=libpath,
613 sym=self.function,
614 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000615 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800616
617class Tool(object):
Mark Drayton5f5687e2017-02-20 18:13:03 +0000618 DEFAULT_PERF_BUFFER_PAGES = 64
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800619 examples = """
620EXAMPLES:
621
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800622trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800623 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800624trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800625 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800626trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800627 Trace the read syscall and print a message for reads >20000 bytes
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000628trace 'r::do_sys_open "%llx", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800629 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800630trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800631 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800632trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800633 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800634trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
635 Trace the write() call from libc to monitor writes to STDOUT
Mark Draytonaa6c9162016-11-03 15:36:29 +0000636trace 'r::__kmalloc (retval == 0) "kmalloc failed!"'
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800637 Trace returns from __kmalloc which returned a null pointer
Mark Draytonaa6c9162016-11-03 15:36:29 +0000638trace 'r:c:malloc (retval) "allocated = %x", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800639 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300640trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800641 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700642trace 'u:pthread:pthread_create (arg4 != 0)'
643 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000644trace 'p::SyS_nanosleep(struct timespec *ts) "sleep for %lld ns", ts->tv_nsec'
645 Trace the nanosleep syscall and print the sleep duration in ns
Yonghong Songf4470dc2017-12-13 14:12:13 -0800646trace -I 'linux/fs.h' \\
647 'p::uprobe_register(struct inode *inode) "a_ops = %llx", inode->i_mapping->a_ops'
648 Trace the uprobe_register inode mapping ops, and the symbol can be found
649 in /proc/kallsyms
650trace -I 'kernel/sched/sched.h' \\
651 'p::__account_cfs_rq_runtime(struct cfs_rq *cfs_rq) "%d", cfs_rq->runtime_remaining'
652 Trace the cfs scheduling runqueue remaining runtime. The struct cfs_rq is defined
653 in kernel/sched/sched.h which is in kernel source tree and not in kernel-devel
654 package. So this command needs to run at the kernel source tree root directory
655 so that the added header file can be found by the compiler.
tehnerd86293f02018-01-23 21:21:58 -0800656trace -I 'net/sock.h' \\
657 'udpv6_sendmsg(struct sock *sk) (sk->sk_dport == 13568)'
658 Trace udpv6 sendmsg calls only if socket's destination port is equal
659 to 53 (DNS; 13568 in big endian order)
Yonghong Songf92fef22018-01-24 20:51:46 -0800660trace -I 'linux/fs_struct.h' 'mntns_install "users = %d", $task->fs->users'
661 Trace the number of users accessing the file system of the current task
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800662"""
663
664 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300665 parser = argparse.ArgumentParser(description="Attach to " +
666 "functions and print trace messages.",
667 formatter_class=argparse.RawDescriptionHelpFormatter,
668 epilog=Tool.examples)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000669 parser.add_argument("-b", "--buffer-pages", type=int,
670 default=Tool.DEFAULT_PERF_BUFFER_PAGES,
671 help="number of pages to use for perf_events ring buffer "
672 "(default: %(default)d)")
Mark Draytonaa6c9162016-11-03 15:36:29 +0000673 # we'll refer to the userspace concepts of "pid" and "tid" by
674 # their kernel names -- tgid and pid -- inside the script
675 parser.add_argument("-p", "--pid", type=int, metavar="PID",
676 dest="tgid", help="id of the process to trace (optional)")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000677 parser.add_argument("-L", "--tid", type=int, metavar="TID",
Mark Draytonaa6c9162016-11-03 15:36:29 +0000678 dest="pid", help="id of the thread to trace (optional)")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800679 parser.add_argument("-v", "--verbose", action="store_true",
680 help="print resulting BPF program code before executing")
681 parser.add_argument("-Z", "--string-size", type=int,
682 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300683 parser.add_argument("-S", "--include-self",
684 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800685 help="do not filter trace's own pid from the trace")
686 parser.add_argument("-M", "--max-events", type=int,
687 help="number of events to print before quitting")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000688 parser.add_argument("-t", "--timestamp", action="store_true",
689 help="print timestamp column (offset from trace start)")
690 parser.add_argument("-T", "--time", action="store_true",
691 help="print time column")
Teng Qinc200b6c2017-12-16 00:15:55 -0800692 parser.add_argument("-C", "--print_cpu", action="store_true",
693 help="print CPU id")
Nikita V. Shirokov3953c702018-07-27 16:13:47 -0700694 parser.add_argument("-B", "--bin_cmp", action="store_true",
695 help="allow to use STRCMP with binary values")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300696 parser.add_argument("-K", "--kernel-stack",
697 action="store_true", help="output kernel stack trace")
698 parser.add_argument("-U", "--user-stack",
699 action="store_true", help="output user stack trace")
Mirek Klimose5382282018-01-26 14:52:50 -0800700 parser.add_argument("-a", "--address", action="store_true",
701 help="print virtual address in stacks")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800702 parser.add_argument(metavar="probe", dest="probes", nargs="+",
703 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300704 parser.add_argument("-I", "--include", action="append",
705 metavar="header",
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300706 help="additional header files to include in the BPF program "
Yonghong Songf4470dc2017-12-13 14:12:13 -0800707 "as either full path, "
708 "or relative to current working directory, "
709 "or relative to default kernel header search path")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100710 parser.add_argument("--ebpf", action="store_true",
711 help=argparse.SUPPRESS)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800712 self.args = parser.parse_args()
Mark Draytonaa6c9162016-11-03 15:36:29 +0000713 if self.args.tgid and self.args.pid:
Yonghong Songf4470dc2017-12-13 14:12:13 -0800714 parser.error("only one of -p and -L may be specified")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800715
716 def _create_probes(self):
717 Probe.configure(self.args)
718 self.probes = []
719 for probe_spec in self.args.probes:
720 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700721 probe_spec, self.args.string_size,
722 self.args.kernel_stack, self.args.user_stack))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800723
724 def _generate_program(self):
725 self.program = """
726#include <linux/ptrace.h>
727#include <linux/sched.h> /* For TASK_COMM_LEN */
728
729"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300730 for include in (self.args.include or []):
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300731 if include.startswith((".", "/")):
732 include = os.path.abspath(include)
733 self.program += "#include \"%s\"\n" % include
734 else:
735 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700736 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800737 map(lambda p: p.raw_probe, self.probes))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800738 for probe in self.probes:
739 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700740 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800741
Nathan Scottcf0792f2018-02-02 16:56:50 +1100742 if self.args.verbose or self.args.ebpf:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800743 print(self.program)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100744 if self.args.ebpf:
745 exit()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800746
747 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300748 usdt_contexts = []
749 for probe in self.probes:
750 if probe.usdt:
751 # USDT probes must be enabled before the BPF object
752 # is initialized, because that's where the actual
753 # uprobe is being attached.
754 probe.usdt.enable_probe(
755 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300756 if self.args.verbose:
757 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300758 usdt_contexts.append(probe.usdt)
759 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800760 for probe in self.probes:
761 if self.args.verbose:
762 print(probe)
763 probe.attach(self.bpf, self.args.verbose)
764
765 def _main_loop(self):
766 all_probes_trivial = all(map(Probe.is_default_action,
767 self.probes))
768
769 # Print header
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000770 if self.args.timestamp or self.args.time:
Teng Qinc200b6c2017-12-16 00:15:55 -0800771 print("%-8s " % "TIME", end="");
772 if self.args.print_cpu:
773 print("%-3s " % "CPU", end="");
774 print("%-7s %-7s %-15s %-16s %s" %
775 ("PID", "TID", "COMM", "FUNC",
776 "-" if not all_probes_trivial else ""))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800777
778 while True:
Teng Qindbf00292018-02-28 21:47:50 -0800779 self.bpf.perf_buffer_poll()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800780
781 def run(self):
782 try:
783 self._create_probes()
784 self._generate_program()
785 self._attach_probes()
786 self._main_loop()
787 except:
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500788 exc_info = sys.exc_info()
789 sys_exit = exc_info[0] is SystemExit
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800790 if self.args.verbose:
791 traceback.print_exc()
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500792 elif not sys_exit:
793 print(exc_info[1])
794 exit(0 if sys_exit else 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800795
796if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300797 Tool().run()