blob: 0f6d90e8b1a549018a217d10c14e3a97dcbb5aad [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
Jonathan Giddyec0691e2021-02-21 09:44:26 +000016from time import 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
evilpanf32f7722021-12-11 00:58:51 +080040 uid = -1
Mark Drayton5f5687e2017-02-20 18:13:03 +000041 page_cnt = None
vijunag9924e642019-01-23 12:35:33 +053042 build_id_enabled = False
Sasha Goldshtein38847f02016-02-22 02:19:24 -080043
44 @classmethod
45 def configure(cls, args):
46 cls.max_events = args.max_events
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +000047 cls.print_time = args.timestamp or args.time
Maik Riechert3a0d3c42019-05-23 17:57:10 +010048 cls.print_unix_timestamp = args.unix_timestamp
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +000049 cls.use_localtime = not args.timestamp
Teng Qinc200b6c2017-12-16 00:15:55 -080050 cls.time_field = cls.print_time and (not cls.use_localtime)
51 cls.print_cpu = args.print_cpu
Mirek Klimose5382282018-01-26 14:52:50 -080052 cls.print_address = args.address
Sasha Goldshtein60c41922017-02-09 04:19:53 -050053 cls.first_ts = BPF.monotonic_time()
Maik Riechert3a0d3c42019-05-23 17:57:10 +010054 cls.first_ts_real = time.time()
Mark Draytonaa6c9162016-11-03 15:36:29 +000055 cls.tgid = args.tgid or -1
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070056 cls.pid = args.pid or -1
evilpanf32f7722021-12-11 00:58:51 +080057 cls.uid = args.uid or -1
Mark Drayton5f5687e2017-02-20 18:13:03 +000058 cls.page_cnt = args.buffer_pages
Nikita V. Shirokov3953c702018-07-27 16:13:47 -070059 cls.bin_cmp = args.bin_cmp
vijunag9924e642019-01-23 12:35:33 +053060 cls.build_id_enabled = args.sym_file_list is not None
Sasha Goldshtein38847f02016-02-22 02:19:24 -080061
yonghong-songc2a530b2019-10-20 09:35:55 -070062 def __init__(self, probe, string_size, kernel_stack, user_stack,
tty55cf529e2019-12-06 17:52:56 +080063 cgroup_map_name, name, msg_filter):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +030064 self.usdt = None
Sasha Goldshteinf4797b02016-10-17 01:44:56 -070065 self.streq_functions = ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -080066 self.raw_probe = probe
67 self.string_size = string_size
Teng Qin6b0ed372016-09-29 21:30:13 -070068 self.kernel_stack = kernel_stack
69 self.user_stack = user_stack
Sumanth Korikkar7cbd0742020-04-27 09:09:28 -050070 self.probe_user_list = set()
Sasha Goldshtein38847f02016-02-22 02:19:24 -080071 Probe.probe_count += 1
72 self._parse_probe()
73 self.probe_num = Probe.probe_count
74 self.probe_name = "probe_%s_%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070075 (self._display_function(), self.probe_num)
Paul Chaignon956ca1c2017-03-04 20:07:56 +010076 self.probe_name = re.sub(r'[^A-Za-z0-9_]', '_',
77 self.probe_name)
yonghong-songc2a530b2019-10-20 09:35:55 -070078 self.cgroup_map_name = cgroup_map_name
Jonathan Giddyec0691e2021-02-21 09:44:26 +000079 if name is None:
80 # An empty bytestring is always contained in the command
81 # name so this will always succeed.
82 self.name = b''
83 else:
84 self.name = name.encode('ascii')
tty55cf529e2019-12-06 17:52:56 +080085 self.msg_filter = msg_filter
yonghong-song2da34262018-06-13 06:12:22 -070086 # compiler can generate proper codes for function
87 # signatures with "syscall__" prefix
88 if self.is_syscall_kprobe:
89 self.probe_name = "syscall__" + self.probe_name[6:]
90
Sasha Goldshtein38847f02016-02-22 02:19:24 -080091 def __str__(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070092 return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type,
93 self.library, self._display_function(), self.filter,
Sasha Goldshtein38847f02016-02-22 02:19:24 -080094 self.types, self.values)
95
96 def is_default_action(self):
97 return self.python_format == ""
98
99 def _bail(self, error):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700100 raise ValueError("error in probe '%s': %s" %
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800101 (self.raw_probe, error))
102
103 def _parse_probe(self):
104 text = self.raw_probe
105
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000106 # There might be a function signature preceding the actual
107 # filter/print part, or not. Find the probe specifier first --
108 # it ends with either a space or an open paren ( for the
109 # function signature part.
110 # opt. signature
111 # probespec | rest
112 # --------- ---------- --
113 (spec, sig, rest) = re.match(r'([^ \t\(]+)(\([^\(]*\))?(.*)',
114 text).groups()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800115
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000116 self._parse_spec(spec)
Paul Chaignon956ca1c2017-03-04 20:07:56 +0100117 # Remove the parens
118 self.signature = sig[1:-1] if sig else None
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000119 if self.signature and self.probe_type in ['u', 't']:
120 self._bail("USDT and tracepoint probes can't have " +
121 "a function signature; use arg1, arg2, " +
122 "... instead")
123
124 text = rest.lstrip()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800125 # If we now have a (, wait for the balanced closing ) and that
126 # will be the predicate
127 self.filter = None
128 if len(text) > 0 and text[0] == "(":
129 balance = 1
130 for i in range(1, len(text)):
131 if text[i] == "(":
132 balance += 1
133 if text[i] == ")":
134 balance -= 1
135 if balance == 0:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300136 self._parse_filter(text[:i + 1])
137 text = text[i + 1:]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800138 break
139 if self.filter is None:
140 self._bail("unmatched end of predicate")
141
142 if self.filter is None:
143 self.filter = "1"
144
145 # The remainder of the text is the printf action
146 self._parse_action(text.lstrip())
147
Ferenc Fejesd7b427e2020-08-01 21:18:57 +0200148 def _parse_offset(self, func_and_offset):
149 func, offset_str = func_and_offset.split("+")
150 try:
151 if "x" in offset_str or "X" in offset_str:
152 offset = int(offset_str, 16)
153 else:
154 offset = int(offset_str)
155 except ValueError:
156 self._bail("invalid offset format " +
157 " '%s', must be decimal or hexadecimal" % offset_str)
158
159 return func, offset
160
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800161 def _parse_spec(self, spec):
162 parts = spec.split(":")
163 # Two special cases: 'func' means 'p::func', 'lib:func' means
164 # 'p:lib:func'. Other combinations need to provide an empty
165 # value between delimiters, e.g. 'r::func' for a kretprobe on
166 # the function func.
167 if len(parts) == 1:
168 parts = ["p", "", parts[0]]
169 elif len(parts) == 2:
170 parts = ["p", parts[0], parts[1]]
171 if len(parts[0]) == 0:
172 self.probe_type = "p"
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700173 elif parts[0] in ["p", "r", "t", "u"]:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800174 self.probe_type = parts[0]
175 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700176 self._bail("probe type must be '', 'p', 't', 'r', " +
177 "or 'u', but got '%s'" % parts[0])
Ferenc Fejesd7b427e2020-08-01 21:18:57 +0200178 self.offset = 0
179 if "+" in parts[-1]:
180 parts[-1], self.offset = self._parse_offset(parts[-1])
181
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800182 if self.probe_type == "t":
183 self.tp_category = parts[1]
184 self.tp_event = parts[2]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800185 self.library = "" # kernel
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300186 self.function = "" # from TRACEPOINT_PROBE
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700187 elif self.probe_type == "u":
Fuji Goro21625162020-03-08 08:16:54 +0000188 # u:<library>[:<provider>]:<probe> where :<provider> is optional
189 self.library = parts[1]
190 self.usdt_name = ":".join(parts[2:])
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700191 self.function = "" # no function, just address
192 # We will discover the USDT provider by matching on
193 # the USDT name in the specified library
194 self._find_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800195 else:
vkhromov5a2b39e2017-07-14 20:42:29 +0100196 self.library = ':'.join(parts[1:-1])
197 self.function = parts[-1]
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800198
yonghong-song2da34262018-06-13 06:12:22 -0700199 # only x64 syscalls needs checking, no other syscall wrapper yet.
200 self.is_syscall_kprobe = False
201 if self.probe_type == "p" and len(self.library) == 0 and \
202 self.function[:10] == "__x64_sys_":
203 self.is_syscall_kprobe = True
204
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700205 def _find_usdt_probe(self):
Sasha Goldshteindd045362016-11-13 05:07:38 -0800206 target = Probe.pid if Probe.pid and Probe.pid != -1 \
207 else Probe.tgid
Mark Draytonaa6c9162016-11-03 15:36:29 +0000208 self.usdt = USDT(path=self.library, pid=target)
Fuji Goro21625162020-03-08 08:16:54 +0000209
210 parts = self.usdt_name.split(":")
211 if len(parts) == 1:
212 provider_name = None
213 usdt_name = parts[0].encode("ascii")
214 else:
215 provider_name = parts[0].encode("ascii")
216 usdt_name = parts[1].encode("ascii")
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300217 for probe in self.usdt.enumerate_probes():
Fuji Goro21625162020-03-08 08:16:54 +0000218 if ((not provider_name or probe.provider == provider_name)
219 and probe.name == usdt_name):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300220 return # Found it, will enable later
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700221 self._bail("unrecognized USDT probe %s" % self.usdt_name)
222
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800223 def _parse_filter(self, filt):
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700224 self.filter = self._rewrite_expr(filt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800225
226 def _parse_types(self, fmt):
227 for match in re.finditer(
yonghong-songf7202572018-09-19 08:50:59 -0700228 r'[^%]%(s|u|d|lu|llu|ld|lld|hu|hd|x|lx|llx|c|K|U)', fmt):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800229 self.types.append(match.group(1))
yonghong-songf7202572018-09-19 08:50:59 -0700230 fmt = re.sub(r'([^%]%)(u|d|lu|llu|ld|lld|hu|hd)', r'\1d', fmt)
231 fmt = re.sub(r'([^%]%)(x|lx|llx)', r'\1x', fmt)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700232 fmt = re.sub('%K|%U', '%s', fmt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800233 self.python_format = fmt.strip('"')
234
235 def _parse_action(self, action):
236 self.values = []
237 self.types = []
238 self.python_format = ""
239 if len(action) == 0:
240 return
241
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800242 action = action.strip()
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700243 match = re.search(r'(\".*?\"),?(.*)', action)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800244 if match is None:
245 self._bail("expected format string in \"s")
246
247 self.raw_format = match.group(1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800248 self._parse_types(self.raw_format)
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700249 for part in re.split('(?<!"),', match.group(2)):
250 part = self._rewrite_expr(part)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800251 if len(part) > 0:
252 self.values.append(part)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800253
yonghong-song2da34262018-06-13 06:12:22 -0700254 aliases_arg = {
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530255 "arg1": "PT_REGS_PARM1(ctx)",
256 "arg2": "PT_REGS_PARM2(ctx)",
257 "arg3": "PT_REGS_PARM3(ctx)",
258 "arg4": "PT_REGS_PARM4(ctx)",
259 "arg5": "PT_REGS_PARM5(ctx)",
260 "arg6": "PT_REGS_PARM6(ctx)",
yonghong-song2da34262018-06-13 06:12:22 -0700261 }
262
263 aliases_indarg = {
Prashant Bhole05765ee2018-12-28 01:47:56 +0900264 "arg1": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500265 " bpf_probe_read_kernel(&_val, sizeof(_val), &(PT_REGS_PARM1(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800266 "arg2": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500267 " bpf_probe_read_kernel(&_val, sizeof(_val), &(PT_REGS_PARM2(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800268 "arg3": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500269 " bpf_probe_read_kernel(&_val, sizeof(_val), &(PT_REGS_PARM3(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800270 "arg4": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500271 " bpf_probe_read_kernel(&_val, sizeof(_val), &(PT_REGS_PARM4(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800272 "arg5": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500273 " bpf_probe_read_kernel(&_val, sizeof(_val), &(PT_REGS_PARM5(_ctx))); _val;})",
Xiaozhou Liu25a0ef32019-01-14 14:14:43 +0800274 "arg6": "({u64 _val; struct pt_regs *_ctx = (struct pt_regs *)PT_REGS_PARM1(ctx);"
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500275 " bpf_probe_read_kernel(&_val, sizeof(_val), &(PT_REGS_PARM6(_ctx))); _val;})",
yonghong-song2da34262018-06-13 06:12:22 -0700276 }
277
278 aliases_common = {
279 "retval": "PT_REGS_RC(ctx)",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800280 "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)",
281 "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)",
282 "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)",
283 "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)",
Yonghong Songf92fef22018-01-24 20:51:46 -0800284 "$cpu": "bpf_get_smp_processor_id()",
Jonathan Giddyec0691e2021-02-21 09:44:26 +0000285 "$task": "((struct task_struct *)bpf_get_current_task())"
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800286 }
287
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700288 def _rewrite_expr(self, expr):
Sumanth Korikkar7cbd0742020-04-27 09:09:28 -0500289 # Find the occurances of any arg[1-6]@user. Use it later to
290 # identify bpf_probe_read_user
291 for matches in re.finditer(r'(arg[1-6])(@user)', expr):
292 if matches.group(1).strip() not in self.probe_user_list:
293 self.probe_user_list.add(matches.group(1).strip())
294 # Remove @user occurrences from arg before resolving to its
295 # corresponding aliases.
296 expr = re.sub(r'(arg[1-6])@user', r'\1', expr)
297 rdict = StrcmpRewrite.rewrite_expr(expr,
298 self.bin_cmp, self.library,
299 self.probe_user_list, self.streq_functions,
300 Probe.streq_index)
301 expr = rdict["expr"]
302 self.streq_functions = rdict["streq_functions"]
303 Probe.streq_index = rdict["probeid"]
304 alias_to_check = Probe.aliases_indarg \
305 if self.is_syscall_kprobe \
306 else Probe.aliases_arg
307 # For USDT probes, we replace argN values with the
308 # actual arguments for that probe obtained using
309 # bpf_readarg_N macros emitted at BPF construction.
310 if not self.probe_type == "u":
311 for alias, replacement in alias_to_check.items():
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800312 expr = expr.replace(alias, replacement)
yonghong-song2da34262018-06-13 06:12:22 -0700313 for alias, replacement in Probe.aliases_common.items():
314 expr = expr.replace(alias, replacement)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800315 return expr
316
yonghong-songf7202572018-09-19 08:50:59 -0700317 p_type = {"u": ct.c_uint, "d": ct.c_int, "lu": ct.c_ulong,
318 "ld": ct.c_long,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300319 "llu": ct.c_ulonglong, "lld": ct.c_longlong,
320 "hu": ct.c_ushort, "hd": ct.c_short,
yonghong-songf7202572018-09-19 08:50:59 -0700321 "x": ct.c_uint, "lx": ct.c_ulong, "llx": ct.c_ulonglong,
322 "c": ct.c_ubyte,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300323 "K": ct.c_ulonglong, "U": ct.c_ulonglong}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800324
325 def _generate_python_field_decl(self, idx, fields):
326 field_type = self.types[idx]
327 if field_type == "s":
328 ptype = ct.c_char * self.string_size
329 else:
330 ptype = Probe.p_type[field_type]
331 fields.append(("v%d" % idx, ptype))
332
333 def _generate_python_data_decl(self):
334 self.python_struct_name = "%s_%d_Data" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700335 (self._display_function(), self.probe_num)
Teng Qinc200b6c2017-12-16 00:15:55 -0800336 fields = []
337 if self.time_field:
338 fields.append(("timestamp_ns", ct.c_ulonglong))
339 if self.print_cpu:
340 fields.append(("cpu", ct.c_int))
341 fields.extend([
Mark Draytonaa6c9162016-11-03 15:36:29 +0000342 ("tgid", ct.c_uint),
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800343 ("pid", ct.c_uint),
344 ("comm", ct.c_char * 16) # TASK_COMM_LEN
Teng Qinc200b6c2017-12-16 00:15:55 -0800345 ])
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800346 for i in range(0, len(self.types)):
347 self._generate_python_field_decl(i, fields)
Teng Qin6b0ed372016-09-29 21:30:13 -0700348 if self.kernel_stack:
349 fields.append(("kernel_stack_id", ct.c_int))
350 if self.user_stack:
351 fields.append(("user_stack_id", ct.c_int))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800352 return type(self.python_struct_name, (ct.Structure,),
353 dict(_fields_=fields))
354
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300355 c_type = {"u": "unsigned int", "d": "int",
yonghong-songf7202572018-09-19 08:50:59 -0700356 "lu": "unsigned long", "ld": "long",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300357 "llu": "unsigned long long", "lld": "long long",
358 "hu": "unsigned short", "hd": "short",
yonghong-songf7202572018-09-19 08:50:59 -0700359 "x": "unsigned int", "lx": "unsigned long",
360 "llx": "unsigned long long",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300361 "c": "char", "K": "unsigned long long",
362 "U": "unsigned long long"}
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800363 fmt_types = c_type.keys()
364
365 def _generate_field_decl(self, idx):
366 field_type = self.types[idx]
367 if field_type == "s":
368 return "char v%d[%d];\n" % (idx, self.string_size)
369 if field_type in Probe.fmt_types:
370 return "%s v%d;\n" % (Probe.c_type[field_type], idx)
371 self._bail("unrecognized format specifier %s" % field_type)
372
373 def _generate_data_decl(self):
374 # The BPF program will populate values into the struct
375 # according to the format string, and the Python program will
376 # construct the final display string.
377 self.events_name = "%s_events" % self.probe_name
378 self.struct_name = "%s_data_t" % self.probe_name
Teng Qin6b0ed372016-09-29 21:30:13 -0700379 self.stacks_name = "%s_stacks" % self.probe_name
vijunag9924e642019-01-23 12:35:33 +0530380 stack_type = "BPF_STACK_TRACE" if self.build_id_enabled is False \
381 else "BPF_STACK_TRACE_BUILDID"
Jonathan Giddyec0691e2021-02-21 09:44:26 +0000382 stack_table = "%s(%s, 1024);" % (stack_type, self.stacks_name) \
Teng Qin6b0ed372016-09-29 21:30:13 -0700383 if (self.kernel_stack or self.user_stack) else ""
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800384 data_fields = ""
385 for i, field_type in enumerate(self.types):
386 data_fields += " " + \
387 self._generate_field_decl(i)
Teng Qinc200b6c2017-12-16 00:15:55 -0800388 time_str = "u64 timestamp_ns;" if self.time_field else ""
389 cpu_str = "int cpu;" if self.print_cpu else ""
Teng Qin6b0ed372016-09-29 21:30:13 -0700390 kernel_stack_str = " int kernel_stack_id;" \
391 if self.kernel_stack else ""
392 user_stack_str = " int user_stack_id;" \
393 if self.user_stack else ""
394
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800395 text = """
396struct %s
397{
Teng Qinc200b6c2017-12-16 00:15:55 -0800398%s
399%s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000400 u32 tgid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800401 u32 pid;
402 char comm[TASK_COMM_LEN];
403%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700404%s
405%s
evilpanf32f7722021-12-11 00:58:51 +0800406 u32 uid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800407};
408
409BPF_PERF_OUTPUT(%s);
Teng Qin6b0ed372016-09-29 21:30:13 -0700410%s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800411"""
Teng Qinc200b6c2017-12-16 00:15:55 -0800412 return text % (self.struct_name, time_str, cpu_str, data_fields,
Teng Qin6b0ed372016-09-29 21:30:13 -0700413 kernel_stack_str, user_stack_str,
414 self.events_name, stack_table)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800415
416 def _generate_field_assign(self, idx):
417 field_type = self.types[idx]
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300418 expr = self.values[idx].strip()
419 text = ""
420 if self.probe_type == "u" and expr[0:3] == "arg":
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000421 arg_index = int(expr[3])
422 arg_ctype = self.usdt.get_probe_arg_ctype(
423 self.usdt_name, arg_index - 1)
424 text = (" %s %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300425 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
Sasha Goldshtein3a5256f2017-02-20 15:42:57 +0000426 % (arg_ctype, expr, expr[3], expr)
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500427 probe_read_func = "bpf_probe_read_kernel"
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800428 if field_type == "s":
Sumanth Korikkar7cbd0742020-04-27 09:09:28 -0500429 if self.library:
430 probe_read_func = "bpf_probe_read_user"
431 else:
432 alias_to_check = Probe.aliases_indarg \
433 if self.is_syscall_kprobe \
434 else Probe.aliases_arg
435 for arg, alias in alias_to_check.items():
436 if alias == expr and arg in self.probe_user_list:
437 probe_read_func = "bpf_probe_read_user"
438 break
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300439 return text + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800440 if (%s != 0) {
yonghong-song61484e12018-09-17 22:24:31 -0700441 void *__tmp = (void *)%s;
Sumanth Korikkar7cbd0742020-04-27 09:09:28 -0500442 %s(&__data.v%d, sizeof(__data.v%d), __tmp);
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800443 }
Sumanth Korikkar7cbd0742020-04-27 09:09:28 -0500444 """ % (expr, expr, probe_read_func, idx, idx)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800445 if field_type in Probe.fmt_types:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300446 return text + " __data.v%d = (%s)%s;\n" % \
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800447 (idx, Probe.c_type[field_type], expr)
448 self._bail("unrecognized field type %s" % field_type)
449
Teng Qin0615bff2016-09-28 08:19:40 -0700450 def _generate_usdt_filter_read(self):
451 text = ""
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000452 if self.probe_type != "u":
453 return text
yonghong-song2da34262018-06-13 06:12:22 -0700454 for arg, _ in Probe.aliases_arg.items():
455 if not (arg in self.filter):
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000456 continue
457 arg_index = int(arg.replace("arg", ""))
458 arg_ctype = self.usdt.get_probe_arg_ctype(
Sasha Goldshteindcf16752017-01-17 07:40:57 +0000459 self.usdt_name, arg_index - 1)
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000460 if not arg_ctype:
461 self._bail("Unable to determine type of {} "
462 "in the filter".format(arg))
463 text += """
Teng Qin0615bff2016-09-28 08:19:40 -0700464 {} {}_filter;
465 bpf_usdt_readarg({}, ctx, &{}_filter);
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000466 """.format(arg_ctype, arg, arg_index, arg)
467 self.filter = self.filter.replace(
468 arg, "{}_filter".format(arg))
Teng Qin0615bff2016-09-28 08:19:40 -0700469 return text
470
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700471 def generate_program(self, include_self):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800472 data_decl = self._generate_data_decl()
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000473 if Probe.pid != -1:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800474 pid_filter = """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800475 if (__pid != %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300476 """ % Probe.pid
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000477 # uprobes can have a built-in tgid filter passed to
478 # attach_uprobe, hence the check here -- for kprobes, we
479 # need to do the tgid test by hand:
Mark Draytonaa6c9162016-11-03 15:36:29 +0000480 elif len(self.library) == 0 and Probe.tgid != -1:
481 pid_filter = """
482 if (__tgid != %d) { return 0; }
483 """ % Probe.tgid
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800484 elif not include_self:
485 pid_filter = """
Mark Draytonaa6c9162016-11-03 15:36:29 +0000486 if (__tgid == %d) { return 0; }
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300487 """ % os.getpid()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800488 else:
489 pid_filter = ""
490
evilpanf32f7722021-12-11 00:58:51 +0800491 if Probe.uid != -1:
492 uid_filter = """
493 if (__uid != %d) { return 0; }
494 """ % Probe.uid
495 else:
496 uid_filter = ""
497
yonghong-songc2a530b2019-10-20 09:35:55 -0700498 if self.cgroup_map_name is not None:
499 cgroup_filter = """
500 if (%s.check_current_task(0) <= 0) { return 0; }
501 """ % self.cgroup_map_name
502 else:
503 cgroup_filter = ""
504
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700505 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700506 signature = "struct pt_regs *ctx"
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000507 if self.signature:
508 signature += ", " + self.signature
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700509
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800510 data_fields = ""
511 for i, expr in enumerate(self.values):
512 data_fields += self._generate_field_assign(i)
513
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300514 if self.probe_type == "t":
515 heading = "TRACEPOINT_PROBE(%s, %s)" % \
516 (self.tp_category, self.tp_event)
517 ctx_name = "args"
518 else:
519 heading = "int %s(%s)" % (self.probe_name, signature)
520 ctx_name = "ctx"
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300521
Teng Qinc200b6c2017-12-16 00:15:55 -0800522 time_str = """
523 __data.timestamp_ns = bpf_ktime_get_ns();""" if self.time_field else ""
524 cpu_str = """
525 __data.cpu = bpf_get_smp_processor_id();""" if self.print_cpu else ""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300526 stack_trace = ""
527 if self.user_stack:
528 stack_trace += """
529 __data.user_stack_id = %s.get_stackid(
Yonghong Song90f20862019-11-27 09:16:23 -0800530 %s, BPF_F_USER_STACK
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300531 );""" % (self.stacks_name, ctx_name)
532 if self.kernel_stack:
533 stack_trace += """
534 __data.kernel_stack_id = %s.get_stackid(
Yonghong Song90f20862019-11-27 09:16:23 -0800535 %s, 0
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300536 );""" % (self.stacks_name, ctx_name)
537
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300538 text = heading + """
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800539{
Mark Draytonaa6c9162016-11-03 15:36:29 +0000540 u64 __pid_tgid = bpf_get_current_pid_tgid();
541 u32 __tgid = __pid_tgid >> 32;
542 u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
evilpanf32f7722021-12-11 00:58:51 +0800543 u32 __uid = bpf_get_current_uid_gid();
544 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800545 %s
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800546 %s
Teng Qin0615bff2016-09-28 08:19:40 -0700547 %s
yonghong-songc2a530b2019-10-20 09:35:55 -0700548 %s
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800549 if (!(%s)) return 0;
550
551 struct %s __data = {0};
Teng Qinc200b6c2017-12-16 00:15:55 -0800552 %s
553 %s
Mark Draytonaa6c9162016-11-03 15:36:29 +0000554 __data.tgid = __tgid;
555 __data.pid = __pid;
evilpanf32f7722021-12-11 00:58:51 +0800556 __data.uid = __uid;
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800557 bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
558%s
Teng Qin6b0ed372016-09-29 21:30:13 -0700559%s
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300560 %s.perf_submit(%s, &__data, sizeof(__data));
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800561 return 0;
562}
563"""
evilpanf32f7722021-12-11 00:58:51 +0800564 text = text % (pid_filter, uid_filter, cgroup_filter, prefix,
Teng Qin0615bff2016-09-28 08:19:40 -0700565 self._generate_usdt_filter_read(), self.filter,
Teng Qinc200b6c2017-12-16 00:15:55 -0800566 self.struct_name, time_str, cpu_str, data_fields,
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300567 stack_trace, self.events_name, ctx_name)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700568
Sasha Goldshteinf4797b02016-10-17 01:44:56 -0700569 return self.streq_functions + data_decl + "\n" + text
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800570
571 @classmethod
572 def _time_off_str(cls, timestamp_ns):
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100573 offset = 1e-9 * (timestamp_ns - cls.first_ts)
574 if cls.print_unix_timestamp:
575 return "%.6f" % (offset + cls.first_ts_real)
576 else:
577 return "%.6f" % offset
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800578
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800579 def _display_function(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700580 if self.probe_type == 'p' or self.probe_type == 'r':
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800581 return self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700582 elif self.probe_type == 'u':
583 return self.usdt_name
584 else: # self.probe_type == 't'
585 return self.tp_event
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800586
Mark Draytonaa6c9162016-11-03 15:36:29 +0000587 def print_stack(self, bpf, stack_id, tgid):
Teng Qin6b0ed372016-09-29 21:30:13 -0700588 if stack_id < 0:
Mirek Klimose5382282018-01-26 14:52:50 -0800589 print(" %d" % stack_id)
590 return
Teng Qin6b0ed372016-09-29 21:30:13 -0700591
592 stack = list(bpf.get_table(self.stacks_name).walk(stack_id))
593 for addr in stack:
Mirek Klimose5382282018-01-26 14:52:50 -0800594 print(" ", end="")
595 if Probe.print_address:
596 print("%16x " % addr, end="")
597 print("%s" % (bpf.sym(addr, tgid,
598 show_module=True, show_offset=True)))
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700599
Mark Draytonaa6c9162016-11-03 15:36:29 +0000600 def _format_message(self, bpf, tgid, values):
601 # Replace each %K with kernel sym and %U with user sym in tgid
Rafael Fonsecaaee5ecf2017-02-08 16:14:31 +0100602 kernel_placeholders = [i for i, t in enumerate(self.types)
603 if t == 'K']
604 user_placeholders = [i for i, t in enumerate(self.types)
605 if t == 'U']
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700606 for kp in kernel_placeholders:
Sasha Goldshtein01553852017-02-09 03:58:09 -0500607 values[kp] = bpf.ksym(values[kp], show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700608 for up in user_placeholders:
Sasha Goldshtein1e34f4e2017-02-09 00:21:49 -0500609 values[up] = bpf.sym(values[up], tgid,
Sasha Goldshtein01553852017-02-09 03:58:09 -0500610 show_module=True, show_offset=True)
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700611 return self.python_format % tuple(values)
Teng Qin6b0ed372016-09-29 21:30:13 -0700612
613 def print_event(self, bpf, cpu, data, size):
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800614 # Cast as the generated structure type and display
615 # according to the format string in the probe.
616 event = ct.cast(data, ct.POINTER(self.python_struct)).contents
Jonathan Giddyec0691e2021-02-21 09:44:26 +0000617 if self.name not in event.comm:
tty59ce7b7e2019-12-04 22:49:38 +0800618 return
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800619 values = map(lambda i: getattr(event, "v%d" % i),
620 range(0, len(self.values)))
Mark Draytonaa6c9162016-11-03 15:36:29 +0000621 msg = self._format_message(bpf, event.tgid, values)
Jonathan Giddyec0691e2021-02-21 09:44:26 +0000622 if self.msg_filter and self.msg_filter not in msg:
tty55cf529e2019-12-06 17:52:56 +0800623 return
Teng Qinc200b6c2017-12-16 00:15:55 -0800624 if Probe.print_time:
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000625 time = strftime("%H:%M:%S") if Probe.use_localtime else \
626 Probe._time_off_str(event.timestamp_ns)
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100627 if Probe.print_unix_timestamp:
628 print("%-17s " % time[:17], end="")
629 else:
630 print("%-8s " % time[:8], end="")
Teng Qinc200b6c2017-12-16 00:15:55 -0800631 if Probe.print_cpu:
632 print("%-3s " % event.cpu, end="")
633 print("%-7d %-7d %-15s %-16s %s" %
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200634 (event.tgid, event.pid,
635 event.comm.decode('utf-8', 'replace'),
Teng Qinc200b6c2017-12-16 00:15:55 -0800636 self._display_function(), msg))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800637
Teng Qin6b0ed372016-09-29 21:30:13 -0700638 if self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700639 self.print_stack(bpf, event.kernel_stack_id, -1)
Mark Draytonaa6c9162016-11-03 15:36:29 +0000640 if self.user_stack:
641 self.print_stack(bpf, event.user_stack_id, event.tgid)
Teng Qin6b0ed372016-09-29 21:30:13 -0700642 if self.user_stack or self.kernel_stack:
Sasha Goldshteinaccd4cf2016-10-11 07:56:13 -0700643 print("")
Teng Qin6b0ed372016-09-29 21:30:13 -0700644
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800645 Probe.event_count += 1
646 if Probe.max_events is not None and \
647 Probe.event_count >= Probe.max_events:
648 exit()
Alban Crequy8bb4e472019-12-21 16:09:53 +0100649 sys.stdout.flush()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800650
651 def attach(self, bpf, verbose):
652 if len(self.library) == 0:
653 self._attach_k(bpf)
654 else:
655 self._attach_u(bpf)
656 self.python_struct = self._generate_python_data_decl()
Teng Qin6b0ed372016-09-29 21:30:13 -0700657 callback = partial(self.print_event, bpf)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000658 bpf[self.events_name].open_perf_buffer(callback,
659 page_cnt=self.page_cnt)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800660
661 def _attach_k(self, bpf):
662 if self.probe_type == "r":
663 bpf.attach_kretprobe(event=self.function,
664 fn_name=self.probe_name)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300665 elif self.probe_type == "p":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800666 bpf.attach_kprobe(event=self.function,
Ferenc Fejesd7b427e2020-08-01 21:18:57 +0200667 fn_name=self.probe_name,
668 event_off=self.offset)
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300669 # Note that tracepoints don't need an explicit attach
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800670
671 def _attach_u(self, bpf):
672 libpath = BPF.find_library(self.library)
673 if libpath is None:
674 # This might be an executable (e.g. 'bash')
Sasha Goldshteinec679712016-10-04 18:33:36 +0300675 libpath = BPF.find_exe(self.library)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800676 if libpath is None or len(libpath) == 0:
677 self._bail("unable to find library %s" % self.library)
678
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700679 if self.probe_type == "u":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300680 pass # Was already enabled by the BPF constructor
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700681 elif self.probe_type == "r":
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800682 bpf.attach_uretprobe(name=libpath,
683 sym=self.function,
684 fn_name=self.probe_name,
Sasha Goldshteinb6300922017-01-16 18:43:11 +0000685 pid=Probe.tgid)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800686 else:
687 bpf.attach_uprobe(name=libpath,
688 sym=self.function,
689 fn_name=self.probe_name,
Ferenc Fejesd7b427e2020-08-01 21:18:57 +0200690 pid=Probe.tgid,
691 sym_off=self.offset)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800692
693class Tool(object):
Mark Drayton5f5687e2017-02-20 18:13:03 +0000694 DEFAULT_PERF_BUFFER_PAGES = 64
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800695 examples = """
696EXAMPLES:
697
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800698trace do_sys_open
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800699 Trace the open syscall and print a default trace message when entered
Ferenc Fejesd7b427e2020-08-01 21:18:57 +0200700trace kfree_skb+0x12
701 Trace the kfree_skb kernel function after the instruction on the 0x12 offset
evilpanf32f7722021-12-11 00:58:51 +0800702trace 'do_sys_open "%s", arg2@user'
703 Trace the open syscall and print the filename. being opened @user is
704 added to arg2 in kprobes to ensure that char * should be copied from
705 the userspace stack to the bpf stack. If not specified, previous
706 behaviour is expected.
707
708trace 'do_sys_open "%s", arg2@user' -n main
tty59ce7b7e2019-12-04 22:49:38 +0800709 Trace the open syscall and only print event that process names containing "main"
evilpanf32f7722021-12-11 00:58:51 +0800710trace 'do_sys_open "%s", arg2@user' --uid 1001
711 Trace the open syscall and only print event that processes with user ID 1001
712trace 'do_sys_open "%s", arg2@user' -f config
tty55cf529e2019-12-06 17:52:56 +0800713 Trace the open syscall and print the filename being opened filtered by "config"
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800714trace 'sys_read (arg3 > 20000) "read %d bytes", arg3'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800715 Trace the read syscall and print a message for reads >20000 bytes
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000716trace 'r::do_sys_open "%llx", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800717 Trace the return from the open syscall and print the return value
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800718trace 'c:open (arg2 == 42) "%s %d", arg1, arg2'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800719 Trace the open() call from libc only if the flags (arg2) argument is 42
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800720trace 'c:malloc "size = %d", arg1'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800721 Trace malloc calls and print the size being allocated
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800722trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3'
723 Trace the write() call from libc to monitor writes to STDOUT
Mark Draytonaa6c9162016-11-03 15:36:29 +0000724trace 'r::__kmalloc (retval == 0) "kmalloc failed!"'
Sasha Goldshtein8acd0152016-02-22 02:25:03 -0800725 Trace returns from __kmalloc which returned a null pointer
Mark Draytonaa6c9162016-11-03 15:36:29 +0000726trace 'r:c:malloc (retval) "allocated = %x", retval'
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800727 Trace returns from malloc and print non-NULL allocated buffers
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300728trace 't:block:block_rq_complete "sectors=%d", args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800729 Trace the block_rq_complete kernel tracepoint and print # of tx sectors
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700730trace 'u:pthread:pthread_create (arg4 != 0)'
731 Trace the USDT probe pthread_create when its 4th argument is non-zero
Fuji Goro21625162020-03-08 08:16:54 +0000732trace 'u:pthread:libpthread:pthread_create (arg4 != 0)'
733 Ditto, but the provider name "libpthread" is specified.
Sasha Goldshtein23e72b82017-01-17 08:49:36 +0000734trace 'p::SyS_nanosleep(struct timespec *ts) "sleep for %lld ns", ts->tv_nsec'
735 Trace the nanosleep syscall and print the sleep duration in ns
yonghong-songc2a530b2019-10-20 09:35:55 -0700736trace -c /sys/fs/cgroup/system.slice/workload.service '__x64_sys_nanosleep' '__x64_sys_clone'
737 Trace nanosleep/clone syscall calls only under workload.service
738 cgroup hierarchy.
Yonghong Songf4470dc2017-12-13 14:12:13 -0800739trace -I 'linux/fs.h' \\
740 'p::uprobe_register(struct inode *inode) "a_ops = %llx", inode->i_mapping->a_ops'
741 Trace the uprobe_register inode mapping ops, and the symbol can be found
742 in /proc/kallsyms
743trace -I 'kernel/sched/sched.h' \\
744 'p::__account_cfs_rq_runtime(struct cfs_rq *cfs_rq) "%d", cfs_rq->runtime_remaining'
745 Trace the cfs scheduling runqueue remaining runtime. The struct cfs_rq is defined
746 in kernel/sched/sched.h which is in kernel source tree and not in kernel-devel
747 package. So this command needs to run at the kernel source tree root directory
748 so that the added header file can be found by the compiler.
tehnerd86293f02018-01-23 21:21:58 -0800749trace -I 'net/sock.h' \\
750 'udpv6_sendmsg(struct sock *sk) (sk->sk_dport == 13568)'
751 Trace udpv6 sendmsg calls only if socket's destination port is equal
752 to 53 (DNS; 13568 in big endian order)
Yonghong Songf92fef22018-01-24 20:51:46 -0800753trace -I 'linux/fs_struct.h' 'mntns_install "users = %d", $task->fs->users'
754 Trace the number of users accessing the file system of the current task
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800755"""
756
757 def __init__(self):
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300758 parser = argparse.ArgumentParser(description="Attach to " +
759 "functions and print trace messages.",
760 formatter_class=argparse.RawDescriptionHelpFormatter,
761 epilog=Tool.examples)
Mark Drayton5f5687e2017-02-20 18:13:03 +0000762 parser.add_argument("-b", "--buffer-pages", type=int,
763 default=Tool.DEFAULT_PERF_BUFFER_PAGES,
764 help="number of pages to use for perf_events ring buffer "
765 "(default: %(default)d)")
Mark Draytonaa6c9162016-11-03 15:36:29 +0000766 # we'll refer to the userspace concepts of "pid" and "tid" by
767 # their kernel names -- tgid and pid -- inside the script
768 parser.add_argument("-p", "--pid", type=int, metavar="PID",
769 dest="tgid", help="id of the process to trace (optional)")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000770 parser.add_argument("-L", "--tid", type=int, metavar="TID",
Mark Draytonaa6c9162016-11-03 15:36:29 +0000771 dest="pid", help="id of the thread to trace (optional)")
evilpanf32f7722021-12-11 00:58:51 +0800772 parser.add_argument("--uid", type=int, metavar="UID",
773 dest="uid", help="id of the user to trace (optional)")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800774 parser.add_argument("-v", "--verbose", action="store_true",
775 help="print resulting BPF program code before executing")
776 parser.add_argument("-Z", "--string-size", type=int,
777 default=80, help="maximum size to read from strings")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300778 parser.add_argument("-S", "--include-self",
779 action="store_true",
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800780 help="do not filter trace's own pid from the trace")
781 parser.add_argument("-M", "--max-events", type=int,
782 help="number of events to print before quitting")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000783 parser.add_argument("-t", "--timestamp", action="store_true",
784 help="print timestamp column (offset from trace start)")
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100785 parser.add_argument("-u", "--unix-timestamp", action="store_true",
786 help="print UNIX timestamp instead of offset from trace start, requires -t")
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000787 parser.add_argument("-T", "--time", action="store_true",
788 help="print time column")
Teng Qinc200b6c2017-12-16 00:15:55 -0800789 parser.add_argument("-C", "--print_cpu", action="store_true",
790 help="print CPU id")
Jonathan Giddyec0691e2021-02-21 09:44:26 +0000791 parser.add_argument("-c", "--cgroup-path", type=str,
792 metavar="CGROUP_PATH", dest="cgroup_path",
yonghong-songc2a530b2019-10-20 09:35:55 -0700793 help="cgroup path")
tty59ce7b7e2019-12-04 22:49:38 +0800794 parser.add_argument("-n", "--name", type=str,
795 help="only print process names containing this name")
tty55cf529e2019-12-06 17:52:56 +0800796 parser.add_argument("-f", "--msg-filter", type=str, dest="msg_filter",
797 help="only print the msg of event containing this string")
Nikita V. Shirokov3953c702018-07-27 16:13:47 -0700798 parser.add_argument("-B", "--bin_cmp", action="store_true",
799 help="allow to use STRCMP with binary values")
Jonathan Giddyec0691e2021-02-21 09:44:26 +0000800 parser.add_argument('-s', "--sym_file_list", type=str,
801 metavar="SYM_FILE_LIST", dest="sym_file_list",
vijunag9924e642019-01-23 12:35:33 +0530802 help="coma separated list of symbol files to use \
803 for symbol resolution")
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300804 parser.add_argument("-K", "--kernel-stack",
805 action="store_true", help="output kernel stack trace")
806 parser.add_argument("-U", "--user-stack",
807 action="store_true", help="output user stack trace")
Mirek Klimose5382282018-01-26 14:52:50 -0800808 parser.add_argument("-a", "--address", action="store_true",
809 help="print virtual address in stacks")
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800810 parser.add_argument(metavar="probe", dest="probes", nargs="+",
811 help="probe specifier (see examples)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300812 parser.add_argument("-I", "--include", action="append",
813 metavar="header",
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300814 help="additional header files to include in the BPF program "
Yonghong Songf4470dc2017-12-13 14:12:13 -0800815 "as either full path, "
816 "or relative to current working directory, "
817 "or relative to default kernel header search path")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100818 parser.add_argument("--ebpf", action="store_true",
819 help=argparse.SUPPRESS)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800820 self.args = parser.parse_args()
Mark Draytonaa6c9162016-11-03 15:36:29 +0000821 if self.args.tgid and self.args.pid:
Yonghong Songf4470dc2017-12-13 14:12:13 -0800822 parser.error("only one of -p and -L may be specified")
yonghong-songc2a530b2019-10-20 09:35:55 -0700823 if self.args.cgroup_path is not None:
824 self.cgroup_map_name = "__cgroup"
825 else:
826 self.cgroup_map_name = None
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800827
828 def _create_probes(self):
829 Probe.configure(self.args)
830 self.probes = []
831 for probe_spec in self.args.probes:
832 self.probes.append(Probe(
Teng Qin6b0ed372016-09-29 21:30:13 -0700833 probe_spec, self.args.string_size,
yonghong-songc2a530b2019-10-20 09:35:55 -0700834 self.args.kernel_stack, self.args.user_stack,
tty55cf529e2019-12-06 17:52:56 +0800835 self.cgroup_map_name, self.args.name, self.args.msg_filter))
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800836
837 def _generate_program(self):
838 self.program = """
839#include <linux/ptrace.h>
840#include <linux/sched.h> /* For TASK_COMM_LEN */
841
842"""
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300843 for include in (self.args.include or []):
ShelbyFrancesf5dbbdb2017-02-08 05:56:52 +0300844 if include.startswith((".", "/")):
845 include = os.path.abspath(include)
846 self.program += "#include \"%s\"\n" % include
847 else:
848 self.program += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700849 self.program += BPF.generate_auto_includes(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800850 map(lambda p: p.raw_probe, self.probes))
yonghong-songc2a530b2019-10-20 09:35:55 -0700851 if self.cgroup_map_name is not None:
852 self.program += "BPF_CGROUP_ARRAY(%s, 1);\n" % \
853 self.cgroup_map_name
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800854 for probe in self.probes:
855 self.program += probe.generate_program(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700856 self.args.include_self)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800857
Nathan Scottcf0792f2018-02-02 16:56:50 +1100858 if self.args.verbose or self.args.ebpf:
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800859 print(self.program)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100860 if self.args.ebpf:
861 exit()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800862
863 def _attach_probes(self):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300864 usdt_contexts = []
865 for probe in self.probes:
866 if probe.usdt:
867 # USDT probes must be enabled before the BPF object
868 # is initialized, because that's where the actual
869 # uprobe is being attached.
870 probe.usdt.enable_probe(
871 probe.usdt_name, probe.probe_name)
Sasha Goldshteinf733cac2016-10-04 18:39:01 +0300872 if self.args.verbose:
873 print(probe.usdt.get_text())
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300874 usdt_contexts.append(probe.usdt)
875 self.bpf = BPF(text=self.program, usdt_contexts=usdt_contexts)
vijunag9924e642019-01-23 12:35:33 +0530876 if self.args.sym_file_list is not None:
877 print("Note: Kernel bpf will report stack map with ip/build_id")
878 map(lambda x: self.bpf.add_module(x), self.args.sym_file_list.split(','))
yonghong-songc2a530b2019-10-20 09:35:55 -0700879
880 # if cgroup filter is requested, update the cgroup array map
881 if self.cgroup_map_name is not None:
882 cgroup_array = self.bpf.get_table(self.cgroup_map_name)
883 cgroup_array[0] = self.args.cgroup_path
884
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800885 for probe in self.probes:
886 if self.args.verbose:
887 print(probe)
888 probe.attach(self.bpf, self.args.verbose)
889
890 def _main_loop(self):
891 all_probes_trivial = all(map(Probe.is_default_action,
892 self.probes))
893
894 # Print header
Sasha Goldshtein49d50ba2016-12-19 10:17:38 +0000895 if self.args.timestamp or self.args.time:
Maik Riechert3a0d3c42019-05-23 17:57:10 +0100896 col_fmt = "%-17s " if self.args.unix_timestamp else "%-8s "
Jonathan Giddyec0691e2021-02-21 09:44:26 +0000897 print(col_fmt % "TIME", end="")
Teng Qinc200b6c2017-12-16 00:15:55 -0800898 if self.args.print_cpu:
Jonathan Giddyec0691e2021-02-21 09:44:26 +0000899 print("%-3s " % "CPU", end="")
Teng Qinc200b6c2017-12-16 00:15:55 -0800900 print("%-7s %-7s %-15s %-16s %s" %
901 ("PID", "TID", "COMM", "FUNC",
902 "-" if not all_probes_trivial else ""))
Alban Crequy8bb4e472019-12-21 16:09:53 +0100903 sys.stdout.flush()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800904
905 while True:
Teng Qindbf00292018-02-28 21:47:50 -0800906 self.bpf.perf_buffer_poll()
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800907
908 def run(self):
909 try:
910 self._create_probes()
911 self._generate_program()
912 self._attach_probes()
913 self._main_loop()
914 except:
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500915 exc_info = sys.exc_info()
916 sys_exit = exc_info[0] is SystemExit
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800917 if self.args.verbose:
918 traceback.print_exc()
Sasha Goldshtein2febc292017-02-13 20:25:32 -0500919 elif not sys_exit:
920 print(exc_info[1])
921 exit(0 if sys_exit else 1)
Sasha Goldshtein38847f02016-02-22 02:19:24 -0800922
923if __name__ == "__main__":
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300924 Tool().run()