blob: 549fb20dcead4ec48dfedded334e61fc2137b942 [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
yonghong-song2da34262018-06-13 06:12:22 -070067 # compiler can generate proper codes for function
68 # signatures with "syscall__" prefix
69 if self.is_syscall_kprobe:
70 self.probe_name = "syscall__" + self.probe_name[6:]
71
Sasha Goldshtein38847f02016-02-22 02:19:24 -080072 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070073 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
74 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080075 self.types, self.values)
76
77 def is_default_action(self):
78 return self.python_format == ""
79
80 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070081 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080082 (self.raw_probe, error))
83
84 def _parse_probe(self):
85 text = self.raw_probe
86
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000087 # There might be a function signature preceding the actual
88 # filter/print part, or not. Find the probe specifier first --
89 # it ends with either a space or an open paren ( for the
90 # function signature part.
91 # opt. signature
92 # probespec | rest
93 # --------- ---------- --
94 (spec, sig, rest) = re.match(r'([^ \t\(]+)(\([^\(]*\))?(.*)',
95 text).groups()
Sasha Goldshtein38847f02016-02-22 02:19:24 -080096
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000097 self._parse_spec(spec)
Paul Chaignon956ca1c2017-03-04 20:07:56 +010098 # Remove the parens
99 self.signature = sig[1:-1] if sig else None
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000100 if self.signature and self.probe_type in ['u', 't']:
101 self._bail("USDT and tracepoint probes can't have " +
102 "a function signature; use arg1, arg2, " +
103 "... instead")
104
105 text = rest.lstrip()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800106 # If we now have a (, wait for the balanced closing ) and that
107 # will be the predicate
108 self.filter = None
109 if len(text) > 0 and text[0] == "(":
110 balance = 1
111 for i in range(1, len(text)):
112 if text[i] == "(":
113 balance += 1
114 if text[i] == ")":
115 balance -= 1
116 if balance == 0:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300117 self._parse_filter(text[:i + 1])
118 text = text[i + 1:]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800119 break
120 if self.filter is None:
121 self._bail("unmatched end of predicate")
122
123 if self.filter is None:
124 self.filter = "1"
125
126 # The remainder of the text is the printf action
127 self._parse_action(text.lstrip())
128
129 def _parse_spec(self, spec):
130 parts = spec.split(":")
131 # Two special cases: 'func' means 'p::func', 'lib:func' means
132 # 'p:lib:func'. Other combinations need to provide an empty
133 # value between delimiters, e.g. 'r::func' for a kretprobe on
134 # the function func.
135 if len(parts) == 1:
136 parts = ["p", "", parts[0]]
137 elif len(parts) == 2:
138 parts = ["p", parts[0], parts[1]]
139 if len(parts[0]) == 0:
140 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700141 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800142 self.probe_type = parts[0]
143 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700144 self._bail("probe type must be '', 'p', 't', 'r', " +
145 "or 'u', but got '%s'" % parts[0])
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800146 if self.probe_type == "t":
147 self.tp_category = parts[1]
148 self.tp_event = parts[2]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800149 self.library = "" # kernel
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300150 self.function = "" # from TRACEPOINT_PROBE
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700151 elif self.probe_type == "u":
vkhromov5a2b39e2017-07-14 20:42:29 +0100152 self.library = ':'.join(parts[1:-1])
153 self.usdt_name = parts[-1]
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700154 self.function = "" # no function, just address
155 # We will discover the USDT provider by matching on
156 # the USDT name in the specified library
157 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800158 else:
vkhromov5a2b39e2017-07-14 20:42:29 +0100159 self.library = ':'.join(parts[1:-1])
160 self.function = parts[-1]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800161
yonghong-song2da34262018-06-13 06:12:22 -0700162 # only x64 syscalls needs checking, no other syscall wrapper yet.
163 self.is_syscall_kprobe = False
164 if self.probe_type == "p" and len(self.library) == 0 and \
165 self.function[:10] == "__x64_sys_":
166 self.is_syscall_kprobe = True
167
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700168 def _find_usdt_probe(self):
Sasha Goldshteindd045362016-11-13 05:07:38 -0800169 target = Probe.pid if Probe.pid and Probe.pid != -1 \
170 else Probe.tgid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000171 self.usdt = USDT(path=self.library, pid=target)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300172 for probe in self.usdt.enumerate_probes():
Javier Honduvilla Coto1ef82e22018-04-19 14:14:24 +0200173 if probe.name == self.usdt_name.encode('ascii'):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300174 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700175 self._bail("unrecognized USDT probe %s" % self.usdt_name)
176
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800177 def _parse_filter(self, filt):
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700178 self.filter = self._rewrite_expr(filt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800179
180 def _parse_types(self, fmt):
181 for match in re.finditer(
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300182 r'[^%]%(s|u|d|llu|lld|hu|hd|x|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800183 self.types.append(match.group(1))
184 fmt = re.sub(r'([^%]%)(u|d|llu|lld|hu|hd)', r'\1d', fmt)
185 fmt = re.sub(r'([^%]%)(x|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700186 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800187 self.python_format = fmt.strip('"')
188
189 def _parse_action(self, action):
190 self.values = []
191 self.types = []
192 self.python_format = ""
193 if len(action) == 0:
194 return
195
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800196 action = action.strip()
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700197 match = re.search(r'(\".*?\"),?(.*)', action)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800198 if match is None:
199 self._bail("expected format string in \"s")
200
201 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800202 self._parse_types(self.raw_format)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700203 for part in re.split('(?<!"),', match.group(2)):
204 part = self._rewrite_expr(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800205 if len(part) > 0:
206 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800207
yonghong-song2da34262018-06-13 06:12:22 -0700208 aliases_arg = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530209 "arg1": "PT_REGS_PARM1(ctx)",
210 "arg2": "PT_REGS_PARM2(ctx)",
211 "arg3": "PT_REGS_PARM3(ctx)",
212 "arg4": "PT_REGS_PARM4(ctx)",
213 "arg5": "PT_REGS_PARM5(ctx)",
214 "arg6": "PT_REGS_PARM6(ctx)",
yonghong-song2da34262018-06-13 06:12:22 -0700215 }
216
217 aliases_indarg = {
218 "arg1": "({u64 _val; struct pt_regs *_ctx = PT_REGS_PARM1(ctx);"
219 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM1(_ctx))); _val;})",
220 "arg2": "({u64 _val; struct pt_regs *_ctx = PT_REGS_PARM2(ctx);"
221 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM2(_ctx))); _val;})",
222 "arg3": "({u64 _val; struct pt_regs *_ctx = PT_REGS_PARM3(ctx);"
223 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM3(_ctx))); _val;})",
224 "arg4": "({u64 _val; struct pt_regs *_ctx = PT_REGS_PARM4(ctx);"
225 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM4(_ctx))); _val;})",
226 "arg5": "({u64 _val; struct pt_regs *_ctx = PT_REGS_PARM5(ctx);"
227 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM5(_ctx))); _val;})",
228 "arg6": "({u64 _val; struct pt_regs *_ctx = PT_REGS_PARM6(ctx);"
229 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM6(_ctx))); _val;})",
230 }
231
232 aliases_common = {
233 "retval": "PT_REGS_RC(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800234 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
235 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
236 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
237 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
Yonghong Songf92fef22018-01-24 20:51:46 -0800238 "$cpu": "bpf_get_smp_processor_id()",
239 "$task" : "((struct task_struct *)bpf_get_current_task())"
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800240 }
241
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700242 def _generate_streq_function(self, string):
243 fname = "streq_%d" % Probe.streq_index
244 Probe.streq_index += 1
245 self.streq_functions += """
Sasha Goldshteinb9aec342017-01-16 18:41:22 +0000246static inline bool %s(char const *ignored, uintptr_t str) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700247 char needle[] = %s;
248 char haystack[sizeof(needle)];
249 bpf_probe_read(&haystack, sizeof(haystack), (void *)str);
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000250 for (int i = 0; i < sizeof(needle) - 1; ++i) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700251 if (needle[i] != haystack[i]) {
252 return false;
253 }
254 }
255 return true;
256}
257 """ % (fname, string)
258 return fname
259
260 def _rewrite_expr(self, expr):
yonghong-song2da34262018-06-13 06:12:22 -0700261 if self.is_syscall_kprobe:
262 for alias, replacement in Probe.aliases_indarg.items():
263 expr = expr.replace(alias, replacement)
264 else:
265 for alias, replacement in Probe.aliases_arg.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700266 # For USDT probes, we replace argN values with the
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300267 # actual arguments for that probe obtained using
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300268 # bpf_readarg_N macros emitted at BPF construction.
yonghong-song2da34262018-06-13 06:12:22 -0700269 if self.probe_type == "u":
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700270 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800271 expr = expr.replace(alias, replacement)
yonghong-song2da34262018-06-13 06:12:22 -0700272 for alias, replacement in Probe.aliases_common.items():
273 expr = expr.replace(alias, replacement)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700274 matches = re.finditer('STRCMP\\(("[^"]+\\")', expr)
275 for match in matches:
276 string = match.group(1)
277 fname = self._generate_streq_function(string)
278 expr = expr.replace("STRCMP", fname, 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800279 return expr
280
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300281 p_type = {"u": ct.c_uint, "d": ct.c_int,
282 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
283 "hu": ct.c_ushort, "hd": ct.c_short,
284 "x": ct.c_uint, "llx": ct.c_ulonglong, "c": ct.c_ubyte,
285 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800286
287 def _generate_python_field_decl(self, idx, fields):
288 field_type = self.types[idx]
289 if field_type == "s":
290 ptype = ct.c_char * self.string_size
291 else:
292 ptype = Probe.p_type[field_type]
293 fields.append(("v%d" % idx, ptype))
294
295 def _generate_python_data_decl(self):
296 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700297 (self._display_function(), self.probe_num)
Teng Qinc200b6c2017-12-16 00:15:55 -0800298 fields = []
299 if self.time_field:
300 fields.append(("timestamp_ns", ct.c_ulonglong))
301 if self.print_cpu:
302 fields.append(("cpu", ct.c_int))
303 fields.extend([
Mark Draytonaa6c9162016-11-03 15:36:29 +0000304 ("tgid", ct.c_uint),
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800305 ("pid", ct.c_uint),
306 ("comm", ct.c_char * 16) # TASK_COMM_LEN
Teng Qinc200b6c2017-12-16 00:15:55 -0800307 ])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800308 for i in range(0, len(self.types)):
309 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700310 if self.kernel_stack:
311 fields.append(("kernel_stack_id", ct.c_int))
312 if self.user_stack:
313 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800314 return type(self.python_struct_name, (ct.Structure,),
315 dict(_fields_=fields))
316
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300317 c_type = {"u": "unsigned int", "d": "int",
318 "llu": "unsigned long long", "lld": "long long",
319 "hu": "unsigned short", "hd": "short",
320 "x": "unsigned int", "llx": "unsigned long long",
321 "c": "char", "K": "unsigned long long",
322 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800323 fmt_types = c_type.keys()
324
325 def _generate_field_decl(self, idx):
326 field_type = self.types[idx]
327 if field_type == "s":
328 return "char v%d[%d];\n" % (idx, self.string_size)
329 if field_type in Probe.fmt_types:
330 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
331 self._bail("unrecognized format specifier %s" % field_type)
332
333 def _generate_data_decl(self):
334 # The BPF program will populate values into the struct
335 # according to the format string, and the Python program will
336 # construct the final display string.
337 self.events_name = "%s_events" % self.probe_name
338 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700339 self.stacks_name = "%s_stacks" % self.probe_name
340 stack_table = "BPF_STACK_TRACE(%s, 1024);" % self.stacks_name \
341 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800342 data_fields = ""
343 for i, field_type in enumerate(self.types):
344 data_fields += " " + \
345 self._generate_field_decl(i)
Teng Qinc200b6c2017-12-16 00:15:55 -0800346 time_str = "u64 timestamp_ns;" if self.time_field else ""
347 cpu_str = "int cpu;" if self.print_cpu else ""
Teng Qin6b0ed372016-09-29 21:30:13 -0700348 kernel_stack_str = " int kernel_stack_id;" \
349 if self.kernel_stack else ""
350 user_stack_str = " int user_stack_id;" \
351 if self.user_stack else ""
352
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800353 text = """
354struct %s
355{
Teng Qinc200b6c2017-12-16 00:15:55 -0800356%s
357%s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000358 u32 tgid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800359 u32 pid;
360 char comm[TASK_COMM_LEN];
361%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700362%s
363%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800364};
365
366BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700367%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800368"""
Teng Qinc200b6c2017-12-16 00:15:55 -0800369 return text % (self.struct_name, time_str, cpu_str, data_fields,
Teng Qin6b0ed372016-09-29 21:30:13 -0700370 kernel_stack_str, user_stack_str,
371 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800372
373 def _generate_field_assign(self, idx):
374 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300375 expr = self.values[idx].strip()
376 text = ""
377 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000378 arg_index = int(expr[3])
379 arg_ctype = self.usdt.get_probe_arg_ctype(
380 self.usdt_name, arg_index - 1)
381 text = (" %s %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300382 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000383 % (arg_ctype, expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300384
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800385 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300386 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800387 if (%s != 0) {
388 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), (void *)%s);
389 }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300390 """ % (expr, idx, idx, expr)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800391 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300392 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800393 (idx, Probe.c_type[field_type], expr)
394 self._bail("unrecognized field type %s" % field_type)
395
Teng Qin0615bff2016-09-28 08:19:40 -0700396 def _generate_usdt_filter_read(self):
397 text = ""
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000398 if self.probe_type != "u":
399 return text
yonghong-song2da34262018-06-13 06:12:22 -0700400 for arg, _ in Probe.aliases_arg.items():
401 if not (arg in self.filter):
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000402 continue
403 arg_index = int(arg.replace("arg", ""))
404 arg_ctype = self.usdt.get_probe_arg_ctype(
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000405 self.usdt_name, arg_index - 1)
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000406 if not arg_ctype:
407 self._bail("Unable to determine type of {} "
408 "in the filter".format(arg))
409 text += """
Teng Qin0615bff2016-09-28 08:19:40 -0700410 {} {}_filter;
411 bpf_usdt_readarg({}, ctx, &{}_filter);
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000412 """.format(arg_ctype, arg, arg_index, arg)
413 self.filter = self.filter.replace(
414 arg, "{}_filter".format(arg))
Teng Qin0615bff2016-09-28 08:19:40 -0700415 return text
416
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700417 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800418 data_decl = self._generate_data_decl()
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000419 if Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800420 pid_filter = """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800421 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300422 """ % Probe.pid
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000423 # uprobes can have a built-in tgid filter passed to
424 # attach_uprobe, hence the check here -- for kprobes, we
425 # need to do the tgid test by hand:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000426 elif len(self.library) == 0 and Probe.tgid != -1:
427 pid_filter = """
428 if (__tgid != %d) { return 0; }
429 """ % Probe.tgid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800430 elif not include_self:
431 pid_filter = """
Mark Draytonaa6c9162016-11-03 15:36:29 +0000432 if (__tgid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300433 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800434 else:
435 pid_filter = ""
436
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700437 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700438 signature = "struct pt_regs *ctx"
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000439 if self.signature:
440 signature += ", " + self.signature
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700441
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800442 data_fields = ""
443 for i, expr in enumerate(self.values):
444 data_fields += self._generate_field_assign(i)
445
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300446 if self.probe_type == "t":
447 heading = "TRACEPOINT_PROBE(%s, %s)" % \
448 (self.tp_category, self.tp_event)
449 ctx_name = "args"
450 else:
451 heading = "int %s(%s)" % (self.probe_name, signature)
452 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300453
Teng Qinc200b6c2017-12-16 00:15:55 -0800454 time_str = """
455 __data.timestamp_ns = bpf_ktime_get_ns();""" if self.time_field else ""
456 cpu_str = """
457 __data.cpu = bpf_get_smp_processor_id();""" if self.print_cpu else ""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300458 stack_trace = ""
459 if self.user_stack:
460 stack_trace += """
461 __data.user_stack_id = %s.get_stackid(
462 %s, BPF_F_REUSE_STACKID | BPF_F_USER_STACK
463 );""" % (self.stacks_name, ctx_name)
464 if self.kernel_stack:
465 stack_trace += """
466 __data.kernel_stack_id = %s.get_stackid(
467 %s, BPF_F_REUSE_STACKID
468 );""" % (self.stacks_name, ctx_name)
469
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300470 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800471{
Mark Draytonaa6c9162016-11-03 15:36:29 +0000472 u64 __pid_tgid = bpf_get_current_pid_tgid();
473 u32 __tgid = __pid_tgid >> 32;
474 u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800475 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800476 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700477 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800478 if (!(%s)) return 0;
479
480 struct %s __data = {0};
Teng Qinc200b6c2017-12-16 00:15:55 -0800481 %s
482 %s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000483 __data.tgid = __tgid;
484 __data.pid = __pid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800485 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
486%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700487%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300488 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800489 return 0;
490}
491"""
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300492 text = text % (pid_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700493 self._generate_usdt_filter_read(), self.filter,
Teng Qinc200b6c2017-12-16 00:15:55 -0800494 self.struct_name, time_str, cpu_str, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300495 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700496
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700497 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800498
499 @classmethod
500 def _time_off_str(cls, timestamp_ns):
501 return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts))
502
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800503 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700504 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800505 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700506 elif self.probe_type == 'u':
507 return self.usdt_name
508 else: # self.probe_type == 't'
509 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800510
Mark Draytonaa6c9162016-11-03 15:36:29 +0000511 def print_stack(self, bpf, stack_id, tgid):
Teng Qin6b0ed372016-09-29 21:30:13 -0700512 if stack_id < 0:
Mirek Klimose5382282018-01-26 14:52:50 -0800513 print(" %d" % stack_id)
514 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700515
516 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
517 for addr in stack:
Mirek Klimose5382282018-01-26 14:52:50 -0800518 print(" ", end="")
519 if Probe.print_address:
520 print("%16x " % addr, end="")
521 print("%s" % (bpf.sym(addr, tgid,
522 show_module=True, show_offset=True)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700523
Mark Draytonaa6c9162016-11-03 15:36:29 +0000524 def _format_message(self, bpf, tgid, values):
525 # Replace each %K with kernel sym and %U with user sym in tgid
Rafael Fonsecaaee5ecf2017-02-08 16:14:31 +0100526 kernel_placeholders = [i for i, t in enumerate(self.types)
527 if t == 'K']
528 user_placeholders = [i for i, t in enumerate(self.types)
529 if t == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700530 for kp in kernel_placeholders:
Sasha Goldshtein01553852017-02-09 03:58:09 -0500531 values[kp] = bpf.ksym(values[kp], show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700532 for up in user_placeholders:
Sasha Goldshtein1e34f4e2017-02-09 00:21:49 -0500533 values[up] = bpf.sym(values[up], tgid,
Sasha Goldshtein01553852017-02-09 03:58:09 -0500534 show_module=True, show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700535 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700536
537 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800538 # Cast as the generated structure type and display
539 # according to the format string in the probe.
540 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
541 values = map(lambda i: getattr(event, "v%d" % i),
542 range(0, len(self.values)))
Mark Draytonaa6c9162016-11-03 15:36:29 +0000543 msg = self._format_message(bpf, event.tgid, values)
Teng Qinc200b6c2017-12-16 00:15:55 -0800544 if Probe.print_time:
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000545 time = strftime("%H:%M:%S") if Probe.use_localtime else \
546 Probe._time_off_str(event.timestamp_ns)
Teng Qinc200b6c2017-12-16 00:15:55 -0800547 print("%-8s " % time[:8], end="")
548 if Probe.print_cpu:
549 print("%-3s " % event.cpu, end="")
550 print("%-7d %-7d %-15s %-16s %s" %
551 (event.tgid, event.pid, event.comm.decode(),
552 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800553
Teng Qin6b0ed372016-09-29 21:30:13 -0700554 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700555 self.print_stack(bpf, event.kernel_stack_id, -1)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000556 if self.user_stack:
557 self.print_stack(bpf, event.user_stack_id, event.tgid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700558 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700559 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700560
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800561 Probe.event_count += 1
562 if Probe.max_events is not None and \
563 Probe.event_count >= Probe.max_events:
564 exit()
565
566 def attach(self, bpf, verbose):
567 if len(self.library) == 0:
568 self._attach_k(bpf)
569 else:
570 self._attach_u(bpf)
571 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700572 callback = partial(self.print_event, bpf)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000573 bpf[self.events_name].open_perf_buffer(callback,
574 page_cnt=self.page_cnt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800575
576 def _attach_k(self, bpf):
577 if self.probe_type == "r":
578 bpf.attach_kretprobe(event=self.function,
579 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300580 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800581 bpf.attach_kprobe(event=self.function,
582 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300583 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800584
585 def _attach_u(self, bpf):
586 libpath = BPF.find_library(self.library)
587 if libpath is None:
588 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300589 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800590 if libpath is None or len(libpath) == 0:
591 self._bail("unable to find library %s" % self.library)
592
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700593 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300594 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700595 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800596 bpf.attach_uretprobe(name=libpath,
597 sym=self.function,
598 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000599 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800600 else:
601 bpf.attach_uprobe(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
606class Tool(object):
Mark Drayton5f5687e2017-02-20 18:13:03 +0000607 DEFAULT_PERF_BUFFER_PAGES = 64
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800608 examples = """
609EXAMPLES:
610
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800611trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800612 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800613trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800614 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800615trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800616 Trace the read syscall and print a message for reads >20000 bytes
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000617trace 'r::do_sys_open "%llx", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800618 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800619trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800620 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800621trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800622 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800623trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
624 Trace the write() call from libc to monitor writes to STDOUT
Mark Draytonaa6c9162016-11-03 15:36:29 +0000625trace 'r::__kmalloc (retval == 0) "kmalloc failed!"'
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800626 Trace returns from __kmalloc which returned a null pointer
Mark Draytonaa6c9162016-11-03 15:36:29 +0000627trace 'r:c:malloc (retval) "allocated = %x", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800628 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300629trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800630 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700631trace 'u:pthread:pthread_create (arg4 != 0)'
632 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000633trace 'p::SyS_nanosleep(struct timespec *ts) "sleep for %lld ns", ts->tv_nsec'
634 Trace the nanosleep syscall and print the sleep duration in ns
Yonghong Songf4470dc2017-12-13 14:12:13 -0800635trace -I 'linux/fs.h' \\
636 'p::uprobe_register(struct inode *inode) "a_ops = %llx", inode->i_mapping->a_ops'
637 Trace the uprobe_register inode mapping ops, and the symbol can be found
638 in /proc/kallsyms
639trace -I 'kernel/sched/sched.h' \\
640 'p::__account_cfs_rq_runtime(struct cfs_rq *cfs_rq) "%d", cfs_rq->runtime_remaining'
641 Trace the cfs scheduling runqueue remaining runtime. The struct cfs_rq is defined
642 in kernel/sched/sched.h which is in kernel source tree and not in kernel-devel
643 package. So this command needs to run at the kernel source tree root directory
644 so that the added header file can be found by the compiler.
tehnerd86293f02018-01-23 21:21:58 -0800645trace -I 'net/sock.h' \\
646 'udpv6_sendmsg(struct sock *sk) (sk->sk_dport == 13568)'
647 Trace udpv6 sendmsg calls only if socket's destination port is equal
648 to 53 (DNS; 13568 in big endian order)
Yonghong Songf92fef22018-01-24 20:51:46 -0800649trace -I 'linux/fs_struct.h' 'mntns_install "users = %d", $task->fs->users'
650 Trace the number of users accessing the file system of the current task
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800651"""
652
653 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300654 parser = argparse.ArgumentParser(description="Attach to " +
655 "functions and print trace messages.",
656 formatter_class=argparse.RawDescriptionHelpFormatter,
657 epilog=Tool.examples)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000658 parser.add_argument("-b", "--buffer-pages", type=int,
659 default=Tool.DEFAULT_PERF_BUFFER_PAGES,
660 help="number of pages to use for perf_events ring buffer "
661 "(default: %(default)d)")
Mark Draytonaa6c9162016-11-03 15:36:29 +0000662 # we'll refer to the userspace concepts of "pid" and "tid" by
663 # their kernel names -- tgid and pid -- inside the script
664 parser.add_argument("-p", "--pid", type=int, metavar="PID",
665 dest="tgid", help="id of the process to trace (optional)")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000666 parser.add_argument("-L", "--tid", type=int, metavar="TID",
Mark Draytonaa6c9162016-11-03 15:36:29 +0000667 dest="pid", help="id of the thread to trace (optional)")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800668 parser.add_argument("-v", "--verbose", action="store_true",
669 help="print resulting BPF program code before executing")
670 parser.add_argument("-Z", "--string-size", type=int,
671 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300672 parser.add_argument("-S", "--include-self",
673 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800674 help="do not filter trace's own pid from the trace")
675 parser.add_argument("-M", "--max-events", type=int,
676 help="number of events to print before quitting")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000677 parser.add_argument("-t", "--timestamp", action="store_true",
678 help="print timestamp column (offset from trace start)")
679 parser.add_argument("-T", "--time", action="store_true",
680 help="print time column")
Teng Qinc200b6c2017-12-16 00:15:55 -0800681 parser.add_argument("-C", "--print_cpu", action="store_true",
682 help="print CPU id")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300683 parser.add_argument("-K", "--kernel-stack",
684 action="store_true", help="output kernel stack trace")
685 parser.add_argument("-U", "--user-stack",
686 action="store_true", help="output user stack trace")
Mirek Klimose5382282018-01-26 14:52:50 -0800687 parser.add_argument("-a", "--address", action="store_true",
688 help="print virtual address in stacks")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800689 parser.add_argument(metavar="probe", dest="probes", nargs="+",
690 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300691 parser.add_argument("-I", "--include", action="append",
692 metavar="header",
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300693 help="additional header files to include in the BPF program "
Yonghong Songf4470dc2017-12-13 14:12:13 -0800694 "as either full path, "
695 "or relative to current working directory, "
696 "or relative to default kernel header search path")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100697 parser.add_argument("--ebpf", action="store_true",
698 help=argparse.SUPPRESS)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800699 self.args = parser.parse_args()
Mark Draytonaa6c9162016-11-03 15:36:29 +0000700 if self.args.tgid and self.args.pid:
Yonghong Songf4470dc2017-12-13 14:12:13 -0800701 parser.error("only one of -p and -L may be specified")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800702
703 def _create_probes(self):
704 Probe.configure(self.args)
705 self.probes = []
706 for probe_spec in self.args.probes:
707 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700708 probe_spec, self.args.string_size,
709 self.args.kernel_stack, self.args.user_stack))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800710
711 def _generate_program(self):
712 self.program = """
713#include <linux/ptrace.h>
714#include <linux/sched.h> /* For TASK_COMM_LEN */
715
716"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300717 for include in (self.args.include or []):
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300718 if include.startswith((".", "/")):
719 include = os.path.abspath(include)
720 self.program += "#include \"%s\"\n" % include
721 else:
722 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700723 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800724 map(lambda p: p.raw_probe, self.probes))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800725 for probe in self.probes:
726 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700727 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800728
Nathan Scottcf0792f2018-02-02 16:56:50 +1100729 if self.args.verbose or self.args.ebpf:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800730 print(self.program)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100731 if self.args.ebpf:
732 exit()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800733
734 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300735 usdt_contexts = []
736 for probe in self.probes:
737 if probe.usdt:
738 # USDT probes must be enabled before the BPF object
739 # is initialized, because that's where the actual
740 # uprobe is being attached.
741 probe.usdt.enable_probe(
742 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300743 if self.args.verbose:
744 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300745 usdt_contexts.append(probe.usdt)
746 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800747 for probe in self.probes:
748 if self.args.verbose:
749 print(probe)
750 probe.attach(self.bpf, self.args.verbose)
751
752 def _main_loop(self):
753 all_probes_trivial = all(map(Probe.is_default_action,
754 self.probes))
755
756 # Print header
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000757 if self.args.timestamp or self.args.time:
Teng Qinc200b6c2017-12-16 00:15:55 -0800758 print("%-8s " % "TIME", end="");
759 if self.args.print_cpu:
760 print("%-3s " % "CPU", end="");
761 print("%-7s %-7s %-15s %-16s %s" %
762 ("PID", "TID", "COMM", "FUNC",
763 "-" if not all_probes_trivial else ""))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800764
765 while True:
Teng Qindbf00292018-02-28 21:47:50 -0800766 self.bpf.perf_buffer_poll()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800767
768 def run(self):
769 try:
770 self._create_probes()
771 self._generate_program()
772 self._attach_probes()
773 self._main_loop()
774 except:
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500775 exc_info = sys.exc_info()
776 sys_exit = exc_info[0] is SystemExit
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800777 if self.args.verbose:
778 traceback.print_exc()
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500779 elif not sys_exit:
780 print(exc_info[1])
781 exit(0 if sys_exit else 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800782
783if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300784 Tool().run()