blob: f406f7cae9e13d97953b2962f4558c9ba09fed54 [file] [log] [blame]
Alexey Ivanovcc01a9c2019-01-16 09:50:46 -08001#!/usr/bin/python
Sasha Goldshtein38847f02016-02-22 02:19:24 -08002#
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]
vijunag9924e642019-01-23 12:35:33 +05307# [-M MAX_EVENTS] [-s SYMBOLFILES] [-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
Maik Riechert3a0d3c42019-05-23 17:57:10 +010017import time
Sasha Goldshtein38847f02016-02-22 02:19:24 -080018import argparse
19import re
20import ctypes as ct
21import os
22import traceback
23import sys
24
Sasha Goldshtein38847f02016-02-22 02:19:24 -080025class Probe(object):
26 probe_count = 0
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070027 streq_index = 0
Sasha Goldshtein38847f02016-02-22 02:19:24 -080028 max_events = None
29 event_count = 0
30 first_ts = 0
Maik Riechert3a0d3c42019-05-23 17:57:10 +010031 first_ts_real = None
Teng Qinc200b6c2017-12-16 00:15:55 -080032 print_time = False
Maik Riechert3a0d3c42019-05-23 17:57:10 +010033 print_unix_timestamp = False
Sasha Goldshtein38847f02016-02-22 02:19:24 -080034 use_localtime = True
Teng Qinc200b6c2017-12-16 00:15:55 -080035 time_field = False
36 print_cpu = False
Mirek Klimose5382282018-01-26 14:52:50 -080037 print_address = False
Mark Draytonaa6c9162016-11-03 15:36:29 +000038 tgid = -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070039 pid = -1
Mark Drayton5f5687e2017-02-20 18:13:03 +000040 page_cnt = None
vijunag9924e642019-01-23 12:35:33 +053041 build_id_enabled = False
Sasha Goldshtein38847f02016-02-22 02:19:24 -080042
43 @classmethod
44 def configure(cls, args):
45 cls.max_events = args.max_events
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +000046 cls.print_time = args.timestamp or args.time
Maik Riechert3a0d3c42019-05-23 17:57:10 +010047 cls.print_unix_timestamp = args.unix_timestamp
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +000048 cls.use_localtime = not args.timestamp
Teng Qinc200b6c2017-12-16 00:15:55 -080049 cls.time_field = cls.print_time and (not cls.use_localtime)
50 cls.print_cpu = args.print_cpu
Mirek Klimose5382282018-01-26 14:52:50 -080051 cls.print_address = args.address
Sasha Goldshtein60c41922017-02-09 04:19:53 -050052 cls.first_ts = BPF.monotonic_time()
Maik Riechert3a0d3c42019-05-23 17:57:10 +010053 cls.first_ts_real = time.time()
Mark Draytonaa6c9162016-11-03 15:36:29 +000054 cls.tgid = args.tgid or -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070055 cls.pid = args.pid or -1
Mark Drayton5f5687e2017-02-20 18:13:03 +000056 cls.page_cnt = args.buffer_pages
Nikita V. Shirokov3953c702018-07-27 16:13:47 -070057 cls.bin_cmp = args.bin_cmp
vijunag9924e642019-01-23 12:35:33 +053058 cls.build_id_enabled = args.sym_file_list is not None
Sasha Goldshtein38847f02016-02-22 02:19:24 -080059
Teng Qin6b0ed372016-09-29 21:30:13 -070060 def __init__(self, probe, string_size, kernel_stack, user_stack):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +030061 self.usdt = None
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070062 self.streq_functions = ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -080063 self.raw_probe = probe
64 self.string_size = string_size
Teng Qin6b0ed372016-09-29 21:30:13 -070065 self.kernel_stack = kernel_stack
66 self.user_stack = user_stack
Sasha Goldshtein38847f02016-02-22 02:19:24 -080067 Probe.probe_count += 1
68 self._parse_probe()
69 self.probe_num = Probe.probe_count
70 self.probe_name = "probe_%s_%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070071 (self._display_function(), self.probe_num)
Paul Chaignon956ca1c2017-03-04 20:07:56 +010072 self.probe_name = re.sub(r'[^A-Za-z0-9_]', '_',
73 self.probe_name)
Sasha Goldshtein38847f02016-02-22 02:19:24 -080074
yonghong-song2da34262018-06-13 06:12:22 -070075 # compiler can generate proper codes for function
76 # signatures with "syscall__" prefix
77 if self.is_syscall_kprobe:
78 self.probe_name = "syscall__" + self.probe_name[6:]
79
Sasha Goldshtein38847f02016-02-22 02:19:24 -080080 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070081 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
82 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080083 self.types, self.values)
84
85 def is_default_action(self):
86 return self.python_format == ""
87
88 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070089 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080090 (self.raw_probe, error))
91
92 def _parse_probe(self):
93 text = self.raw_probe
94
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000095 # There might be a function signature preceding the actual
96 # filter/print part, or not. Find the probe specifier first --
97 # it ends with either a space or an open paren ( for the
98 # function signature part.
99 # opt. signature
100 # probespec | rest
101 # --------- ---------- --
102 (spec, sig, rest) = re.match(r'([^ \t\(]+)(\([^\(]*\))?(.*)',
103 text).groups()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800104
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000105 self._parse_spec(spec)
Paul Chaignon956ca1c2017-03-04 20:07:56 +0100106 # Remove the parens
107 self.signature = sig[1:-1] if sig else None
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000108 if self.signature and self.probe_type in ['u', 't']:
109 self._bail("USDT and tracepoint probes can't have " +
110 "a function signature; use arg1, arg2, " +
111 "... instead")
112
113 text = rest.lstrip()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800114 # If we now have a (, wait for the balanced closing ) and that
115 # will be the predicate
116 self.filter = None
117 if len(text) > 0 and text[0] == "(":
118 balance = 1
119 for i in range(1, len(text)):
120 if text[i] == "(":
121 balance += 1
122 if text[i] == ")":
123 balance -= 1
124 if balance == 0:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300125 self._parse_filter(text[:i + 1])
126 text = text[i + 1:]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800127 break
128 if self.filter is None:
129 self._bail("unmatched end of predicate")
130
131 if self.filter is None:
132 self.filter = "1"
133
134 # The remainder of the text is the printf action
135 self._parse_action(text.lstrip())
136
137 def _parse_spec(self, spec):
138 parts = spec.split(":")
139 # Two special cases: 'func' means 'p::func', 'lib:func' means
140 # 'p:lib:func'. Other combinations need to provide an empty
141 # value between delimiters, e.g. 'r::func' for a kretprobe on
142 # the function func.
143 if len(parts) == 1:
144 parts = ["p", "", parts[0]]
145 elif len(parts) == 2:
146 parts = ["p", parts[0], parts[1]]
147 if len(parts[0]) == 0:
148 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700149 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800150 self.probe_type = parts[0]
151 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700152 self._bail("probe type must be '', 'p', 't', 'r', " +
153 "or 'u', but got '%s'" % parts[0])
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800154 if self.probe_type == "t":
155 self.tp_category = parts[1]
156 self.tp_event = parts[2]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800157 self.library = "" # kernel
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300158 self.function = "" # from TRACEPOINT_PROBE
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700159 elif self.probe_type == "u":
vkhromov5a2b39e2017-07-14 20:42:29 +0100160 self.library = ':'.join(parts[1:-1])
161 self.usdt_name = parts[-1]
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700162 self.function = "" # no function, just address
163 # We will discover the USDT provider by matching on
164 # the USDT name in the specified library
165 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800166 else:
vkhromov5a2b39e2017-07-14 20:42:29 +0100167 self.library = ':'.join(parts[1:-1])
168 self.function = parts[-1]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800169
yonghong-song2da34262018-06-13 06:12:22 -0700170 # only x64 syscalls needs checking, no other syscall wrapper yet.
171 self.is_syscall_kprobe = False
172 if self.probe_type == "p" and len(self.library) == 0 and \
173 self.function[:10] == "__x64_sys_":
174 self.is_syscall_kprobe = True
175
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700176 def _find_usdt_probe(self):
Sasha Goldshteindd045362016-11-13 05:07:38 -0800177 target = Probe.pid if Probe.pid and Probe.pid != -1 \
178 else Probe.tgid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000179 self.usdt = USDT(path=self.library, pid=target)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300180 for probe in self.usdt.enumerate_probes():
Javier Honduvilla Coto1ef82e22018-04-19 14:14:24 +0200181 if probe.name == self.usdt_name.encode('ascii'):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300182 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700183 self._bail("unrecognized USDT probe %s" % self.usdt_name)
184
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800185 def _parse_filter(self, filt):
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700186 self.filter = self._rewrite_expr(filt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800187
188 def _parse_types(self, fmt):
189 for match in re.finditer(
yonghong-songf7202572018-09-19 08:50:59 -0700190 r'[^%]%(s|u|d|lu|llu|ld|lld|hu|hd|x|lx|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800191 self.types.append(match.group(1))
yonghong-songf7202572018-09-19 08:50:59 -0700192 fmt = re.sub(r'([^%]%)(u|d|lu|llu|ld|lld|hu|hd)', r'\1d', fmt)
193 fmt = re.sub(r'([^%]%)(x|lx|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700194 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800195 self.python_format = fmt.strip('"')
196
197 def _parse_action(self, action):
198 self.values = []
199 self.types = []
200 self.python_format = ""
201 if len(action) == 0:
202 return
203
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800204 action = action.strip()
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700205 match = re.search(r'(\".*?\"),?(.*)', action)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800206 if match is None:
207 self._bail("expected format string in \"s")
208
209 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800210 self._parse_types(self.raw_format)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700211 for part in re.split('(?<!"),', match.group(2)):
212 part = self._rewrite_expr(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800213 if len(part) > 0:
214 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800215
yonghong-song2da34262018-06-13 06:12:22 -0700216 aliases_arg = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530217 "arg1": "PT_REGS_PARM1(ctx)",
218 "arg2": "PT_REGS_PARM2(ctx)",
219 "arg3": "PT_REGS_PARM3(ctx)",
220 "arg4": "PT_REGS_PARM4(ctx)",
221 "arg5": "PT_REGS_PARM5(ctx)",
222 "arg6": "PT_REGS_PARM6(ctx)",
yonghong-song2da34262018-06-13 06:12:22 -0700223 }
224
225 aliases_indarg = {
Prashant Bhole05765ee2018-12-28 01:47:56 +0900226 "arg1": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700227 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM1(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800228 "arg2": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700229 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM2(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800230 "arg3": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700231 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM3(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800232 "arg4": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700233 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM4(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800234 "arg5": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700235 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM5(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800236 "arg6": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
yonghong-song2da34262018-06-13 06:12:22 -0700237 " bpf_probe_read(&_val, sizeof(_val), &(PT_REGS_PARM6(_ctx))); _val;})",
238 }
239
240 aliases_common = {
241 "retval": "PT_REGS_RC(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800242 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
243 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
244 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
245 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
Yonghong Songf92fef22018-01-24 20:51:46 -0800246 "$cpu": "bpf_get_smp_processor_id()",
247 "$task" : "((struct task_struct *)bpf_get_current_task())"
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800248 }
249
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700250 def _generate_streq_function(self, string):
251 fname = "streq_%d" % Probe.streq_index
252 Probe.streq_index += 1
253 self.streq_functions += """
Sasha Goldshteinb9aec342017-01-16 18:41:22 +0000254static inline bool %s(char const *ignored, uintptr_t str) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700255 char needle[] = %s;
256 char haystack[sizeof(needle)];
257 bpf_probe_read(&haystack, sizeof(haystack), (void *)str);
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000258 for (int i = 0; i < sizeof(needle) - 1; ++i) {
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700259 if (needle[i] != haystack[i]) {
260 return false;
261 }
262 }
263 return true;
264}
265 """ % (fname, string)
266 return fname
267
268 def _rewrite_expr(self, expr):
yonghong-song2da34262018-06-13 06:12:22 -0700269 if self.is_syscall_kprobe:
270 for alias, replacement in Probe.aliases_indarg.items():
271 expr = expr.replace(alias, replacement)
272 else:
273 for alias, replacement in Probe.aliases_arg.items():
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700274 # For USDT probes, we replace argN values with the
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300275 # actual arguments for that probe obtained using
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300276 # bpf_readarg_N macros emitted at BPF construction.
yonghong-song2da34262018-06-13 06:12:22 -0700277 if self.probe_type == "u":
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700278 continue
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800279 expr = expr.replace(alias, replacement)
yonghong-song2da34262018-06-13 06:12:22 -0700280 for alias, replacement in Probe.aliases_common.items():
281 expr = expr.replace(alias, replacement)
Nikita V. Shirokov3953c702018-07-27 16:13:47 -0700282 if self.bin_cmp:
283 STRCMP_RE = 'STRCMP\\(\"([^"]+)\\"'
284 else:
285 STRCMP_RE = 'STRCMP\\(("[^"]+\\")'
286 matches = re.finditer(STRCMP_RE, expr)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700287 for match in matches:
288 string = match.group(1)
289 fname = self._generate_streq_function(string)
290 expr = expr.replace("STRCMP", fname, 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800291 return expr
292
yonghong-songf7202572018-09-19 08:50:59 -0700293 p_type = {"u": ct.c_uint, "d": ct.c_int, "lu": ct.c_ulong,
294 "ld": ct.c_long,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300295 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
296 "hu": ct.c_ushort, "hd": ct.c_short,
yonghong-songf7202572018-09-19 08:50:59 -0700297 "x": ct.c_uint, "lx": ct.c_ulong, "llx": ct.c_ulonglong,
298 "c": ct.c_ubyte,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300299 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800300
301 def _generate_python_field_decl(self, idx, fields):
302 field_type = self.types[idx]
303 if field_type == "s":
304 ptype = ct.c_char * self.string_size
305 else:
306 ptype = Probe.p_type[field_type]
307 fields.append(("v%d" % idx, ptype))
308
309 def _generate_python_data_decl(self):
310 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700311 (self._display_function(), self.probe_num)
Teng Qinc200b6c2017-12-16 00:15:55 -0800312 fields = []
313 if self.time_field:
314 fields.append(("timestamp_ns", ct.c_ulonglong))
315 if self.print_cpu:
316 fields.append(("cpu", ct.c_int))
317 fields.extend([
Mark Draytonaa6c9162016-11-03 15:36:29 +0000318 ("tgid", ct.c_uint),
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800319 ("pid", ct.c_uint),
320 ("comm", ct.c_char * 16) # TASK_COMM_LEN
Teng Qinc200b6c2017-12-16 00:15:55 -0800321 ])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800322 for i in range(0, len(self.types)):
323 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700324 if self.kernel_stack:
325 fields.append(("kernel_stack_id", ct.c_int))
326 if self.user_stack:
327 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800328 return type(self.python_struct_name, (ct.Structure,),
329 dict(_fields_=fields))
330
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300331 c_type = {"u": "unsigned int", "d": "int",
yonghong-songf7202572018-09-19 08:50:59 -0700332 "lu": "unsigned long", "ld": "long",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300333 "llu": "unsigned long long", "lld": "long long",
334 "hu": "unsigned short", "hd": "short",
yonghong-songf7202572018-09-19 08:50:59 -0700335 "x": "unsigned int", "lx": "unsigned long",
336 "llx": "unsigned long long",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300337 "c": "char", "K": "unsigned long long",
338 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800339 fmt_types = c_type.keys()
340
341 def _generate_field_decl(self, idx):
342 field_type = self.types[idx]
343 if field_type == "s":
344 return "char v%d[%d];\n" % (idx, self.string_size)
345 if field_type in Probe.fmt_types:
346 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
347 self._bail("unrecognized format specifier %s" % field_type)
348
349 def _generate_data_decl(self):
350 # The BPF program will populate values into the struct
351 # according to the format string, and the Python program will
352 # construct the final display string.
353 self.events_name = "%s_events" % self.probe_name
354 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700355 self.stacks_name = "%s_stacks" % self.probe_name
vijunag9924e642019-01-23 12:35:33 +0530356 stack_type = "BPF_STACK_TRACE" if self.build_id_enabled is False \
357 else "BPF_STACK_TRACE_BUILDID"
358 stack_table = "%s(%s, 1024);" % (stack_type,self.stacks_name) \
Teng Qin6b0ed372016-09-29 21:30:13 -0700359 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800360 data_fields = ""
361 for i, field_type in enumerate(self.types):
362 data_fields += " " + \
363 self._generate_field_decl(i)
Teng Qinc200b6c2017-12-16 00:15:55 -0800364 time_str = "u64 timestamp_ns;" if self.time_field else ""
365 cpu_str = "int cpu;" if self.print_cpu else ""
Teng Qin6b0ed372016-09-29 21:30:13 -0700366 kernel_stack_str = " int kernel_stack_id;" \
367 if self.kernel_stack else ""
368 user_stack_str = " int user_stack_id;" \
369 if self.user_stack else ""
370
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800371 text = """
372struct %s
373{
Teng Qinc200b6c2017-12-16 00:15:55 -0800374%s
375%s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000376 u32 tgid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800377 u32 pid;
378 char comm[TASK_COMM_LEN];
379%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700380%s
381%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800382};
383
384BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700385%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800386"""
Teng Qinc200b6c2017-12-16 00:15:55 -0800387 return text % (self.struct_name, time_str, cpu_str, data_fields,
Teng Qin6b0ed372016-09-29 21:30:13 -0700388 kernel_stack_str, user_stack_str,
389 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800390
391 def _generate_field_assign(self, idx):
392 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300393 expr = self.values[idx].strip()
394 text = ""
395 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000396 arg_index = int(expr[3])
397 arg_ctype = self.usdt.get_probe_arg_ctype(
398 self.usdt_name, arg_index - 1)
399 text = (" %s %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300400 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000401 % (arg_ctype, expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300402
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800403 if field_type == "s":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300404 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800405 if (%s != 0) {
yonghong-song61484e12018-09-17 22:24:31 -0700406 void *__tmp = (void *)%s;
407 bpf_probe_read(&__data.v%d, sizeof(__data.v%d), __tmp);
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800408 }
yonghong-song61484e12018-09-17 22:24:31 -0700409 """ % (expr, expr, idx, idx)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800410 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300411 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800412 (idx, Probe.c_type[field_type], expr)
413 self._bail("unrecognized field type %s" % field_type)
414
Teng Qin0615bff2016-09-28 08:19:40 -0700415 def _generate_usdt_filter_read(self):
416 text = ""
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000417 if self.probe_type != "u":
418 return text
yonghong-song2da34262018-06-13 06:12:22 -0700419 for arg, _ in Probe.aliases_arg.items():
420 if not (arg in self.filter):
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000421 continue
422 arg_index = int(arg.replace("arg", ""))
423 arg_ctype = self.usdt.get_probe_arg_ctype(
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000424 self.usdt_name, arg_index - 1)
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000425 if not arg_ctype:
426 self._bail("Unable to determine type of {} "
427 "in the filter".format(arg))
428 text += """
Teng Qin0615bff2016-09-28 08:19:40 -0700429 {} {}_filter;
430 bpf_usdt_readarg({}, ctx, &{}_filter);
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000431 """.format(arg_ctype, arg, arg_index, arg)
432 self.filter = self.filter.replace(
433 arg, "{}_filter".format(arg))
Teng Qin0615bff2016-09-28 08:19:40 -0700434 return text
435
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700436 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800437 data_decl = self._generate_data_decl()
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000438 if Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800439 pid_filter = """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800440 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300441 """ % Probe.pid
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000442 # uprobes can have a built-in tgid filter passed to
443 # attach_uprobe, hence the check here -- for kprobes, we
444 # need to do the tgid test by hand:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000445 elif len(self.library) == 0 and Probe.tgid != -1:
446 pid_filter = """
447 if (__tgid != %d) { return 0; }
448 """ % Probe.tgid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800449 elif not include_self:
450 pid_filter = """
Mark Draytonaa6c9162016-11-03 15:36:29 +0000451 if (__tgid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300452 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800453 else:
454 pid_filter = ""
455
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700456 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700457 signature = "struct pt_regs *ctx"
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000458 if self.signature:
459 signature += ", " + self.signature
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700460
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800461 data_fields = ""
462 for i, expr in enumerate(self.values):
463 data_fields += self._generate_field_assign(i)
464
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300465 if self.probe_type == "t":
466 heading = "TRACEPOINT_PROBE(%s, %s)" % \
467 (self.tp_category, self.tp_event)
468 ctx_name = "args"
469 else:
470 heading = "int %s(%s)" % (self.probe_name, signature)
471 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300472
Teng Qinc200b6c2017-12-16 00:15:55 -0800473 time_str = """
474 __data.timestamp_ns = bpf_ktime_get_ns();""" if self.time_field else ""
475 cpu_str = """
476 __data.cpu = bpf_get_smp_processor_id();""" if self.print_cpu else ""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300477 stack_trace = ""
478 if self.user_stack:
479 stack_trace += """
480 __data.user_stack_id = %s.get_stackid(
481 %s, BPF_F_REUSE_STACKID | BPF_F_USER_STACK
482 );""" % (self.stacks_name, ctx_name)
483 if self.kernel_stack:
484 stack_trace += """
485 __data.kernel_stack_id = %s.get_stackid(
486 %s, BPF_F_REUSE_STACKID
487 );""" % (self.stacks_name, ctx_name)
488
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300489 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800490{
Mark Draytonaa6c9162016-11-03 15:36:29 +0000491 u64 __pid_tgid = bpf_get_current_pid_tgid();
492 u32 __tgid = __pid_tgid >> 32;
493 u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800494 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800495 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700496 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800497 if (!(%s)) return 0;
498
499 struct %s __data = {0};
Teng Qinc200b6c2017-12-16 00:15:55 -0800500 %s
501 %s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000502 __data.tgid = __tgid;
503 __data.pid = __pid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800504 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
505%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700506%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300507 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800508 return 0;
509}
510"""
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300511 text = text % (pid_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700512 self._generate_usdt_filter_read(), self.filter,
Teng Qinc200b6c2017-12-16 00:15:55 -0800513 self.struct_name, time_str, cpu_str, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300514 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700515
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700516 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800517
518 @classmethod
519 def _time_off_str(cls, timestamp_ns):
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100520 offset = 1e-9 * (timestamp_ns - cls.first_ts)
521 if cls.print_unix_timestamp:
522 return "%.6f" % (offset + cls.first_ts_real)
523 else:
524 return "%.6f" % offset
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800525
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800526 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700527 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800528 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700529 elif self.probe_type == 'u':
530 return self.usdt_name
531 else: # self.probe_type == 't'
532 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800533
Mark Draytonaa6c9162016-11-03 15:36:29 +0000534 def print_stack(self, bpf, stack_id, tgid):
Teng Qin6b0ed372016-09-29 21:30:13 -0700535 if stack_id < 0:
Mirek Klimose5382282018-01-26 14:52:50 -0800536 print(" %d" % stack_id)
537 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700538
539 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
540 for addr in stack:
Mirek Klimose5382282018-01-26 14:52:50 -0800541 print(" ", end="")
542 if Probe.print_address:
543 print("%16x " % addr, end="")
544 print("%s" % (bpf.sym(addr, tgid,
545 show_module=True, show_offset=True)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700546
Mark Draytonaa6c9162016-11-03 15:36:29 +0000547 def _format_message(self, bpf, tgid, values):
548 # Replace each %K with kernel sym and %U with user sym in tgid
Rafael Fonsecaaee5ecf2017-02-08 16:14:31 +0100549 kernel_placeholders = [i for i, t in enumerate(self.types)
550 if t == 'K']
551 user_placeholders = [i for i, t in enumerate(self.types)
552 if t == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700553 for kp in kernel_placeholders:
Sasha Goldshtein01553852017-02-09 03:58:09 -0500554 values[kp] = bpf.ksym(values[kp], show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700555 for up in user_placeholders:
Sasha Goldshtein1e34f4e2017-02-09 00:21:49 -0500556 values[up] = bpf.sym(values[up], tgid,
Sasha Goldshtein01553852017-02-09 03:58:09 -0500557 show_module=True, show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700558 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700559
560 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800561 # Cast as the generated structure type and display
562 # according to the format string in the probe.
563 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
564 values = map(lambda i: getattr(event, "v%d" % i),
565 range(0, len(self.values)))
Mark Draytonaa6c9162016-11-03 15:36:29 +0000566 msg = self._format_message(bpf, event.tgid, values)
Teng Qinc200b6c2017-12-16 00:15:55 -0800567 if Probe.print_time:
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000568 time = strftime("%H:%M:%S") if Probe.use_localtime else \
569 Probe._time_off_str(event.timestamp_ns)
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100570 if Probe.print_unix_timestamp:
571 print("%-17s " % time[:17], end="")
572 else:
573 print("%-8s " % time[:8], end="")
Teng Qinc200b6c2017-12-16 00:15:55 -0800574 if Probe.print_cpu:
575 print("%-3s " % event.cpu, end="")
576 print("%-7d %-7d %-15s %-16s %s" %
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200577 (event.tgid, event.pid,
578 event.comm.decode('utf-8', 'replace'),
Teng Qinc200b6c2017-12-16 00:15:55 -0800579 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800580
Teng Qin6b0ed372016-09-29 21:30:13 -0700581 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700582 self.print_stack(bpf, event.kernel_stack_id, -1)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000583 if self.user_stack:
584 self.print_stack(bpf, event.user_stack_id, event.tgid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700585 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700586 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700587
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800588 Probe.event_count += 1
589 if Probe.max_events is not None and \
590 Probe.event_count >= Probe.max_events:
591 exit()
592
593 def attach(self, bpf, verbose):
594 if len(self.library) == 0:
595 self._attach_k(bpf)
596 else:
597 self._attach_u(bpf)
598 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700599 callback = partial(self.print_event, bpf)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000600 bpf[self.events_name].open_perf_buffer(callback,
601 page_cnt=self.page_cnt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800602
603 def _attach_k(self, bpf):
604 if self.probe_type == "r":
605 bpf.attach_kretprobe(event=self.function,
606 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300607 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800608 bpf.attach_kprobe(event=self.function,
609 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300610 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800611
612 def _attach_u(self, bpf):
613 libpath = BPF.find_library(self.library)
614 if libpath is None:
615 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300616 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800617 if libpath is None or len(libpath) == 0:
618 self._bail("unable to find library %s" % self.library)
619
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700620 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300621 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700622 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800623 bpf.attach_uretprobe(name=libpath,
624 sym=self.function,
625 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000626 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800627 else:
628 bpf.attach_uprobe(name=libpath,
629 sym=self.function,
630 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000631 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800632
633class Tool(object):
Mark Drayton5f5687e2017-02-20 18:13:03 +0000634 DEFAULT_PERF_BUFFER_PAGES = 64
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800635 examples = """
636EXAMPLES:
637
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800638trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800639 Trace the open syscall and print a default trace message when entered
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800640trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800641 Trace the open syscall and print the filename being opened
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800642trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800643 Trace the read syscall and print a message for reads >20000 bytes
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000644trace 'r::do_sys_open "%llx", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800645 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800646trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800647 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800648trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800649 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800650trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
651 Trace the write() call from libc to monitor writes to STDOUT
Mark Draytonaa6c9162016-11-03 15:36:29 +0000652trace 'r::__kmalloc (retval == 0) "kmalloc failed!"'
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800653 Trace returns from __kmalloc which returned a null pointer
Mark Draytonaa6c9162016-11-03 15:36:29 +0000654trace 'r:c:malloc (retval) "allocated = %x", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800655 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300656trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800657 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700658trace 'u:pthread:pthread_create (arg4 != 0)'
659 Trace the USDT probe pthread_create when its 4th argument is non-zero
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000660trace 'p::SyS_nanosleep(struct timespec *ts) "sleep for %lld ns", ts->tv_nsec'
661 Trace the nanosleep syscall and print the sleep duration in ns
Yonghong Songf4470dc2017-12-13 14:12:13 -0800662trace -I 'linux/fs.h' \\
663 'p::uprobe_register(struct inode *inode) "a_ops = %llx", inode->i_mapping->a_ops'
664 Trace the uprobe_register inode mapping ops, and the symbol can be found
665 in /proc/kallsyms
666trace -I 'kernel/sched/sched.h' \\
667 'p::__account_cfs_rq_runtime(struct cfs_rq *cfs_rq) "%d", cfs_rq->runtime_remaining'
668 Trace the cfs scheduling runqueue remaining runtime. The struct cfs_rq is defined
669 in kernel/sched/sched.h which is in kernel source tree and not in kernel-devel
670 package. So this command needs to run at the kernel source tree root directory
671 so that the added header file can be found by the compiler.
tehnerd86293f02018-01-23 21:21:58 -0800672trace -I 'net/sock.h' \\
673 'udpv6_sendmsg(struct sock *sk) (sk->sk_dport == 13568)'
674 Trace udpv6 sendmsg calls only if socket's destination port is equal
675 to 53 (DNS; 13568 in big endian order)
Yonghong Songf92fef22018-01-24 20:51:46 -0800676trace -I 'linux/fs_struct.h' 'mntns_install "users = %d", $task->fs->users'
677 Trace the number of users accessing the file system of the current task
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800678"""
679
680 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300681 parser = argparse.ArgumentParser(description="Attach to " +
682 "functions and print trace messages.",
683 formatter_class=argparse.RawDescriptionHelpFormatter,
684 epilog=Tool.examples)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000685 parser.add_argument("-b", "--buffer-pages", type=int,
686 default=Tool.DEFAULT_PERF_BUFFER_PAGES,
687 help="number of pages to use for perf_events ring buffer "
688 "(default: %(default)d)")
Mark Draytonaa6c9162016-11-03 15:36:29 +0000689 # we'll refer to the userspace concepts of "pid" and "tid" by
690 # their kernel names -- tgid and pid -- inside the script
691 parser.add_argument("-p", "--pid", type=int, metavar="PID",
692 dest="tgid", help="id of the process to trace (optional)")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000693 parser.add_argument("-L", "--tid", type=int, metavar="TID",
Mark Draytonaa6c9162016-11-03 15:36:29 +0000694 dest="pid", help="id of the thread to trace (optional)")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800695 parser.add_argument("-v", "--verbose", action="store_true",
696 help="print resulting BPF program code before executing")
697 parser.add_argument("-Z", "--string-size", type=int,
698 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300699 parser.add_argument("-S", "--include-self",
700 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800701 help="do not filter trace's own pid from the trace")
702 parser.add_argument("-M", "--max-events", type=int,
703 help="number of events to print before quitting")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000704 parser.add_argument("-t", "--timestamp", action="store_true",
705 help="print timestamp column (offset from trace start)")
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100706 parser.add_argument("-u", "--unix-timestamp", action="store_true",
707 help="print UNIX timestamp instead of offset from trace start, requires -t")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000708 parser.add_argument("-T", "--time", action="store_true",
709 help="print time column")
Teng Qinc200b6c2017-12-16 00:15:55 -0800710 parser.add_argument("-C", "--print_cpu", action="store_true",
711 help="print CPU id")
Nikita V. Shirokov3953c702018-07-27 16:13:47 -0700712 parser.add_argument("-B", "--bin_cmp", action="store_true",
713 help="allow to use STRCMP with binary values")
vijunag9924e642019-01-23 12:35:33 +0530714 parser.add_argument('-s', "--sym_file_list", type=str, \
715 metavar="SYM_FILE_LIST", dest="sym_file_list", \
716 help="coma separated list of symbol files to use \
717 for symbol resolution")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300718 parser.add_argument("-K", "--kernel-stack",
719 action="store_true", help="output kernel stack trace")
720 parser.add_argument("-U", "--user-stack",
721 action="store_true", help="output user stack trace")
Mirek Klimose5382282018-01-26 14:52:50 -0800722 parser.add_argument("-a", "--address", action="store_true",
723 help="print virtual address in stacks")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800724 parser.add_argument(metavar="probe", dest="probes", nargs="+",
725 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300726 parser.add_argument("-I", "--include", action="append",
727 metavar="header",
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300728 help="additional header files to include in the BPF program "
Yonghong Songf4470dc2017-12-13 14:12:13 -0800729 "as either full path, "
730 "or relative to current working directory, "
731 "or relative to default kernel header search path")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100732 parser.add_argument("--ebpf", action="store_true",
733 help=argparse.SUPPRESS)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800734 self.args = parser.parse_args()
Mark Draytonaa6c9162016-11-03 15:36:29 +0000735 if self.args.tgid and self.args.pid:
Yonghong Songf4470dc2017-12-13 14:12:13 -0800736 parser.error("only one of -p and -L may be specified")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800737
738 def _create_probes(self):
739 Probe.configure(self.args)
740 self.probes = []
741 for probe_spec in self.args.probes:
742 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700743 probe_spec, self.args.string_size,
744 self.args.kernel_stack, self.args.user_stack))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800745
746 def _generate_program(self):
747 self.program = """
748#include <linux/ptrace.h>
749#include <linux/sched.h> /* For TASK_COMM_LEN */
750
751"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300752 for include in (self.args.include or []):
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300753 if include.startswith((".", "/")):
754 include = os.path.abspath(include)
755 self.program += "#include \"%s\"\n" % include
756 else:
757 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700758 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800759 map(lambda p: p.raw_probe, self.probes))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800760 for probe in self.probes:
761 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700762 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800763
Nathan Scottcf0792f2018-02-02 16:56:50 +1100764 if self.args.verbose or self.args.ebpf:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800765 print(self.program)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100766 if self.args.ebpf:
767 exit()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800768
769 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300770 usdt_contexts = []
771 for probe in self.probes:
772 if probe.usdt:
773 # USDT probes must be enabled before the BPF object
774 # is initialized, because that's where the actual
775 # uprobe is being attached.
776 probe.usdt.enable_probe(
777 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300778 if self.args.verbose:
779 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300780 usdt_contexts.append(probe.usdt)
781 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
vijunag9924e642019-01-23 12:35:33 +0530782 if self.args.sym_file_list is not None:
783 print("Note: Kernel bpf will report stack map with ip/build_id")
784 map(lambda x: self.bpf.add_module(x), self.args.sym_file_list.split(','))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800785 for probe in self.probes:
786 if self.args.verbose:
787 print(probe)
788 probe.attach(self.bpf, self.args.verbose)
789
790 def _main_loop(self):
791 all_probes_trivial = all(map(Probe.is_default_action,
792 self.probes))
793
794 # Print header
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000795 if self.args.timestamp or self.args.time:
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100796 col_fmt = "%-17s " if self.args.unix_timestamp else "%-8s "
797 print(col_fmt % "TIME", end="");
Teng Qinc200b6c2017-12-16 00:15:55 -0800798 if self.args.print_cpu:
799 print("%-3s " % "CPU", end="");
800 print("%-7s %-7s %-15s %-16s %s" %
801 ("PID", "TID", "COMM", "FUNC",
802 "-" if not all_probes_trivial else ""))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800803
804 while True:
Teng Qindbf00292018-02-28 21:47:50 -0800805 self.bpf.perf_buffer_poll()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800806
807 def run(self):
808 try:
809 self._create_probes()
810 self._generate_program()
811 self._attach_probes()
812 self._main_loop()
813 except:
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500814 exc_info = sys.exc_info()
815 sys_exit = exc_info[0] is SystemExit
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800816 if self.args.verbose:
817 traceback.print_exc()
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500818 elif not sys_exit:
819 print(exc_info[1])
820 exit(0 if sys_exit else 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800821
822if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300823 Tool().run()