blob: 051ba9b083e3f6da1566122b8d1500827b94e528 [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(
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300183 r'[^%]%(s|u|d|llu|lld|hu|hd|x|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800184 self.types.append(match.group(1))
185 fmt = re.sub(r'([^%]%)(u|d|llu|lld|hu|hd)', r'\1d', fmt)
186 fmt = re.sub(r'([^%]%)(x|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
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300286 p_type = {"u": ct.c_uint, "d": ct.c_int,
287 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
288 "hu": ct.c_ushort, "hd": ct.c_short,
289 "x": ct.c_uint, "llx": ct.c_ulonglong, "c": ct.c_ubyte,
290 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800291
292 def _generate_python_field_decl(self, idx, fields):
293 field_type = self.types[idx]
294 if field_type == "s":
295 ptype = ct.c_char * self.string_size
296 else:
297 ptype = Probe.p_type[field_type]
298 fields.append(("v%d" % idx, ptype))
299
300 def _generate_python_data_decl(self):
301 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700302 (self._display_function(), self.probe_num)
Teng Qinc200b6c2017-12-16 00:15:55 -0800303 fields = []
304 if self.time_field:
305 fields.append(("timestamp_ns", ct.c_ulonglong))
306 if self.print_cpu:
307 fields.append(("cpu", ct.c_int))
308 fields.extend([
Mark Draytonaa6c9162016-11-03 15:36:29 +0000309 ("tgid", ct.c_uint),
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800310 ("pid", ct.c_uint),
311 ("comm", ct.c_char * 16) # TASK_COMM_LEN
Teng Qinc200b6c2017-12-16 00:15:55 -0800312 ])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800313 for i in range(0, len(self.types)):
314 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700315 if self.kernel_stack:
316 fields.append(("kernel_stack_id", ct.c_int))
317 if self.user_stack:
318 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800319 return type(self.python_struct_name, (ct.Structure,),
320 dict(_fields_=fields))
321
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300322 c_type = {"u": "unsigned int", "d": "int",
323 "llu": "unsigned long long", "lld": "long long",
324 "hu": "unsigned short", "hd": "short",
325 "x": "unsigned int", "llx": "unsigned long long",
326 "c": "char", "K": "unsigned long long",
327 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800328 fmt_types = c_type.keys()
329
330 def _generate_field_decl(self, idx):
331 field_type = self.types[idx]
332 if field_type == "s":
333 return "char v%d[%d];\n" % (idx, self.string_size)
334 if field_type in Probe.fmt_types:
335 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
336 self._bail("unrecognized format specifier %s" % field_type)
337
338 def _generate_data_decl(self):
339 # The BPF program will populate values into the struct
340 # according to the format string, and the Python program will
341 # construct the final display string.
342 self.events_name = "%s_events" % self.probe_name
343 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700344 self.stacks_name = "%s_stacks" % self.probe_name
345 stack_table = "BPF_STACK_TRACE(%s, 1024);" % self.stacks_name \
346 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800347 data_fields = ""
348 for i, field_type in enumerate(self.types):
349 data_fields += " " + \
350 self._generate_field_decl(i)
Teng Qinc200b6c2017-12-16 00:15:55 -0800351 time_str = "u64 timestamp_ns;" if self.time_field else ""
352 cpu_str = "int cpu;" if self.print_cpu else ""
Teng Qin6b0ed372016-09-29 21:30:13 -0700353 kernel_stack_str = " int kernel_stack_id;" \
354 if self.kernel_stack else ""
355 user_stack_str = " int user_stack_id;" \
356 if self.user_stack else ""
357
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800358 text = """
359struct %s
360{
Teng Qinc200b6c2017-12-16 00:15:55 -0800361%s
362%s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000363 u32 tgid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800364 u32 pid;
365 char comm[TASK_COMM_LEN];
366%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700367%s
368%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800369};
370
371BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700372%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800373"""
Teng Qinc200b6c2017-12-16 00:15:55 -0800374 return text % (self.struct_name, time_str, cpu_str, data_fields,
Teng Qin6b0ed372016-09-29 21:30:13 -0700375 kernel_stack_str, user_stack_str,
376 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800377
378 def _generate_field_assign(self, idx):
379 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300380 expr = self.values[idx].strip()
381 text = ""
382 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000383 arg_index = int(expr[3])
384 arg_ctype = self.usdt.get_probe_arg_ctype(
385 self.usdt_name, arg_index - 1)
386 text = (" %s %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300387 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000388 % (arg_ctype, expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300389
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800390 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300391 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800392 if (%s != 0) {
393 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), (void *)%s);
394 }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300395 """ % (expr, idx, idx, expr)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800396 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300397 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800398 (idx, Probe.c_type[field_type], expr)
399 self._bail("unrecognized field type %s" % field_type)
400
Teng Qin0615bff2016-09-28 08:19:40 -0700401 def _generate_usdt_filter_read(self):
402 text = ""
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000403 if self.probe_type != "u":
404 return text
yonghong-song2da34262018-06-13 06:12:22 -0700405 for arg, _ in Probe.aliases_arg.items():
406 if not (arg in self.filter):
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000407 continue
408 arg_index = int(arg.replace("arg", ""))
409 arg_ctype = self.usdt.get_probe_arg_ctype(
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000410 self.usdt_name, arg_index - 1)
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000411 if not arg_ctype:
412 self._bail("Unable to determine type of {} "
413 "in the filter".format(arg))
414 text += """
Teng Qin0615bff2016-09-28 08:19:40 -0700415 {} {}_filter;
416 bpf_usdt_readarg({}, ctx, &{}_filter);
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000417 """.format(arg_ctype, arg, arg_index, arg)
418 self.filter = self.filter.replace(
419 arg, "{}_filter".format(arg))
Teng Qin0615bff2016-09-28 08:19:40 -0700420 return text
421
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700422 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800423 data_decl = self._generate_data_decl()
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000424 if Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800425 pid_filter = """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800426 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300427 """ % Probe.pid
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000428 # uprobes can have a built-in tgid filter passed to
429 # attach_uprobe, hence the check here -- for kprobes, we
430 # need to do the tgid test by hand:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000431 elif len(self.library) == 0 and Probe.tgid != -1:
432 pid_filter = """
433 if (__tgid != %d) { return 0; }
434 """ % Probe.tgid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800435 elif not include_self:
436 pid_filter = """
Mark Draytonaa6c9162016-11-03 15:36:29 +0000437 if (__tgid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300438 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800439 else:
440 pid_filter = ""
441
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700442 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700443 signature = "struct pt_regs *ctx"
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000444 if self.signature:
445 signature += ", " + self.signature
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700446
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800447 data_fields = ""
448 for i, expr in enumerate(self.values):
449 data_fields += self._generate_field_assign(i)
450
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300451 if self.probe_type == "t":
452 heading = "TRACEPOINT_PROBE(%s, %s)" % \
453 (self.tp_category, self.tp_event)
454 ctx_name = "args"
455 else:
456 heading = "int %s(%s)" % (self.probe_name, signature)
457 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300458
Teng Qinc200b6c2017-12-16 00:15:55 -0800459 time_str = """
460 __data.timestamp_ns = bpf_ktime_get_ns();""" if self.time_field else ""
461 cpu_str = """
462 __data.cpu = bpf_get_smp_processor_id();""" if self.print_cpu else ""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300463 stack_trace = ""
464 if self.user_stack:
465 stack_trace += """
466 __data.user_stack_id = %s.get_stackid(
467 %s, BPF_F_REUSE_STACKID | BPF_F_USER_STACK
468 );""" % (self.stacks_name, ctx_name)
469 if self.kernel_stack:
470 stack_trace += """
471 __data.kernel_stack_id = %s.get_stackid(
472 %s, BPF_F_REUSE_STACKID
473 );""" % (self.stacks_name, ctx_name)
474
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300475 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800476{
Mark Draytonaa6c9162016-11-03 15:36:29 +0000477 u64 __pid_tgid = bpf_get_current_pid_tgid();
478 u32 __tgid = __pid_tgid >> 32;
479 u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800480 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800481 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700482 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800483 if (!(%s)) return 0;
484
485 struct %s __data = {0};
Teng Qinc200b6c2017-12-16 00:15:55 -0800486 %s
487 %s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000488 __data.tgid = __tgid;
489 __data.pid = __pid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800490 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
491%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700492%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300493 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800494 return 0;
495}
496"""
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300497 text = text % (pid_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700498 self._generate_usdt_filter_read(), self.filter,
Teng Qinc200b6c2017-12-16 00:15:55 -0800499 self.struct_name, time_str, cpu_str, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300500 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700501
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700502 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800503
504 @classmethod
505 def _time_off_str(cls, timestamp_ns):
506 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
507
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800508 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700509 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800510 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700511 elif self.probe_type == 'u':
512 return self.usdt_name
513 else: # self.probe_type == 't'
514 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800515
Mark Draytonaa6c9162016-11-03 15:36:29 +0000516 def print_stack(self, bpf, stack_id, tgid):
Teng Qin6b0ed372016-09-29 21:30:13 -0700517 if stack_id < 0:
Mirek Klimose5382282018-01-26 14:52:50 -0800518 print(" %d" % stack_id)
519 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700520
521 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
522 for addr in stack:
Mirek Klimose5382282018-01-26 14:52:50 -0800523 print(" ", end="")
524 if Probe.print_address:
525 print("%16x " % addr, end="")
526 print("%s" % (bpf.sym(addr, tgid,
527 show_module=True, show_offset=True)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700528
Mark Draytonaa6c9162016-11-03 15:36:29 +0000529 def _format_message(self, bpf, tgid, values):
530 # Replace each %K with kernel sym and %U with user sym in tgid
Rafael Fonsecaaee5ecf2017-02-08 16:14:31 +0100531 kernel_placeholders = [i for i, t in enumerate(self.types)
532 if t == 'K']
533 user_placeholders = [i for i, t in enumerate(self.types)
534 if t == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700535 for kp in kernel_placeholders:
Sasha Goldshtein01553852017-02-09 03:58:09 -0500536 values[kp] = bpf.ksym(values[kp], show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700537 for up in user_placeholders:
Sasha Goldshtein1e34f4e2017-02-09 00:21:49 -0500538 values[up] = bpf.sym(values[up], tgid,
Sasha Goldshtein01553852017-02-09 03:58:09 -0500539 show_module=True, show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700540 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700541
542 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800543 # Cast as the generated structure type and display
544 # according to the format string in the probe.
545 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
546 values = map(lambda i: getattr(event, "v%d" % i),
547 range(0, len(self.values)))
Mark Draytonaa6c9162016-11-03 15:36:29 +0000548 msg = self._format_message(bpf, event.tgid, values)
Teng Qinc200b6c2017-12-16 00:15:55 -0800549 if Probe.print_time:
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000550 time = strftime("%H:%M:%S") if Probe.use_localtime else \
551 Probe._time_off_str(event.timestamp_ns)
Teng Qinc200b6c2017-12-16 00:15:55 -0800552 print("%-8s " % time[:8], end="")
553 if Probe.print_cpu:
554 print("%-3s " % event.cpu, end="")
555 print("%-7d %-7d %-15s %-16s %s" %
556 (event.tgid, event.pid, event.comm.decode(),
557 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800558
Teng Qin6b0ed372016-09-29 21:30:13 -0700559 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700560 self.print_stack(bpf, event.kernel_stack_id, -1)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000561 if self.user_stack:
562 self.print_stack(bpf, event.user_stack_id, event.tgid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700563 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700564 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700565
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800566 Probe.event_count += 1
567 if Probe.max_events is not None and \
568 Probe.event_count >= Probe.max_events:
569 exit()
570
571 def attach(self, bpf, verbose):
572 if len(self.library) == 0:
573 self._attach_k(bpf)
574 else:
575 self._attach_u(bpf)
576 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700577 callback = partial(self.print_event, bpf)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000578 bpf[self.events_name].open_perf_buffer(callback,
579 page_cnt=self.page_cnt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800580
581 def _attach_k(self, bpf):
582 if self.probe_type == "r":
583 bpf.attach_kretprobe(event=self.function,
584 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300585 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800586 bpf.attach_kprobe(event=self.function,
587 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300588 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800589
590 def _attach_u(self, bpf):
591 libpath = BPF.find_library(self.library)
592 if libpath is None:
593 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300594 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800595 if libpath is None or len(libpath) == 0:
596 self._bail("unable to find library %s" % self.library)
597
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700598 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300599 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700600 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800601 bpf.attach_uretprobe(name=libpath,
602 sym=self.function,
603 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000604 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800605 else:
606 bpf.attach_uprobe(name=libpath,
607 sym=self.function,
608 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000609 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800610
611class Tool(object):
Mark Drayton5f5687e2017-02-20 18:13:03 +0000612 DEFAULT_PERF_BUFFER_PAGES = 64
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800613 examples = """
614EXAMPLES:
615
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800616trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800617 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800618trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800619 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800620trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800621 Trace the read syscall and print a message for reads >20000 bytes
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000622trace 'r::do_sys_open "%llx", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800623 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800624trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800625 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800626trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800627 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800628trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
629 Trace the write() call from libc to monitor writes to STDOUT
Mark Draytonaa6c9162016-11-03 15:36:29 +0000630trace 'r::__kmalloc (retval == 0) "kmalloc failed!"'
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800631 Trace returns from __kmalloc which returned a null pointer
Mark Draytonaa6c9162016-11-03 15:36:29 +0000632trace 'r:c:malloc (retval) "allocated = %x", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800633 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300634trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800635 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700636trace 'u:pthread:pthread_create (arg4 != 0)'
637 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000638trace 'p::SyS_nanosleep(struct timespec *ts) "sleep for %lld ns", ts->tv_nsec'
639 Trace the nanosleep syscall and print the sleep duration in ns
Yonghong Songf4470dc2017-12-13 14:12:13 -0800640trace -I 'linux/fs.h' \\
641 'p::uprobe_register(struct inode *inode) "a_ops = %llx", inode->i_mapping->a_ops'
642 Trace the uprobe_register inode mapping ops, and the symbol can be found
643 in /proc/kallsyms
644trace -I 'kernel/sched/sched.h' \\
645 'p::__account_cfs_rq_runtime(struct cfs_rq *cfs_rq) "%d", cfs_rq->runtime_remaining'
646 Trace the cfs scheduling runqueue remaining runtime. The struct cfs_rq is defined
647 in kernel/sched/sched.h which is in kernel source tree and not in kernel-devel
648 package. So this command needs to run at the kernel source tree root directory
649 so that the added header file can be found by the compiler.
tehnerd86293f02018-01-23 21:21:58 -0800650trace -I 'net/sock.h' \\
651 'udpv6_sendmsg(struct sock *sk) (sk->sk_dport == 13568)'
652 Trace udpv6 sendmsg calls only if socket's destination port is equal
653 to 53 (DNS; 13568 in big endian order)
Yonghong Songf92fef22018-01-24 20:51:46 -0800654trace -I 'linux/fs_struct.h' 'mntns_install "users = %d", $task->fs->users'
655 Trace the number of users accessing the file system of the current task
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800656"""
657
658 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300659 parser = argparse.ArgumentParser(description="Attach to " +
660 "functions and print trace messages.",
661 formatter_class=argparse.RawDescriptionHelpFormatter,
662 epilog=Tool.examples)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000663 parser.add_argument("-b", "--buffer-pages", type=int,
664 default=Tool.DEFAULT_PERF_BUFFER_PAGES,
665 help="number of pages to use for perf_events ring buffer "
666 "(default: %(default)d)")
Mark Draytonaa6c9162016-11-03 15:36:29 +0000667 # we'll refer to the userspace concepts of "pid" and "tid" by
668 # their kernel names -- tgid and pid -- inside the script
669 parser.add_argument("-p", "--pid", type=int, metavar="PID",
670 dest="tgid", help="id of the process to trace (optional)")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000671 parser.add_argument("-L", "--tid", type=int, metavar="TID",
Mark Draytonaa6c9162016-11-03 15:36:29 +0000672 dest="pid", help="id of the thread to trace (optional)")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800673 parser.add_argument("-v", "--verbose", action="store_true",
674 help="print resulting BPF program code before executing")
675 parser.add_argument("-Z", "--string-size", type=int,
676 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300677 parser.add_argument("-S", "--include-self",
678 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800679 help="do not filter trace's own pid from the trace")
680 parser.add_argument("-M", "--max-events", type=int,
681 help="number of events to print before quitting")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000682 parser.add_argument("-t", "--timestamp", action="store_true",
683 help="print timestamp column (offset from trace start)")
684 parser.add_argument("-T", "--time", action="store_true",
685 help="print time column")
Teng Qinc200b6c2017-12-16 00:15:55 -0800686 parser.add_argument("-C", "--print_cpu", action="store_true",
687 help="print CPU id")
Nikita V. Shirokov3953c702018-07-27 16:13:47 -0700688 parser.add_argument("-B", "--bin_cmp", action="store_true",
689 help="allow to use STRCMP with binary values")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300690 parser.add_argument("-K", "--kernel-stack",
691 action="store_true", help="output kernel stack trace")
692 parser.add_argument("-U", "--user-stack",
693 action="store_true", help="output user stack trace")
Mirek Klimose5382282018-01-26 14:52:50 -0800694 parser.add_argument("-a", "--address", action="store_true",
695 help="print virtual address in stacks")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800696 parser.add_argument(metavar="probe", dest="probes", nargs="+",
697 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300698 parser.add_argument("-I", "--include", action="append",
699 metavar="header",
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300700 help="additional header files to include in the BPF program "
Yonghong Songf4470dc2017-12-13 14:12:13 -0800701 "as either full path, "
702 "or relative to current working directory, "
703 "or relative to default kernel header search path")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100704 parser.add_argument("--ebpf", action="store_true",
705 help=argparse.SUPPRESS)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800706 self.args = parser.parse_args()
Mark Draytonaa6c9162016-11-03 15:36:29 +0000707 if self.args.tgid and self.args.pid:
Yonghong Songf4470dc2017-12-13 14:12:13 -0800708 parser.error("only one of -p and -L may be specified")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800709
710 def _create_probes(self):
711 Probe.configure(self.args)
712 self.probes = []
713 for probe_spec in self.args.probes:
714 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700715 probe_spec, self.args.string_size,
716 self.args.kernel_stack, self.args.user_stack))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800717
718 def _generate_program(self):
719 self.program = """
720#include <linux/ptrace.h>
721#include <linux/sched.h> /* For TASK_COMM_LEN */
722
723"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300724 for include in (self.args.include or []):
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300725 if include.startswith((".", "/")):
726 include = os.path.abspath(include)
727 self.program += "#include \"%s\"\n" % include
728 else:
729 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700730 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800731 map(lambda p: p.raw_probe, self.probes))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800732 for probe in self.probes:
733 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700734 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800735
Nathan Scottcf0792f2018-02-02 16:56:50 +1100736 if self.args.verbose or self.args.ebpf:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800737 print(self.program)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100738 if self.args.ebpf:
739 exit()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800740
741 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300742 usdt_contexts = []
743 for probe in self.probes:
744 if probe.usdt:
745 # USDT probes must be enabled before the BPF object
746 # is initialized, because that's where the actual
747 # uprobe is being attached.
748 probe.usdt.enable_probe(
749 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300750 if self.args.verbose:
751 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300752 usdt_contexts.append(probe.usdt)
753 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800754 for probe in self.probes:
755 if self.args.verbose:
756 print(probe)
757 probe.attach(self.bpf, self.args.verbose)
758
759 def _main_loop(self):
760 all_probes_trivial = all(map(Probe.is_default_action,
761 self.probes))
762
763 # Print header
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000764 if self.args.timestamp or self.args.time:
Teng Qinc200b6c2017-12-16 00:15:55 -0800765 print("%-8s " % "TIME", end="");
766 if self.args.print_cpu:
767 print("%-3s " % "CPU", end="");
768 print("%-7s %-7s %-15s %-16s %s" %
769 ("PID", "TID", "COMM", "FUNC",
770 "-" if not all_probes_trivial else ""))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800771
772 while True:
Teng Qindbf00292018-02-28 21:47:50 -0800773 self.bpf.perf_buffer_poll()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800774
775 def run(self):
776 try:
777 self._create_probes()
778 self._generate_program()
779 self._attach_probes()
780 self._main_loop()
781 except:
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500782 exc_info = sys.exc_info()
783 sys_exit = exc_info[0] is SystemExit
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800784 if self.args.verbose:
785 traceback.print_exc()
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500786 elif not sys_exit:
787 print(exc_info[1])
788 exit(0 if sys_exit else 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800789
790if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300791 Tool().run()