blob: 7a61594f1468e65389010243b4a76816c7e8559b [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#
yonghong-songc2a530b2019-10-20 09:35:55 -07006# usage: trace [-h] [-p PID] [-L TID] [-v] [-Z STRING_SIZE] [-S] [-c cgroup_path]
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
Sumanth Korikkar7cbd0742020-04-27 09:09:28 -050014from bcc import BPF, USDT, StrcmpRewrite
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
yonghong-songc2a530b2019-10-20 09:35:55 -070060 def __init__(self, probe, string_size, kernel_stack, user_stack,
tty55cf529e2019-12-06 17:52:56 +080061 cgroup_map_name, name, msg_filter):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +030062 self.usdt = None
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070063 self.streq_functions = ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -080064 self.raw_probe = probe
65 self.string_size = string_size
Teng Qin6b0ed372016-09-29 21:30:13 -070066 self.kernel_stack = kernel_stack
67 self.user_stack = user_stack
Sumanth Korikkar7cbd0742020-04-27 09:09:28 -050068 self.probe_user_list = set()
Sasha Goldshtein38847f02016-02-22 02:19:24 -080069 Probe.probe_count += 1
70 self._parse_probe()
71 self.probe_num = Probe.probe_count
72 self.probe_name = "probe_%s_%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070073 (self._display_function(), self.probe_num)
Paul Chaignon956ca1c2017-03-04 20:07:56 +010074 self.probe_name = re.sub(r'[^A-Za-z0-9_]', '_',
75 self.probe_name)
yonghong-songc2a530b2019-10-20 09:35:55 -070076 self.cgroup_map_name = cgroup_map_name
tty59ce7b7e2019-12-04 22:49:38 +080077 self.name = name
tty55cf529e2019-12-06 17:52:56 +080078 self.msg_filter = msg_filter
yonghong-song2da34262018-06-13 06:12:22 -070079 # compiler can generate proper codes for function
80 # signatures with "syscall__" prefix
81 if self.is_syscall_kprobe:
82 self.probe_name = "syscall__" + self.probe_name[6:]
83
Sasha Goldshtein38847f02016-02-22 02:19:24 -080084 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070085 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
86 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080087 self.types, self.values)
88
89 def is_default_action(self):
90 return self.python_format == ""
91
92 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070093 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -080094 (self.raw_probe, error))
95
96 def _parse_probe(self):
97 text = self.raw_probe
98
Sasha Goldshtein23e72b82017-01-17 08:49:36 +000099 # There might be a function signature preceding the actual
100 # filter/print part, or not. Find the probe specifier first --
101 # it ends with either a space or an open paren ( for the
102 # function signature part.
103 # opt. signature
104 # probespec | rest
105 # --------- ---------- --
106 (spec, sig, rest) = re.match(r'([^ \t\(]+)(\([^\(]*\))?(.*)',
107 text).groups()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800108
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000109 self._parse_spec(spec)
Paul Chaignon956ca1c2017-03-04 20:07:56 +0100110 # Remove the parens
111 self.signature = sig[1:-1] if sig else None
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000112 if self.signature and self.probe_type in ['u', 't']:
113 self._bail("USDT and tracepoint probes can't have " +
114 "a function signature; use arg1, arg2, " +
115 "... instead")
116
117 text = rest.lstrip()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800118 # If we now have a (, wait for the balanced closing ) and that
119 # will be the predicate
120 self.filter = None
121 if len(text) > 0 and text[0] == "(":
122 balance = 1
123 for i in range(1, len(text)):
124 if text[i] == "(":
125 balance += 1
126 if text[i] == ")":
127 balance -= 1
128 if balance == 0:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300129 self._parse_filter(text[:i + 1])
130 text = text[i + 1:]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800131 break
132 if self.filter is None:
133 self._bail("unmatched end of predicate")
134
135 if self.filter is None:
136 self.filter = "1"
137
138 # The remainder of the text is the printf action
139 self._parse_action(text.lstrip())
140
Ferenc Fejesd7b427e2020-08-01 21:18:57 +0200141 def _parse_offset(self, func_and_offset):
142 func, offset_str = func_and_offset.split("+")
143 try:
144 if "x" in offset_str or "X" in offset_str:
145 offset = int(offset_str, 16)
146 else:
147 offset = int(offset_str)
148 except ValueError:
149 self._bail("invalid offset format " +
150 " '%s', must be decimal or hexadecimal" % offset_str)
151
152 return func, offset
153
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800154 def _parse_spec(self, spec):
155 parts = spec.split(":")
156 # Two special cases: 'func' means 'p::func', 'lib:func' means
157 # 'p:lib:func'. Other combinations need to provide an empty
158 # value between delimiters, e.g. 'r::func' for a kretprobe on
159 # the function func.
160 if len(parts) == 1:
161 parts = ["p", "", parts[0]]
162 elif len(parts) == 2:
163 parts = ["p", parts[0], parts[1]]
164 if len(parts[0]) == 0:
165 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700166 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800167 self.probe_type = parts[0]
168 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700169 self._bail("probe type must be '', 'p', 't', 'r', " +
170 "or 'u', but got '%s'" % parts[0])
Ferenc Fejesd7b427e2020-08-01 21:18:57 +0200171 self.offset = 0
172 if "+" in parts[-1]:
173 parts[-1], self.offset = self._parse_offset(parts[-1])
174
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800175 if self.probe_type == "t":
176 self.tp_category = parts[1]
177 self.tp_event = parts[2]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800178 self.library = "" # kernel
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300179 self.function = "" # from TRACEPOINT_PROBE
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700180 elif self.probe_type == "u":
Fuji Goro21625162020-03-08 08:16:54 +0000181 # u:<library>[:<provider>]:<probe> where :<provider> is optional
182 self.library = parts[1]
183 self.usdt_name = ":".join(parts[2:])
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700184 self.function = "" # no function, just address
185 # We will discover the USDT provider by matching on
186 # the USDT name in the specified library
187 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800188 else:
vkhromov5a2b39e2017-07-14 20:42:29 +0100189 self.library = ':'.join(parts[1:-1])
190 self.function = parts[-1]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800191
yonghong-song2da34262018-06-13 06:12:22 -0700192 # only x64 syscalls needs checking, no other syscall wrapper yet.
193 self.is_syscall_kprobe = False
194 if self.probe_type == "p" and len(self.library) == 0 and \
195 self.function[:10] == "__x64_sys_":
196 self.is_syscall_kprobe = True
197
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700198 def _find_usdt_probe(self):
Sasha Goldshteindd045362016-11-13 05:07:38 -0800199 target = Probe.pid if Probe.pid and Probe.pid != -1 \
200 else Probe.tgid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000201 self.usdt = USDT(path=self.library, pid=target)
Fuji Goro21625162020-03-08 08:16:54 +0000202
203 parts = self.usdt_name.split(":")
204 if len(parts) == 1:
205 provider_name = None
206 usdt_name = parts[0].encode("ascii")
207 else:
208 provider_name = parts[0].encode("ascii")
209 usdt_name = parts[1].encode("ascii")
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300210 for probe in self.usdt.enumerate_probes():
Fuji Goro21625162020-03-08 08:16:54 +0000211 if ((not provider_name or probe.provider == provider_name)
212 and probe.name == usdt_name):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300213 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700214 self._bail("unrecognized USDT probe %s" % self.usdt_name)
215
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800216 def _parse_filter(self, filt):
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700217 self.filter = self._rewrite_expr(filt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800218
219 def _parse_types(self, fmt):
220 for match in re.finditer(
yonghong-songf7202572018-09-19 08:50:59 -0700221 r'[^%]%(s|u|d|lu|llu|ld|lld|hu|hd|x|lx|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800222 self.types.append(match.group(1))
yonghong-songf7202572018-09-19 08:50:59 -0700223 fmt = re.sub(r'([^%]%)(u|d|lu|llu|ld|lld|hu|hd)', r'\1d', fmt)
224 fmt = re.sub(r'([^%]%)(x|lx|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700225 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800226 self.python_format = fmt.strip('"')
227
228 def _parse_action(self, action):
229 self.values = []
230 self.types = []
231 self.python_format = ""
232 if len(action) == 0:
233 return
234
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800235 action = action.strip()
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700236 match = re.search(r'(\".*?\"),?(.*)', action)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800237 if match is None:
238 self._bail("expected format string in \"s")
239
240 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800241 self._parse_types(self.raw_format)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700242 for part in re.split('(?<!"),', match.group(2)):
243 part = self._rewrite_expr(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800244 if len(part) > 0:
245 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800246
yonghong-song2da34262018-06-13 06:12:22 -0700247 aliases_arg = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530248 "arg1": "PT_REGS_PARM1(ctx)",
249 "arg2": "PT_REGS_PARM2(ctx)",
250 "arg3": "PT_REGS_PARM3(ctx)",
251 "arg4": "PT_REGS_PARM4(ctx)",
252 "arg5": "PT_REGS_PARM5(ctx)",
253 "arg6": "PT_REGS_PARM6(ctx)",
yonghong-song2da34262018-06-13 06:12:22 -0700254 }
255
256 aliases_indarg = {
Prashant Bhole05765ee2018-12-28 01:47:56 +0900257 "arg1": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500258 " bpf_probe_read_kernel(&_val, sizeof(_val), &(PT_REGS_PARM1(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800259 "arg2": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500260 " bpf_probe_read_kernel(&_val, sizeof(_val), &(PT_REGS_PARM2(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800261 "arg3": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500262 " bpf_probe_read_kernel(&_val, sizeof(_val), &(PT_REGS_PARM3(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800263 "arg4": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500264 " bpf_probe_read_kernel(&_val, sizeof(_val), &(PT_REGS_PARM4(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800265 "arg5": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500266 " bpf_probe_read_kernel(&_val, sizeof(_val), &(PT_REGS_PARM5(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800267 "arg6": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500268 " bpf_probe_read_kernel(&_val, sizeof(_val), &(PT_REGS_PARM6(_ctx))); _val;})",
yonghong-song2da34262018-06-13 06:12:22 -0700269 }
270
271 aliases_common = {
272 "retval": "PT_REGS_RC(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800273 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
274 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
275 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
276 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
Yonghong Songf92fef22018-01-24 20:51:46 -0800277 "$cpu": "bpf_get_smp_processor_id()",
278 "$task" : "((struct task_struct *)bpf_get_current_task())"
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800279 }
280
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700281 def _rewrite_expr(self, expr):
Sumanth Korikkar7cbd0742020-04-27 09:09:28 -0500282 # Find the occurances of any arg[1-6]@user. Use it later to
283 # identify bpf_probe_read_user
284 for matches in re.finditer(r'(arg[1-6])(@user)', expr):
285 if matches.group(1).strip() not in self.probe_user_list:
286 self.probe_user_list.add(matches.group(1).strip())
287 # Remove @user occurrences from arg before resolving to its
288 # corresponding aliases.
289 expr = re.sub(r'(arg[1-6])@user', r'\1', expr)
290 rdict = StrcmpRewrite.rewrite_expr(expr,
291 self.bin_cmp, self.library,
292 self.probe_user_list, self.streq_functions,
293 Probe.streq_index)
294 expr = rdict["expr"]
295 self.streq_functions = rdict["streq_functions"]
296 Probe.streq_index = rdict["probeid"]
297 alias_to_check = Probe.aliases_indarg \
298 if self.is_syscall_kprobe \
299 else Probe.aliases_arg
300 # For USDT probes, we replace argN values with the
301 # actual arguments for that probe obtained using
302 # bpf_readarg_N macros emitted at BPF construction.
303 if not self.probe_type == "u":
304 for alias, replacement in alias_to_check.items():
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800305 expr = expr.replace(alias, replacement)
yonghong-song2da34262018-06-13 06:12:22 -0700306 for alias, replacement in Probe.aliases_common.items():
307 expr = expr.replace(alias, replacement)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800308 return expr
309
yonghong-songf7202572018-09-19 08:50:59 -0700310 p_type = {"u": ct.c_uint, "d": ct.c_int, "lu": ct.c_ulong,
311 "ld": ct.c_long,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300312 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
313 "hu": ct.c_ushort, "hd": ct.c_short,
yonghong-songf7202572018-09-19 08:50:59 -0700314 "x": ct.c_uint, "lx": ct.c_ulong, "llx": ct.c_ulonglong,
315 "c": ct.c_ubyte,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300316 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800317
318 def _generate_python_field_decl(self, idx, fields):
319 field_type = self.types[idx]
320 if field_type == "s":
321 ptype = ct.c_char * self.string_size
322 else:
323 ptype = Probe.p_type[field_type]
324 fields.append(("v%d" % idx, ptype))
325
326 def _generate_python_data_decl(self):
327 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700328 (self._display_function(), self.probe_num)
Teng Qinc200b6c2017-12-16 00:15:55 -0800329 fields = []
330 if self.time_field:
331 fields.append(("timestamp_ns", ct.c_ulonglong))
332 if self.print_cpu:
333 fields.append(("cpu", ct.c_int))
334 fields.extend([
Mark Draytonaa6c9162016-11-03 15:36:29 +0000335 ("tgid", ct.c_uint),
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800336 ("pid", ct.c_uint),
337 ("comm", ct.c_char * 16) # TASK_COMM_LEN
Teng Qinc200b6c2017-12-16 00:15:55 -0800338 ])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800339 for i in range(0, len(self.types)):
340 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700341 if self.kernel_stack:
342 fields.append(("kernel_stack_id", ct.c_int))
343 if self.user_stack:
344 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800345 return type(self.python_struct_name, (ct.Structure,),
346 dict(_fields_=fields))
347
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300348 c_type = {"u": "unsigned int", "d": "int",
yonghong-songf7202572018-09-19 08:50:59 -0700349 "lu": "unsigned long", "ld": "long",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300350 "llu": "unsigned long long", "lld": "long long",
351 "hu": "unsigned short", "hd": "short",
yonghong-songf7202572018-09-19 08:50:59 -0700352 "x": "unsigned int", "lx": "unsigned long",
353 "llx": "unsigned long long",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300354 "c": "char", "K": "unsigned long long",
355 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800356 fmt_types = c_type.keys()
357
358 def _generate_field_decl(self, idx):
359 field_type = self.types[idx]
360 if field_type == "s":
361 return "char v%d[%d];\n" % (idx, self.string_size)
362 if field_type in Probe.fmt_types:
363 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
364 self._bail("unrecognized format specifier %s" % field_type)
365
366 def _generate_data_decl(self):
367 # The BPF program will populate values into the struct
368 # according to the format string, and the Python program will
369 # construct the final display string.
370 self.events_name = "%s_events" % self.probe_name
371 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700372 self.stacks_name = "%s_stacks" % self.probe_name
vijunag9924e642019-01-23 12:35:33 +0530373 stack_type = "BPF_STACK_TRACE" if self.build_id_enabled is False \
374 else "BPF_STACK_TRACE_BUILDID"
375 stack_table = "%s(%s, 1024);" % (stack_type,self.stacks_name) \
Teng Qin6b0ed372016-09-29 21:30:13 -0700376 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800377 data_fields = ""
378 for i, field_type in enumerate(self.types):
379 data_fields += " " + \
380 self._generate_field_decl(i)
Teng Qinc200b6c2017-12-16 00:15:55 -0800381 time_str = "u64 timestamp_ns;" if self.time_field else ""
382 cpu_str = "int cpu;" if self.print_cpu else ""
Teng Qin6b0ed372016-09-29 21:30:13 -0700383 kernel_stack_str = " int kernel_stack_id;" \
384 if self.kernel_stack else ""
385 user_stack_str = " int user_stack_id;" \
386 if self.user_stack else ""
387
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800388 text = """
389struct %s
390{
Teng Qinc200b6c2017-12-16 00:15:55 -0800391%s
392%s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000393 u32 tgid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800394 u32 pid;
395 char comm[TASK_COMM_LEN];
396%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700397%s
398%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800399};
400
401BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700402%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800403"""
Teng Qinc200b6c2017-12-16 00:15:55 -0800404 return text % (self.struct_name, time_str, cpu_str, data_fields,
Teng Qin6b0ed372016-09-29 21:30:13 -0700405 kernel_stack_str, user_stack_str,
406 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800407
408 def _generate_field_assign(self, idx):
409 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300410 expr = self.values[idx].strip()
411 text = ""
412 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000413 arg_index = int(expr[3])
414 arg_ctype = self.usdt.get_probe_arg_ctype(
415 self.usdt_name, arg_index - 1)
416 text = (" %s %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300417 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000418 % (arg_ctype, expr, expr[3], expr)
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500419 probe_read_func = "bpf_probe_read_kernel"
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800420 if field_type == "s":
Sumanth Korikkar7cbd0742020-04-27 09:09:28 -0500421 if self.library:
422 probe_read_func = "bpf_probe_read_user"
423 else:
424 alias_to_check = Probe.aliases_indarg \
425 if self.is_syscall_kprobe \
426 else Probe.aliases_arg
427 for arg, alias in alias_to_check.items():
428 if alias == expr and arg in self.probe_user_list:
429 probe_read_func = "bpf_probe_read_user"
430 break
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300431 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800432 if (%s != 0) {
yonghong-song61484e12018-09-17 22:24:31 -0700433 void *__tmp = (void *)%s;
Sumanth Korikkar7cbd0742020-04-27 09:09:28 -0500434 %s(&__data.v%d, sizeof(__data.v%d), __tmp);
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800435 }
Sumanth Korikkar7cbd0742020-04-27 09:09:28 -0500436 """ % (expr, expr, probe_read_func, idx, idx)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800437 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300438 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800439 (idx, Probe.c_type[field_type], expr)
440 self._bail("unrecognized field type %s" % field_type)
441
Teng Qin0615bff2016-09-28 08:19:40 -0700442 def _generate_usdt_filter_read(self):
443 text = ""
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000444 if self.probe_type != "u":
445 return text
yonghong-song2da34262018-06-13 06:12:22 -0700446 for arg, _ in Probe.aliases_arg.items():
447 if not (arg in self.filter):
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000448 continue
449 arg_index = int(arg.replace("arg", ""))
450 arg_ctype = self.usdt.get_probe_arg_ctype(
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000451 self.usdt_name, arg_index - 1)
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000452 if not arg_ctype:
453 self._bail("Unable to determine type of {} "
454 "in the filter".format(arg))
455 text += """
Teng Qin0615bff2016-09-28 08:19:40 -0700456 {} {}_filter;
457 bpf_usdt_readarg({}, ctx, &{}_filter);
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000458 """.format(arg_ctype, arg, arg_index, arg)
459 self.filter = self.filter.replace(
460 arg, "{}_filter".format(arg))
Teng Qin0615bff2016-09-28 08:19:40 -0700461 return text
462
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700463 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800464 data_decl = self._generate_data_decl()
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000465 if Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800466 pid_filter = """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800467 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300468 """ % Probe.pid
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000469 # uprobes can have a built-in tgid filter passed to
470 # attach_uprobe, hence the check here -- for kprobes, we
471 # need to do the tgid test by hand:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000472 elif len(self.library) == 0 and Probe.tgid != -1:
473 pid_filter = """
474 if (__tgid != %d) { return 0; }
475 """ % Probe.tgid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800476 elif not include_self:
477 pid_filter = """
Mark Draytonaa6c9162016-11-03 15:36:29 +0000478 if (__tgid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300479 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800480 else:
481 pid_filter = ""
482
yonghong-songc2a530b2019-10-20 09:35:55 -0700483 if self.cgroup_map_name is not None:
484 cgroup_filter = """
485 if (%s.check_current_task(0) <= 0) { return 0; }
486 """ % self.cgroup_map_name
487 else:
488 cgroup_filter = ""
489
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700490 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700491 signature = "struct pt_regs *ctx"
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000492 if self.signature:
493 signature += ", " + self.signature
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700494
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800495 data_fields = ""
496 for i, expr in enumerate(self.values):
497 data_fields += self._generate_field_assign(i)
498
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300499 if self.probe_type == "t":
500 heading = "TRACEPOINT_PROBE(%s, %s)" % \
501 (self.tp_category, self.tp_event)
502 ctx_name = "args"
503 else:
504 heading = "int %s(%s)" % (self.probe_name, signature)
505 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300506
Teng Qinc200b6c2017-12-16 00:15:55 -0800507 time_str = """
508 __data.timestamp_ns = bpf_ktime_get_ns();""" if self.time_field else ""
509 cpu_str = """
510 __data.cpu = bpf_get_smp_processor_id();""" if self.print_cpu else ""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300511 stack_trace = ""
512 if self.user_stack:
513 stack_trace += """
514 __data.user_stack_id = %s.get_stackid(
Yonghong Song90f20862019-11-27 09:16:23 -0800515 %s, BPF_F_USER_STACK
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300516 );""" % (self.stacks_name, ctx_name)
517 if self.kernel_stack:
518 stack_trace += """
519 __data.kernel_stack_id = %s.get_stackid(
Yonghong Song90f20862019-11-27 09:16:23 -0800520 %s, 0
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300521 );""" % (self.stacks_name, ctx_name)
522
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300523 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800524{
Mark Draytonaa6c9162016-11-03 15:36:29 +0000525 u64 __pid_tgid = bpf_get_current_pid_tgid();
526 u32 __tgid = __pid_tgid >> 32;
527 u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800528 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800529 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700530 %s
yonghong-songc2a530b2019-10-20 09:35:55 -0700531 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800532 if (!(%s)) return 0;
533
534 struct %s __data = {0};
Teng Qinc200b6c2017-12-16 00:15:55 -0800535 %s
536 %s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000537 __data.tgid = __tgid;
538 __data.pid = __pid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800539 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
540%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700541%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300542 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800543 return 0;
544}
545"""
yonghong-songc2a530b2019-10-20 09:35:55 -0700546 text = text % (pid_filter, cgroup_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700547 self._generate_usdt_filter_read(), self.filter,
Teng Qinc200b6c2017-12-16 00:15:55 -0800548 self.struct_name, time_str, cpu_str, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300549 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700550
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700551 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800552
553 @classmethod
554 def _time_off_str(cls, timestamp_ns):
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100555 offset = 1e-9 * (timestamp_ns - cls.first_ts)
556 if cls.print_unix_timestamp:
557 return "%.6f" % (offset + cls.first_ts_real)
558 else:
559 return "%.6f" % offset
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800560
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800561 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700562 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800563 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700564 elif self.probe_type == 'u':
565 return self.usdt_name
566 else: # self.probe_type == 't'
567 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800568
Mark Draytonaa6c9162016-11-03 15:36:29 +0000569 def print_stack(self, bpf, stack_id, tgid):
Teng Qin6b0ed372016-09-29 21:30:13 -0700570 if stack_id < 0:
Mirek Klimose5382282018-01-26 14:52:50 -0800571 print(" %d" % stack_id)
572 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700573
574 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
575 for addr in stack:
Mirek Klimose5382282018-01-26 14:52:50 -0800576 print(" ", end="")
577 if Probe.print_address:
578 print("%16x " % addr, end="")
579 print("%s" % (bpf.sym(addr, tgid,
580 show_module=True, show_offset=True)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700581
Mark Draytonaa6c9162016-11-03 15:36:29 +0000582 def _format_message(self, bpf, tgid, values):
583 # Replace each %K with kernel sym and %U with user sym in tgid
Rafael Fonsecaaee5ecf2017-02-08 16:14:31 +0100584 kernel_placeholders = [i for i, t in enumerate(self.types)
585 if t == 'K']
586 user_placeholders = [i for i, t in enumerate(self.types)
587 if t == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700588 for kp in kernel_placeholders:
Sasha Goldshtein01553852017-02-09 03:58:09 -0500589 values[kp] = bpf.ksym(values[kp], show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700590 for up in user_placeholders:
Sasha Goldshtein1e34f4e2017-02-09 00:21:49 -0500591 values[up] = bpf.sym(values[up], tgid,
Sasha Goldshtein01553852017-02-09 03:58:09 -0500592 show_module=True, show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700593 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700594
595 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800596 # Cast as the generated structure type and display
597 # according to the format string in the probe.
598 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
tty59ce7b7e2019-12-04 22:49:38 +0800599 if self.name and bytes(self.name) not in event.comm:
600 return
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800601 values = map(lambda i: getattr(event, "v%d" % i),
602 range(0, len(self.values)))
Mark Draytonaa6c9162016-11-03 15:36:29 +0000603 msg = self._format_message(bpf, event.tgid, values)
tty55cf529e2019-12-06 17:52:56 +0800604 if self.msg_filter and bytes(self.msg_filter) not in msg:
605 return
Teng Qinc200b6c2017-12-16 00:15:55 -0800606 if Probe.print_time:
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000607 time = strftime("%H:%M:%S") if Probe.use_localtime else \
608 Probe._time_off_str(event.timestamp_ns)
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100609 if Probe.print_unix_timestamp:
610 print("%-17s " % time[:17], end="")
611 else:
612 print("%-8s " % time[:8], end="")
Teng Qinc200b6c2017-12-16 00:15:55 -0800613 if Probe.print_cpu:
614 print("%-3s " % event.cpu, end="")
615 print("%-7d %-7d %-15s %-16s %s" %
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200616 (event.tgid, event.pid,
617 event.comm.decode('utf-8', 'replace'),
Teng Qinc200b6c2017-12-16 00:15:55 -0800618 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800619
Teng Qin6b0ed372016-09-29 21:30:13 -0700620 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700621 self.print_stack(bpf, event.kernel_stack_id, -1)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000622 if self.user_stack:
623 self.print_stack(bpf, event.user_stack_id, event.tgid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700624 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700625 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700626
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800627 Probe.event_count += 1
628 if Probe.max_events is not None and \
629 Probe.event_count >= Probe.max_events:
630 exit()
Alban Crequy8bb4e472019-12-21 16:09:53 +0100631 sys.stdout.flush()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800632
633 def attach(self, bpf, verbose):
634 if len(self.library) == 0:
635 self._attach_k(bpf)
636 else:
637 self._attach_u(bpf)
638 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700639 callback = partial(self.print_event, bpf)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000640 bpf[self.events_name].open_perf_buffer(callback,
641 page_cnt=self.page_cnt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800642
643 def _attach_k(self, bpf):
644 if self.probe_type == "r":
645 bpf.attach_kretprobe(event=self.function,
646 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300647 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800648 bpf.attach_kprobe(event=self.function,
Ferenc Fejesd7b427e2020-08-01 21:18:57 +0200649 fn_name=self.probe_name,
650 event_off=self.offset)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300651 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800652
653 def _attach_u(self, bpf):
654 libpath = BPF.find_library(self.library)
655 if libpath is None:
656 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300657 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800658 if libpath is None or len(libpath) == 0:
659 self._bail("unable to find library %s" % self.library)
660
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700661 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300662 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700663 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800664 bpf.attach_uretprobe(name=libpath,
665 sym=self.function,
666 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000667 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800668 else:
669 bpf.attach_uprobe(name=libpath,
670 sym=self.function,
671 fn_name=self.probe_name,
Ferenc Fejesd7b427e2020-08-01 21:18:57 +0200672 pid=Probe.tgid,
673 sym_off=self.offset)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800674
675class Tool(object):
Mark Drayton5f5687e2017-02-20 18:13:03 +0000676 DEFAULT_PERF_BUFFER_PAGES = 64
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800677 examples = """
678EXAMPLES:
679
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800680trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800681 Trace the open syscall and print a default trace message when entered
Ferenc Fejesd7b427e2020-08-01 21:18:57 +0200682trace kfree_skb+0x12
683 Trace the kfree_skb kernel function after the instruction on the 0x12 offset
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800684trace 'do_sys_open "%s", arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800685 Trace the open syscall and print the filename being opened
tty59ce7b7e2019-12-04 22:49:38 +0800686trace 'do_sys_open "%s", arg2' -n main
687 Trace the open syscall and only print event that process names containing "main"
tty55cf529e2019-12-06 17:52:56 +0800688trace 'do_sys_open "%s", arg2' -f config
689 Trace the open syscall and print the filename being opened filtered by "config"
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800690trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800691 Trace the read syscall and print a message for reads >20000 bytes
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000692trace 'r::do_sys_open "%llx", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800693 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800694trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800695 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800696trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800697 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800698trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
699 Trace the write() call from libc to monitor writes to STDOUT
Mark Draytonaa6c9162016-11-03 15:36:29 +0000700trace 'r::__kmalloc (retval == 0) "kmalloc failed!"'
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800701 Trace returns from __kmalloc which returned a null pointer
Mark Draytonaa6c9162016-11-03 15:36:29 +0000702trace 'r:c:malloc (retval) "allocated = %x", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800703 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300704trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800705 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700706trace 'u:pthread:pthread_create (arg4 != 0)'
707 Trace the USDT probe pthread_create when its 4th argument is non-zero
Fuji Goro21625162020-03-08 08:16:54 +0000708trace 'u:pthread:libpthread:pthread_create (arg4 != 0)'
709 Ditto, but the provider name "libpthread" is specified.
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000710trace 'p::SyS_nanosleep(struct timespec *ts) "sleep for %lld ns", ts->tv_nsec'
711 Trace the nanosleep syscall and print the sleep duration in ns
yonghong-songc2a530b2019-10-20 09:35:55 -0700712trace -c /sys/fs/cgroup/system.slice/workload.service '__x64_sys_nanosleep' '__x64_sys_clone'
713 Trace nanosleep/clone syscall calls only under workload.service
714 cgroup hierarchy.
Yonghong Songf4470dc2017-12-13 14:12:13 -0800715trace -I 'linux/fs.h' \\
716 'p::uprobe_register(struct inode *inode) "a_ops = %llx", inode->i_mapping->a_ops'
717 Trace the uprobe_register inode mapping ops, and the symbol can be found
718 in /proc/kallsyms
719trace -I 'kernel/sched/sched.h' \\
720 'p::__account_cfs_rq_runtime(struct cfs_rq *cfs_rq) "%d", cfs_rq->runtime_remaining'
721 Trace the cfs scheduling runqueue remaining runtime. The struct cfs_rq is defined
722 in kernel/sched/sched.h which is in kernel source tree and not in kernel-devel
723 package. So this command needs to run at the kernel source tree root directory
724 so that the added header file can be found by the compiler.
tehnerd86293f02018-01-23 21:21:58 -0800725trace -I 'net/sock.h' \\
726 'udpv6_sendmsg(struct sock *sk) (sk->sk_dport == 13568)'
727 Trace udpv6 sendmsg calls only if socket's destination port is equal
728 to 53 (DNS; 13568 in big endian order)
Yonghong Songf92fef22018-01-24 20:51:46 -0800729trace -I 'linux/fs_struct.h' 'mntns_install "users = %d", $task->fs->users'
730 Trace the number of users accessing the file system of the current task
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800731"""
732
733 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300734 parser = argparse.ArgumentParser(description="Attach to " +
735 "functions and print trace messages.",
736 formatter_class=argparse.RawDescriptionHelpFormatter,
737 epilog=Tool.examples)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000738 parser.add_argument("-b", "--buffer-pages", type=int,
739 default=Tool.DEFAULT_PERF_BUFFER_PAGES,
740 help="number of pages to use for perf_events ring buffer "
741 "(default: %(default)d)")
Mark Draytonaa6c9162016-11-03 15:36:29 +0000742 # we'll refer to the userspace concepts of "pid" and "tid" by
743 # their kernel names -- tgid and pid -- inside the script
744 parser.add_argument("-p", "--pid", type=int, metavar="PID",
745 dest="tgid", help="id of the process to trace (optional)")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000746 parser.add_argument("-L", "--tid", type=int, metavar="TID",
Mark Draytonaa6c9162016-11-03 15:36:29 +0000747 dest="pid", help="id of the thread to trace (optional)")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800748 parser.add_argument("-v", "--verbose", action="store_true",
749 help="print resulting BPF program code before executing")
750 parser.add_argument("-Z", "--string-size", type=int,
751 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300752 parser.add_argument("-S", "--include-self",
753 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800754 help="do not filter trace's own pid from the trace")
755 parser.add_argument("-M", "--max-events", type=int,
756 help="number of events to print before quitting")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000757 parser.add_argument("-t", "--timestamp", action="store_true",
758 help="print timestamp column (offset from trace start)")
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100759 parser.add_argument("-u", "--unix-timestamp", action="store_true",
760 help="print UNIX timestamp instead of offset from trace start, requires -t")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000761 parser.add_argument("-T", "--time", action="store_true",
762 help="print time column")
Teng Qinc200b6c2017-12-16 00:15:55 -0800763 parser.add_argument("-C", "--print_cpu", action="store_true",
764 help="print CPU id")
yonghong-songc2a530b2019-10-20 09:35:55 -0700765 parser.add_argument("-c", "--cgroup-path", type=str, \
766 metavar="CGROUP_PATH", dest="cgroup_path", \
767 help="cgroup path")
tty59ce7b7e2019-12-04 22:49:38 +0800768 parser.add_argument("-n", "--name", type=str,
769 help="only print process names containing this name")
tty55cf529e2019-12-06 17:52:56 +0800770 parser.add_argument("-f", "--msg-filter", type=str, dest="msg_filter",
771 help="only print the msg of event containing this string")
Nikita V. Shirokov3953c702018-07-27 16:13:47 -0700772 parser.add_argument("-B", "--bin_cmp", action="store_true",
773 help="allow to use STRCMP with binary values")
vijunag9924e642019-01-23 12:35:33 +0530774 parser.add_argument('-s', "--sym_file_list", type=str, \
775 metavar="SYM_FILE_LIST", dest="sym_file_list", \
776 help="coma separated list of symbol files to use \
777 for symbol resolution")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300778 parser.add_argument("-K", "--kernel-stack",
779 action="store_true", help="output kernel stack trace")
780 parser.add_argument("-U", "--user-stack",
781 action="store_true", help="output user stack trace")
Mirek Klimose5382282018-01-26 14:52:50 -0800782 parser.add_argument("-a", "--address", action="store_true",
783 help="print virtual address in stacks")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800784 parser.add_argument(metavar="probe", dest="probes", nargs="+",
785 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300786 parser.add_argument("-I", "--include", action="append",
787 metavar="header",
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300788 help="additional header files to include in the BPF program "
Yonghong Songf4470dc2017-12-13 14:12:13 -0800789 "as either full path, "
790 "or relative to current working directory, "
791 "or relative to default kernel header search path")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100792 parser.add_argument("--ebpf", action="store_true",
793 help=argparse.SUPPRESS)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800794 self.args = parser.parse_args()
Mark Draytonaa6c9162016-11-03 15:36:29 +0000795 if self.args.tgid and self.args.pid:
Yonghong Songf4470dc2017-12-13 14:12:13 -0800796 parser.error("only one of -p and -L may be specified")
yonghong-songc2a530b2019-10-20 09:35:55 -0700797 if self.args.cgroup_path is not None:
798 self.cgroup_map_name = "__cgroup"
799 else:
800 self.cgroup_map_name = None
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800801
802 def _create_probes(self):
803 Probe.configure(self.args)
804 self.probes = []
805 for probe_spec in self.args.probes:
806 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700807 probe_spec, self.args.string_size,
yonghong-songc2a530b2019-10-20 09:35:55 -0700808 self.args.kernel_stack, self.args.user_stack,
tty55cf529e2019-12-06 17:52:56 +0800809 self.cgroup_map_name, self.args.name, self.args.msg_filter))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800810
811 def _generate_program(self):
812 self.program = """
813#include <linux/ptrace.h>
814#include <linux/sched.h> /* For TASK_COMM_LEN */
815
816"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300817 for include in (self.args.include or []):
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300818 if include.startswith((".", "/")):
819 include = os.path.abspath(include)
820 self.program += "#include \"%s\"\n" % include
821 else:
822 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700823 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800824 map(lambda p: p.raw_probe, self.probes))
yonghong-songc2a530b2019-10-20 09:35:55 -0700825 if self.cgroup_map_name is not None:
826 self.program += "BPF_CGROUP_ARRAY(%s, 1);\n" % \
827 self.cgroup_map_name
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800828 for probe in self.probes:
829 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700830 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800831
Nathan Scottcf0792f2018-02-02 16:56:50 +1100832 if self.args.verbose or self.args.ebpf:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800833 print(self.program)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100834 if self.args.ebpf:
835 exit()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800836
837 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300838 usdt_contexts = []
839 for probe in self.probes:
840 if probe.usdt:
841 # USDT probes must be enabled before the BPF object
842 # is initialized, because that's where the actual
843 # uprobe is being attached.
844 probe.usdt.enable_probe(
845 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300846 if self.args.verbose:
847 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300848 usdt_contexts.append(probe.usdt)
849 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
vijunag9924e642019-01-23 12:35:33 +0530850 if self.args.sym_file_list is not None:
851 print("Note: Kernel bpf will report stack map with ip/build_id")
852 map(lambda x: self.bpf.add_module(x), self.args.sym_file_list.split(','))
yonghong-songc2a530b2019-10-20 09:35:55 -0700853
854 # if cgroup filter is requested, update the cgroup array map
855 if self.cgroup_map_name is not None:
856 cgroup_array = self.bpf.get_table(self.cgroup_map_name)
857 cgroup_array[0] = self.args.cgroup_path
858
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800859 for probe in self.probes:
860 if self.args.verbose:
861 print(probe)
862 probe.attach(self.bpf, self.args.verbose)
863
864 def _main_loop(self):
865 all_probes_trivial = all(map(Probe.is_default_action,
866 self.probes))
867
868 # Print header
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000869 if self.args.timestamp or self.args.time:
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100870 col_fmt = "%-17s " if self.args.unix_timestamp else "%-8s "
871 print(col_fmt % "TIME", end="");
Teng Qinc200b6c2017-12-16 00:15:55 -0800872 if self.args.print_cpu:
873 print("%-3s " % "CPU", end="");
874 print("%-7s %-7s %-15s %-16s %s" %
875 ("PID", "TID", "COMM", "FUNC",
876 "-" if not all_probes_trivial else ""))
Alban Crequy8bb4e472019-12-21 16:09:53 +0100877 sys.stdout.flush()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800878
879 while True:
Teng Qindbf00292018-02-28 21:47:50 -0800880 self.bpf.perf_buffer_poll()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800881
882 def run(self):
883 try:
884 self._create_probes()
885 self._generate_program()
886 self._attach_probes()
887 self._main_loop()
888 except:
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500889 exc_info = sys.exc_info()
890 sys_exit = exc_info[0] is SystemExit
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800891 if self.args.verbose:
892 traceback.print_exc()
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500893 elif not sys_exit:
894 print(exc_info[1])
895 exit(0 if sys_exit else 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800896
897if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300898 Tool().run()