blob: b49d549db1773f80a7e66540df5dda6152541688 [file] [log] [blame]
Sasha Goldshtein85384852016-02-12 01:29:39 -08001#!/usr/bin/env python
2#
Sasha Goldshtein7df65da2016-02-14 05:12:27 -08003# argdist Trace a function and display a distribution of its
Sasha Goldshteinfd60d552016-03-01 12:15:34 -08004# parameter values as a histogram or frequency count.
Sasha Goldshtein85384852016-02-12 01:29:39 -08005#
Sasha Goldshtein7df65da2016-02-14 05:12:27 -08006# USAGE: argdist [-h] [-p PID] [-z STRING_SIZE] [-i INTERVAL]
Sasha Goldshteind2f47622016-10-04 18:40:15 +03007# [-n COUNT] [-v] [-c] [-T TOP]
Sasha Goldshteinfd60d552016-03-01 12:15:34 -08008# [-C specifier [specifier ...]]
9# [-H specifier [specifier ...]]
10# [-I header [header ...]]
Sasha Goldshtein85384852016-02-12 01:29:39 -080011#
12# Licensed under the Apache License, Version 2.0 (the "License")
13# Copyright (C) 2016 Sasha Goldshtein.
14
Brendan Gregg4f88a942016-07-22 17:11:51 -070015from bcc import BPF, Tracepoint, Perf, USDT
Sasha Goldshtein85384852016-02-12 01:29:39 -080016from time import sleep, strftime
17import argparse
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080018import re
Sasha Goldshteinc9551302016-02-21 02:21:46 -080019import traceback
Sasha Goldshteinfd60d552016-03-01 12:15:34 -080020import os
Sasha Goldshteinc9551302016-02-21 02:21:46 -080021import sys
Sasha Goldshtein85384852016-02-12 01:29:39 -080022
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070023class Probe(object):
Sasha Goldshtein85384852016-02-12 01:29:39 -080024 next_probe_index = 0
Sasha Goldshtein5e4e1f42016-02-12 06:52:19 -080025 aliases = { "$PID": "bpf_get_current_pid_tgid()" }
26
27 def _substitute_aliases(self, expr):
28 if expr is None:
29 return expr
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070030 for alias, subst in Probe.aliases.items():
Sasha Goldshtein5e4e1f42016-02-12 06:52:19 -080031 expr = expr.replace(alias, subst)
32 return expr
Sasha Goldshtein85384852016-02-12 01:29:39 -080033
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080034 def _parse_signature(self):
35 params = map(str.strip, self.signature.split(','))
36 self.param_types = {}
37 for param in params:
38 # If the type is a pointer, the * can be next to the
39 # param name. Other complex types like arrays are not
40 # supported right now.
41 index = param.rfind('*')
42 index = index if index != -1 else param.rfind(' ')
43 param_type = param[0:index+1].strip()
44 param_name = param[index+1:].strip()
45 self.param_types[param_name] = param_type
46
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070047 def _generate_entry(self):
48 self.entry_probe_func = self.probe_func_name + "_entry"
49 text = """
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080050int PROBENAME(struct pt_regs *ctx SIGNATURE)
51{
52 u32 pid = bpf_get_current_pid_tgid();
53 PID_FILTER
54 COLLECT
55 return 0;
56}
57"""
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080058 text = text.replace("PROBENAME", self.entry_probe_func)
59 text = text.replace("SIGNATURE",
60 "" if len(self.signature) == 0 else ", " + self.signature)
61 pid_filter = "" if self.is_user or self.pid is None \
62 else "if (pid != %d) { return 0; }" % self.pid
63 text = text.replace("PID_FILTER", pid_filter)
64 collect = ""
65 for pname in self.args_to_probe:
Sasha Goldshteine3501152016-02-13 03:56:29 -080066 param_hash = self.hashname_prefix + pname
67 if pname == "__latency":
68 collect += """
69u64 __time = bpf_ktime_get_ns();
70%s.update(&pid, &__time);
71""" % param_hash
72 else:
73 collect += "%s.update(&pid, &%s);\n" % \
74 (param_hash, pname)
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080075 text = text.replace("COLLECT", collect)
76 return text
77
78 def _generate_entry_probe(self):
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080079 # Any $entry(name) expressions result in saving that argument
80 # when entering the function.
81 self.args_to_probe = set()
82 regex = r"\$entry\((\w+)\)"
Sasha Goldshteincc27edf2016-02-14 03:49:01 -080083 for expr in self.exprs:
84 for arg in re.finditer(regex, expr):
85 self.args_to_probe.add(arg.group(1))
Sasha Goldshteine3501152016-02-13 03:56:29 -080086 for arg in re.finditer(regex, self.filter):
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080087 self.args_to_probe.add(arg.group(1))
Sasha Goldshteincc27edf2016-02-14 03:49:01 -080088 if any(map(lambda expr: "$latency" in expr, self.exprs)) or \
89 "$latency" in self.filter:
Sasha Goldshteine3501152016-02-13 03:56:29 -080090 self.args_to_probe.add("__latency")
91 self.param_types["__latency"] = "u64" # nanoseconds
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080092 for pname in self.args_to_probe:
93 if pname not in self.param_types:
94 raise ValueError("$entry(%s): no such param" \
95 % arg)
96
97 self.hashname_prefix = "%s_param_" % self.probe_hash_name
98 text = ""
99 for pname in self.args_to_probe:
100 # Each argument is stored in a separate hash that is
101 # keyed by pid.
102 text += "BPF_HASH(%s, u32, %s);\n" % \
103 (self.hashname_prefix + pname,
104 self.param_types[pname])
105 text += self._generate_entry()
106 return text
107
108 def _generate_retprobe_prefix(self):
109 # After we're done here, there are __%s_val variables for each
110 # argument we needed to probe using $entry(name), and they all
111 # have values (which isn't necessarily the case if we missed
112 # the method entry probe).
113 text = "u32 __pid = bpf_get_current_pid_tgid();\n"
114 self.param_val_names = {}
115 for pname in self.args_to_probe:
116 val_name = "__%s_val" % pname
117 text += "%s *%s = %s.lookup(&__pid);\n" % \
118 (self.param_types[pname], val_name,
119 self.hashname_prefix + pname)
120 text += "if (%s == 0) { return 0 ; }\n" % val_name
121 self.param_val_names[pname] = val_name
122 return text
123
124 def _replace_entry_exprs(self):
125 for pname, vname in self.param_val_names.items():
Sasha Goldshteine3501152016-02-13 03:56:29 -0800126 if pname == "__latency":
127 entry_expr = "$latency"
128 val_expr = "(bpf_ktime_get_ns() - *%s)" % vname
129 else:
130 entry_expr = "$entry(%s)" % pname
131 val_expr = "(*%s)" % vname
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800132 for i in range(0, len(self.exprs)):
133 self.exprs[i] = self.exprs[i].replace(
134 entry_expr, val_expr)
Sasha Goldshteine3501152016-02-13 03:56:29 -0800135 self.filter = self.filter.replace(entry_expr,
136 val_expr)
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800137
138 def _attach_entry_probe(self):
139 if self.is_user:
140 self.bpf.attach_uprobe(name=self.library,
141 sym=self.function,
142 fn_name=self.entry_probe_func,
143 pid=self.pid or -1)
144 else:
145 self.bpf.attach_kprobe(event=self.function,
146 fn_name=self.entry_probe_func)
147
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800148 def _bail(self, error):
149 raise ValueError("error parsing probe '%s': %s" %
150 (self.raw_spec, error))
151
152 def _validate_specifier(self):
153 # Everything after '#' is the probe label, ignore it
154 spec = self.raw_spec.split('#')[0]
155 parts = spec.strip().split(':')
156 if len(parts) < 3:
157 self._bail("at least the probe type, library, and " +
158 "function signature must be specified")
159 if len(parts) > 6:
160 self._bail("extraneous ':'-separated parts detected")
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700161 if parts[0] not in ["r", "p", "t", "u"]:
162 self._bail("probe type must be 'p', 'r', 't', or 'u' " +
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800163 "but got '%s'" % parts[0])
164 if re.match(r"\w+\(.*\)", parts[2]) is None:
165 self._bail(("function signature '%s' has an invalid " +
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800166 "format") % parts[2])
167
168 def _parse_expr_types(self, expr_types):
169 if len(expr_types) == 0:
170 self._bail("no expr types specified")
171 self.expr_types = expr_types.split(',')
172
173 def _parse_exprs(self, exprs):
174 if len(exprs) == 0:
175 self._bail("no exprs specified")
176 self.exprs = exprs.split(',')
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800177
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300178 def __init__(self, tool, type, specifier):
179 self.usdt_ctx = None
180 self.pid = tool.args.pid
Sasha Goldshteind2f47622016-10-04 18:40:15 +0300181 self.cumulative = tool.args.cumulative or False
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800182 self.raw_spec = specifier
183 self._validate_specifier()
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800184
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800185 spec_and_label = specifier.split('#')
Sasha Goldshteined21adf2016-02-12 03:04:53 -0800186 self.label = spec_and_label[1] \
187 if len(spec_and_label) == 2 else None
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800188
Sasha Goldshteined21adf2016-02-12 03:04:53 -0800189 parts = spec_and_label[0].strip().split(':')
Sasha Goldshtein85384852016-02-12 01:29:39 -0800190 self.type = type # hist or freq
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800191 self.probe_type = parts[0]
Sasha Goldshtein85384852016-02-12 01:29:39 -0800192 fparts = parts[2].split('(')
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800193 self.function = fparts[0].strip()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800194 if self.probe_type == "t":
195 self.library = "" # kernel
196 self.tp_category = parts[1]
197 self.tp_event = self.function
Sasha Goldshteinc08c4312016-03-21 03:52:09 -0700198 self.tp = Tracepoint.enable_tracepoint(
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800199 self.tp_category, self.tp_event)
200 self.function = "perf_trace_" + self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700201 elif self.probe_type == "u":
202 self.library = parts[1]
Brendan Gregg4f88a942016-07-22 17:11:51 -0700203 self.probe_func_name = "%s_probe%d" % \
204 (self.function, Probe.next_probe_index)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300205 self._enable_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800206 else:
207 self.library = parts[1]
208 self.is_user = len(self.library) > 0
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800209 self.signature = fparts[1].strip()[:-1]
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800210 self._parse_signature()
211
212 # If the user didn't specify an expression to probe, we probe
213 # the retval in a ret probe, or simply the value "1" otherwise.
Sasha Goldshtein85384852016-02-12 01:29:39 -0800214 self.is_default_expr = len(parts) < 5
215 if not self.is_default_expr:
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800216 self._parse_expr_types(parts[3])
217 self._parse_exprs(parts[4])
218 if len(self.exprs) != len(self.expr_types):
219 self._bail("mismatched # of exprs and types")
220 if self.type == "hist" and len(self.expr_types) > 1:
221 self._bail("histograms can only have 1 expr")
Sasha Goldshtein85384852016-02-12 01:29:39 -0800222 else:
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800223 if not self.probe_type == "r" and self.type == "hist":
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800224 self._bail("histograms must have expr")
225 self.expr_types = \
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800226 ["u64" if not self.probe_type == "r" else "int"]
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800227 self.exprs = \
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800228 ["1" if not self.probe_type == "r" else "$retval"]
Sasha Goldshteine3501152016-02-13 03:56:29 -0800229 self.filter = "" if len(parts) != 6 else parts[5]
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800230 self._substitute_exprs()
231
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800232 # Do we need to attach an entry probe so that we can collect an
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800233 # argument that is required for an exit (return) probe?
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800234 def check(expr):
235 keywords = ["$entry", "$latency"]
236 return any(map(lambda kw: kw in expr, keywords))
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800237 self.entry_probe_required = self.probe_type == "r" and \
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800238 (any(map(check, self.exprs)) or check(self.filter))
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800239
Sasha Goldshtein85384852016-02-12 01:29:39 -0800240 self.probe_func_name = "%s_probe%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700241 (self.function, Probe.next_probe_index)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800242 self.probe_hash_name = "%s_hash%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700243 (self.function, Probe.next_probe_index)
244 Probe.next_probe_index += 1
245
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300246 def _enable_usdt_probe(self):
247 self.usdt_ctx = USDT(path=self.library, pid=self.pid)
248 self.usdt_ctx.enable_probe(
249 self.function, self.probe_func_name)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800250
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800251 def _substitute_exprs(self):
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800252 def repl(expr):
253 expr = self._substitute_aliases(expr)
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530254 return expr.replace("$retval", "PT_REGS_RC(ctx)")
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800255 for i in range(0, len(self.exprs)):
256 self.exprs[i] = repl(self.exprs[i])
257 self.filter = repl(self.filter)
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800258
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800259 def _is_string(self, expr_type):
260 return expr_type == "char*" or expr_type == "char *"
Sasha Goldshtein85384852016-02-12 01:29:39 -0800261
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800262 def _generate_hash_field(self, i):
263 if self._is_string(self.expr_types[i]):
264 return "struct __string_t v%d;\n" % i
265 else:
266 return "%s v%d;\n" % (self.expr_types[i], i)
267
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300268 def _generate_usdt_arg_assignment(self, i):
269 expr = self.exprs[i]
270 if self.probe_type == "u" and expr[0:3] == "arg":
271 return (" u64 %s = 0;\n" +
272 " bpf_usdt_readarg(%s, ctx, &%s);\n") % \
273 (expr, expr[3], expr)
274 else:
275 return ""
276
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800277 def _generate_field_assignment(self, i):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300278 text = self._generate_usdt_arg_assignment(i)
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800279 if self._is_string(self.expr_types[i]):
Brendan Gregg4f88a942016-07-22 17:11:51 -0700280 return (text + " bpf_probe_read(&__key.v%d.s," +
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700281 " sizeof(__key.v%d.s), (void *)%s);\n") % \
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800282 (i, i, self.exprs[i])
283 else:
Brendan Gregg4f88a942016-07-22 17:11:51 -0700284 return text + " __key.v%d = %s;\n" % \
285 (i, self.exprs[i])
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800286
287 def _generate_hash_decl(self):
288 if self.type == "hist":
289 return "BPF_HISTOGRAM(%s, %s);" % \
290 (self.probe_hash_name, self.expr_types[0])
291 else:
292 text = "struct %s_key_t {\n" % self.probe_hash_name
293 for i in range(0, len(self.expr_types)):
294 text += self._generate_hash_field(i)
295 text += "};\n"
296 text += "BPF_HASH(%s, struct %s_key_t, u64);\n" % \
297 (self.probe_hash_name, self.probe_hash_name)
298 return text
299
300 def _generate_key_assignment(self):
301 if self.type == "hist":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300302 return self._generate_usdt_arg_assignment(0) + \
303 ("%s __key = %s;\n" % \
304 (self.expr_types[0], self.exprs[0]))
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800305 else:
306 text = "struct %s_key_t __key = {};\n" % \
307 self.probe_hash_name
308 for i in range(0, len(self.exprs)):
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800309 text += self._generate_field_assignment(i)
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800310 return text
311
312 def _generate_hash_update(self):
313 if self.type == "hist":
314 return "%s.increment(bpf_log2l(__key));" % \
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800315 self.probe_hash_name
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800316 else:
317 return "%s.increment(__key);" % self.probe_hash_name
318
319 def _generate_pid_filter(self):
320 # Kernel probes need to explicitly filter pid, because the
321 # attach interface doesn't support pid filtering
322 if self.pid is not None and not self.is_user:
323 return "u32 pid = bpf_get_current_pid_tgid();\n" + \
324 "if (pid != %d) { return 0; }" % self.pid
325 else:
326 return ""
327
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800328 def generate_text(self):
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800329 program = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700330 probe_text = """
331DATA_DECL
332
Brendan Gregg4f88a942016-07-22 17:11:51 -0700333int PROBENAME(struct pt_regs *ctx SIGNATURE)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700334{
335 PID_FILTER
336 PREFIX
337 if (!(FILTER)) return 0;
338 KEY_EXPR
339 COLLECT
340 return 0;
341}
342"""
343 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700344 signature = ""
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800345
346 # If any entry arguments are probed in a ret probe, we need
347 # to generate an entry probe to collect them
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800348 if self.entry_probe_required:
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800349 program += self._generate_entry_probe()
350 prefix += self._generate_retprobe_prefix()
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800351 # Replace $entry(paramname) with a reference to the
352 # value we collected when entering the function:
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800353 self._replace_entry_exprs()
354
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800355 if self.probe_type == "t":
Sasha Goldshteinc08c4312016-03-21 03:52:09 -0700356 program += self.tp.generate_struct()
357 prefix += self.tp.generate_get_struct()
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700358 elif self.probe_type == "p" and len(self.signature) > 0:
359 # Only entry uprobes/kprobes can have user-specified
360 # signatures. Other probes force it to ().
361 signature = ", " + self.signature
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800362
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700363 program += probe_text.replace("PROBENAME", self.probe_func_name)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800364 program = program.replace("SIGNATURE", signature)
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800365 program = program.replace("PID_FILTER",
366 self._generate_pid_filter())
367
368 decl = self._generate_hash_decl()
369 key_expr = self._generate_key_assignment()
370 collect = self._generate_hash_update()
Sasha Goldshtein85384852016-02-12 01:29:39 -0800371 program = program.replace("DATA_DECL", decl)
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800372 program = program.replace("KEY_EXPR", key_expr)
Sasha Goldshteine3501152016-02-13 03:56:29 -0800373 program = program.replace("FILTER",
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800374 "1" if len(self.filter) == 0 else self.filter)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800375 program = program.replace("COLLECT", collect)
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800376 program = program.replace("PREFIX", prefix)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700377
Sasha Goldshtein85384852016-02-12 01:29:39 -0800378 return program
379
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700380 def _attach_u(self):
381 libpath = BPF.find_library(self.library)
382 if libpath is None:
Sasha Goldshteinec679712016-10-04 18:33:36 +0300383 libpath = BPF.find_exe(self.library)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700384 if libpath is None or len(libpath) == 0:
Sasha Goldshtein5a1d2e32016-03-30 08:14:44 -0700385 self._bail("unable to find library %s" % self.library)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700386
Brendan Gregg4f88a942016-07-22 17:11:51 -0700387 if self.probe_type == "r":
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700388 self.bpf.attach_uretprobe(name=libpath,
389 sym=self.function,
390 fn_name=self.probe_func_name,
391 pid=self.pid or -1)
392 else:
393 self.bpf.attach_uprobe(name=libpath,
394 sym=self.function,
395 fn_name=self.probe_func_name,
396 pid=self.pid or -1)
397
398 def _attach_k(self):
399 if self.probe_type == "r" or self.probe_type == "t":
400 self.bpf.attach_kretprobe(event=self.function,
401 fn_name=self.probe_func_name)
402 else:
403 self.bpf.attach_kprobe(event=self.function,
404 fn_name=self.probe_func_name)
405
Sasha Goldshtein85384852016-02-12 01:29:39 -0800406 def attach(self, bpf):
407 self.bpf = bpf
Brendan Gregg4f88a942016-07-22 17:11:51 -0700408 if self.probe_type == "u": return;
Sasha Goldshtein85384852016-02-12 01:29:39 -0800409 if self.is_user:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700410 self._attach_u()
Sasha Goldshtein85384852016-02-12 01:29:39 -0800411 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700412 self._attach_k()
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800413 if self.entry_probe_required:
414 self._attach_entry_probe()
Sasha Goldshtein85384852016-02-12 01:29:39 -0800415
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800416 def _v2s(self, v):
417 # Most fields can be converted with plain str(), but strings
418 # are wrapped in a __string_t which has an .s field
419 if "__string_t" in type(v).__name__:
420 return str(v.s)
421 return str(v)
422
423 def _display_expr(self, i):
424 # Replace ugly latency calculation with $latency
425 expr = self.exprs[i].replace(
426 "(bpf_ktime_get_ns() - *____latency_val)", "$latency")
427 # Replace alias values back with the alias name
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700428 for alias, subst in Probe.aliases.items():
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800429 expr = expr.replace(subst, alias)
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800430 # Replace retval expression with $retval
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530431 expr = expr.replace("PT_REGS_RC(ctx)", "$retval")
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800432 # Replace ugly (*__param_val) expressions with param name
433 return re.sub(r"\(\*__(\w+)_val\)", r"\1", expr)
434
435 def _display_key(self, key):
436 if self.is_default_expr:
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800437 if not self.probe_type == "r":
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800438 return "total calls"
439 else:
440 return "retval = %s" % str(key.v0)
441 else:
442 # The key object has v0, ..., vk fields containing
443 # the values of the expressions from self.exprs
444 def str_i(i):
445 key_i = self._v2s(getattr(key, "v%d" % i))
446 return "%s = %s" % \
447 (self._display_expr(i), key_i)
448 return ", ".join(map(str_i, range(0, len(self.exprs))))
449
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800450 def display(self, top):
Sasha Goldshtein85384852016-02-12 01:29:39 -0800451 data = self.bpf.get_table(self.probe_hash_name)
452 if self.type == "freq":
Sasha Goldshteine3501152016-02-13 03:56:29 -0800453 print(self.label or self.raw_spec)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800454 print("\t%-10s %s" % ("COUNT", "EVENT"))
Sasha Goldshteind2f47622016-10-04 18:40:15 +0300455 sdata = sorted(data.items(), key=lambda kv: kv[1].value)
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800456 if top is not None:
Sasha Goldshteind2f47622016-10-04 18:40:15 +0300457 sdata = sdata[-top:]
458 for key, value in sdata:
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800459 # Print some nice values if the user didn't
460 # specify an expression to probe
Sasha Goldshtein85384852016-02-12 01:29:39 -0800461 if self.is_default_expr:
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800462 if not self.probe_type == "r":
Sasha Goldshtein85384852016-02-12 01:29:39 -0800463 key_str = "total calls"
464 else:
465 key_str = "retval = %s" % \
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800466 self._v2s(key.v0)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800467 else:
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800468 key_str = self._display_key(key)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800469 print("\t%-10s %s" % \
470 (str(value.value), key_str))
471 elif self.type == "hist":
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800472 label = self.label or (self._display_expr(0)
473 if not self.is_default_expr else "retval")
Sasha Goldshtein85384852016-02-12 01:29:39 -0800474 data.print_log2_hist(val_type=label)
Sasha Goldshteind2f47622016-10-04 18:40:15 +0300475 if not self.cumulative:
476 data.clear()
Sasha Goldshtein85384852016-02-12 01:29:39 -0800477
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700478 def __str__(self):
479 return self.label or self.raw_spec
480
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800481class Tool(object):
482 examples = """
Sasha Goldshtein85384852016-02-12 01:29:39 -0800483Probe specifier syntax:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700484 {p,r,t,u}:{[library],category}:function(signature)[:type[,type...]:expr[,expr...][:filter]][#label]
Sasha Goldshtein85384852016-02-12 01:29:39 -0800485Where:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700486 p,r,t,u -- probe at function entry, function exit, kernel tracepoint,
487 or USDT probe
Sasha Goldshteine3501152016-02-13 03:56:29 -0800488 in exit probes: can use $retval, $entry(param), $latency
Sasha Goldshtein85384852016-02-12 01:29:39 -0800489 library -- the library that contains the function
490 (leave empty for kernel functions)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800491 category -- the category of the kernel tracepoint (e.g. net, sched)
492 function -- the function name to trace (or tracepoint name)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800493 signature -- the function's parameters, as in the C header
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800494 type -- the type of the expression to collect (supports multiple)
495 expr -- the expression to collect (supports multiple)
Sasha Goldshteined21adf2016-02-12 03:04:53 -0800496 filter -- the filter that is applied to collected values
497 label -- the label for this probe in the resulting output
Sasha Goldshtein85384852016-02-12 01:29:39 -0800498
499EXAMPLES:
500
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800501argdist -H 'p::__kmalloc(u64 size):u64:size'
Sasha Goldshtein85384852016-02-12 01:29:39 -0800502 Print a histogram of allocation sizes passed to kmalloc
503
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800504argdist -p 1005 -C 'p:c:malloc(size_t size):size_t:size:size==16'
Sasha Goldshtein85384852016-02-12 01:29:39 -0800505 Print a frequency count of how many times process 1005 called malloc
506 with an allocation size of 16 bytes
507
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800508argdist -C 'r:c:gets():char*:(char*)$retval#snooped strings'
Sasha Goldshtein85384852016-02-12 01:29:39 -0800509 Snoop on all strings returned by gets()
510
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800511argdist -H 'r::__kmalloc(size_t size):u64:$latency/$entry(size)#ns per byte'
Sasha Goldshteine3501152016-02-13 03:56:29 -0800512 Print a histogram of nanoseconds per byte from kmalloc allocations
513
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800514argdist -C 'p::__kmalloc(size_t size, gfp_t flags):size_t:size:flags&GFP_ATOMIC'
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800515 Print frequency count of kmalloc allocation sizes that have GFP_ATOMIC
516
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800517argdist -p 1005 -C 'p:c:write(int fd):int:fd' -T 5
Sasha Goldshtein85384852016-02-12 01:29:39 -0800518 Print frequency counts of how many times writes were issued to a
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800519 particular file descriptor number, in process 1005, but only show
520 the top 5 busiest fds
Sasha Goldshtein85384852016-02-12 01:29:39 -0800521
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800522argdist -p 1005 -H 'r:c:read()'
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800523 Print a histogram of results (sizes) returned by read() in process 1005
Sasha Goldshtein85384852016-02-12 01:29:39 -0800524
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800525argdist -C 'r::__vfs_read():u32:$PID:$latency > 100000'
Sasha Goldshteine3501152016-02-13 03:56:29 -0800526 Print frequency of reads by process where the latency was >0.1ms
527
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800528argdist -H 'r::__vfs_read(void *file, void *buf, size_t count):size_t:$entry(count):$latency > 1000000'
Sasha Goldshteine3501152016-02-13 03:56:29 -0800529 Print a histogram of read sizes that were longer than 1ms
530
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800531argdist -H \\
Sasha Goldshteined21adf2016-02-12 03:04:53 -0800532 'p:c:write(int fd, const void *buf, size_t count):size_t:count:fd==1'
Sasha Goldshtein85384852016-02-12 01:29:39 -0800533 Print a histogram of buffer sizes passed to write() across all
534 processes, where the file descriptor was 1 (STDOUT)
535
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800536argdist -C 'p:c:fork()#fork calls'
Sasha Goldshtein85384852016-02-12 01:29:39 -0800537 Count fork() calls in libc across all processes
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800538 Can also use funccount.py, which is easier and more flexible
Sasha Goldshtein85384852016-02-12 01:29:39 -0800539
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800540argdist -H 't:block:block_rq_complete():u32:tp.nr_sector'
541 Print histogram of number of sectors in completing block I/O requests
542
543argdist -C 't:irq:irq_handler_entry():int:tp.irq'
544 Aggregate interrupts by interrupt request (IRQ)
545
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700546argdist -C 'u:pthread:pthread_start():u64:arg2' -p 1337
547 Print frequency of function addresses used as a pthread start function,
548 relying on the USDT pthread_start probe in process 1337
549
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800550argdist -H \\
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800551 'p:c:sleep(u32 seconds):u32:seconds' \\
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800552 'p:c:nanosleep(struct timespec *req):long:req->tv_nsec'
Sasha Goldshtein85384852016-02-12 01:29:39 -0800553 Print histograms of sleep() and nanosleep() parameter values
554
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800555argdist -p 2780 -z 120 \\
Sasha Goldshteined21adf2016-02-12 03:04:53 -0800556 -C 'p:c:write(int fd, char* buf, size_t len):char*:buf:fd==1'
Sasha Goldshtein85384852016-02-12 01:29:39 -0800557 Spy on writes to STDOUT performed by process 2780, up to a string size
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800558 of 120 characters
Sasha Goldshtein85384852016-02-12 01:29:39 -0800559"""
560
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800561 def __init__(self):
562 parser = argparse.ArgumentParser(description="Trace a " +
563 "function and display a summary of its parameter values.",
564 formatter_class=argparse.RawDescriptionHelpFormatter,
565 epilog=Tool.examples)
566 parser.add_argument("-p", "--pid", type=int,
567 help="id of the process to trace (optional)")
568 parser.add_argument("-z", "--string-size", default=80,
569 type=int,
570 help="maximum string size to read from char* arguments")
571 parser.add_argument("-i", "--interval", default=1, type=int,
572 help="output interval, in seconds")
573 parser.add_argument("-n", "--number", type=int, dest="count",
574 help="number of outputs")
575 parser.add_argument("-v", "--verbose", action="store_true",
576 help="print resulting BPF program code before executing")
Sasha Goldshteind2f47622016-10-04 18:40:15 +0300577 parser.add_argument("-c", "--cumulative", action="store_true",
578 help="do not clear histograms and freq counts at each interval")
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800579 parser.add_argument("-T", "--top", type=int,
580 help="number of top results to show (not applicable to " +
581 "histograms)")
582 parser.add_argument("-H", "--histogram", nargs="*",
583 dest="histspecifier", metavar="specifier",
584 help="probe specifier to capture histogram of " +
585 "(see examples below)")
586 parser.add_argument("-C", "--count", nargs="*",
587 dest="countspecifier", metavar="specifier",
588 help="probe specifier to capture count of " +
589 "(see examples below)")
590 parser.add_argument("-I", "--include", nargs="*",
591 metavar="header",
592 help="additional header files to include in the BPF program")
593 self.args = parser.parse_args()
Brendan Gregg4f88a942016-07-22 17:11:51 -0700594 self.usdt_ctx = None
Sasha Goldshtein85384852016-02-12 01:29:39 -0800595
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700596 def _create_probes(self):
597 self.probes = []
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800598 for specifier in (self.args.countspecifier or []):
Brendan Gregg4f88a942016-07-22 17:11:51 -0700599 self.probes.append(Probe(self, "freq", specifier))
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800600 for histspecifier in (self.args.histspecifier or []):
Brendan Gregg4f88a942016-07-22 17:11:51 -0700601 self.probes.append(Probe(self, "hist", histspecifier))
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700602 if len(self.probes) == 0:
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800603 print("at least one specifier is required")
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800604 exit()
Sasha Goldshtein85384852016-02-12 01:29:39 -0800605
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800606 def _generate_program(self):
607 bpf_source = """
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800608struct __string_t { char s[%d]; };
609
610#include <uapi/linux/ptrace.h>
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800611 """ % self.args.string_size
612 for include in (self.args.include or []):
613 bpf_source += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700614 bpf_source += BPF.generate_auto_includes(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700615 map(lambda p: p.raw_spec, self.probes))
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800616 bpf_source += Tracepoint.generate_decl()
617 bpf_source += Tracepoint.generate_entry_probe()
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700618 for probe in self.probes:
619 bpf_source += probe.generate_text()
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800620 if self.args.verbose:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300621 for text in [probe.usdt_ctx.get_text() \
622 for probe in self.probes if probe.usdt_ctx]:
623 print(text)
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800624 print(bpf_source)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300625 usdt_contexts = [probe.usdt_ctx
626 for probe in self.probes if probe.usdt_ctx]
627 self.bpf = BPF(text=bpf_source, usdt_contexts=usdt_contexts)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800628
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800629 def _attach(self):
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800630 Tracepoint.attach(self.bpf)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700631 for probe in self.probes:
632 probe.attach(self.bpf)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800633 if self.args.verbose:
Mark Draytoncb679d72016-07-15 23:55:22 +0100634 print("open uprobes: %s" % self.bpf.open_uprobes)
635 print("open kprobes: %s" % self.bpf.open_kprobes)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800636
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800637 def _main_loop(self):
638 count_so_far = 0
639 while True:
640 try:
641 sleep(self.args.interval)
642 except KeyboardInterrupt:
643 exit()
644 print("[%s]" % strftime("%H:%M:%S"))
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700645 for probe in self.probes:
646 probe.display(self.args.top)
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800647 count_so_far += 1
648 if self.args.count is not None and \
649 count_so_far >= self.args.count:
650 exit()
Sasha Goldshtein85384852016-02-12 01:29:39 -0800651
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800652 def run(self):
653 try:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700654 self._create_probes()
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800655 self._generate_program()
656 self._attach()
657 self._main_loop()
658 except:
659 if self.args.verbose:
660 traceback.print_exc()
Brenden Blancobc94d4c2016-05-05 12:05:07 -0700661 elif sys.exc_info()[0] is not SystemExit:
662 print(sys.exc_info()[1])
Sasha Goldshtein85384852016-02-12 01:29:39 -0800663
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800664if __name__ == "__main__":
665 Tool().run()