blob: 2e3aad5d976c3be50aa717be82631990310db0e2 [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 Goldshtein4725a722016-10-18 20:54:47 +03006# USAGE: argdist [-h] [-p PID] [-z STRING_SIZE] [-i INTERVAL] [-n COUNT] [-v]
7# [-c] [-T TOP] [-C specifier] [-H specifier] [-I header]
Sasha Goldshtein85384852016-02-12 01:29:39 -08008#
9# Licensed under the Apache License, Version 2.0 (the "License")
10# Copyright (C) 2016 Sasha Goldshtein.
11
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +030012from bcc import BPF, USDT
Sasha Goldshtein85384852016-02-12 01:29:39 -080013from time import sleep, strftime
14import argparse
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080015import re
Sasha Goldshteinc9551302016-02-21 02:21:46 -080016import traceback
Sasha Goldshteinfd60d552016-03-01 12:15:34 -080017import os
Sasha Goldshteinc9551302016-02-21 02:21:46 -080018import sys
Sasha Goldshtein85384852016-02-12 01:29:39 -080019
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070020class Probe(object):
Sasha Goldshtein85384852016-02-12 01:29:39 -080021 next_probe_index = 0
Sasha Goldshteinc8f752f2016-10-17 02:18:43 -070022 streq_index = 0
Sasha Goldshteinf41ae862016-10-19 01:14:30 +030023 aliases = {"$PID": "bpf_get_current_pid_tgid()"}
Sasha Goldshtein5e4e1f42016-02-12 06:52:19 -080024
25 def _substitute_aliases(self, expr):
26 if expr is None:
27 return expr
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070028 for alias, subst in Probe.aliases.items():
Sasha Goldshtein5e4e1f42016-02-12 06:52:19 -080029 expr = expr.replace(alias, subst)
30 return expr
Sasha Goldshtein85384852016-02-12 01:29:39 -080031
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080032 def _parse_signature(self):
33 params = map(str.strip, self.signature.split(','))
34 self.param_types = {}
35 for param in params:
36 # If the type is a pointer, the * can be next to the
37 # param name. Other complex types like arrays are not
38 # supported right now.
39 index = param.rfind('*')
40 index = index if index != -1 else param.rfind(' ')
Sasha Goldshteinf41ae862016-10-19 01:14:30 +030041 param_type = param[0:index + 1].strip()
42 param_name = param[index + 1:].strip()
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080043 self.param_types[param_name] = param_type
44
Sasha Goldshtein3e39a082016-03-24 08:39:47 -070045 def _generate_entry(self):
46 self.entry_probe_func = self.probe_func_name + "_entry"
47 text = """
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080048int PROBENAME(struct pt_regs *ctx SIGNATURE)
49{
50 u32 pid = bpf_get_current_pid_tgid();
51 PID_FILTER
52 COLLECT
53 return 0;
54}
55"""
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080056 text = text.replace("PROBENAME", self.entry_probe_func)
57 text = text.replace("SIGNATURE",
58 "" if len(self.signature) == 0 else ", " + self.signature)
59 pid_filter = "" if self.is_user or self.pid is None \
60 else "if (pid != %d) { return 0; }" % self.pid
61 text = text.replace("PID_FILTER", pid_filter)
62 collect = ""
63 for pname in self.args_to_probe:
Sasha Goldshteine3501152016-02-13 03:56:29 -080064 param_hash = self.hashname_prefix + pname
65 if pname == "__latency":
66 collect += """
67u64 __time = bpf_ktime_get_ns();
68%s.update(&pid, &__time);
Sasha Goldshteinf41ae862016-10-19 01:14:30 +030069 """ % param_hash
Sasha Goldshteine3501152016-02-13 03:56:29 -080070 else:
71 collect += "%s.update(&pid, &%s);\n" % \
72 (param_hash, pname)
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080073 text = text.replace("COLLECT", collect)
74 return text
75
76 def _generate_entry_probe(self):
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080077 # Any $entry(name) expressions result in saving that argument
78 # when entering the function.
79 self.args_to_probe = set()
80 regex = r"\$entry\((\w+)\)"
Sasha Goldshteincc27edf2016-02-14 03:49:01 -080081 for expr in self.exprs:
82 for arg in re.finditer(regex, expr):
83 self.args_to_probe.add(arg.group(1))
Sasha Goldshteine3501152016-02-13 03:56:29 -080084 for arg in re.finditer(regex, self.filter):
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080085 self.args_to_probe.add(arg.group(1))
Sasha Goldshteincc27edf2016-02-14 03:49:01 -080086 if any(map(lambda expr: "$latency" in expr, self.exprs)) or \
87 "$latency" in self.filter:
Sasha Goldshteine3501152016-02-13 03:56:29 -080088 self.args_to_probe.add("__latency")
89 self.param_types["__latency"] = "u64" # nanoseconds
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080090 for pname in self.args_to_probe:
91 if pname not in self.param_types:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +030092 raise ValueError("$entry(%s): no such param" %
93 arg)
Sasha Goldshtein392d5c82016-02-12 11:14:20 -080094
95 self.hashname_prefix = "%s_param_" % self.probe_hash_name
96 text = ""
97 for pname in self.args_to_probe:
98 # Each argument is stored in a separate hash that is
99 # keyed by pid.
100 text += "BPF_HASH(%s, u32, %s);\n" % \
101 (self.hashname_prefix + pname,
102 self.param_types[pname])
103 text += self._generate_entry()
104 return text
105
106 def _generate_retprobe_prefix(self):
107 # After we're done here, there are __%s_val variables for each
108 # argument we needed to probe using $entry(name), and they all
109 # have values (which isn't necessarily the case if we missed
110 # the method entry probe).
111 text = "u32 __pid = bpf_get_current_pid_tgid();\n"
112 self.param_val_names = {}
113 for pname in self.args_to_probe:
114 val_name = "__%s_val" % pname
115 text += "%s *%s = %s.lookup(&__pid);\n" % \
116 (self.param_types[pname], val_name,
117 self.hashname_prefix + pname)
118 text += "if (%s == 0) { return 0 ; }\n" % val_name
119 self.param_val_names[pname] = val_name
120 return text
121
122 def _replace_entry_exprs(self):
123 for pname, vname in self.param_val_names.items():
Sasha Goldshteine3501152016-02-13 03:56:29 -0800124 if pname == "__latency":
125 entry_expr = "$latency"
126 val_expr = "(bpf_ktime_get_ns() - *%s)" % vname
127 else:
128 entry_expr = "$entry(%s)" % pname
129 val_expr = "(*%s)" % vname
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800130 for i in range(0, len(self.exprs)):
131 self.exprs[i] = self.exprs[i].replace(
132 entry_expr, val_expr)
Sasha Goldshteine3501152016-02-13 03:56:29 -0800133 self.filter = self.filter.replace(entry_expr,
134 val_expr)
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800135
136 def _attach_entry_probe(self):
137 if self.is_user:
138 self.bpf.attach_uprobe(name=self.library,
139 sym=self.function,
140 fn_name=self.entry_probe_func,
141 pid=self.pid or -1)
142 else:
143 self.bpf.attach_kprobe(event=self.function,
144 fn_name=self.entry_probe_func)
145
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800146 def _bail(self, error):
147 raise ValueError("error parsing probe '%s': %s" %
148 (self.raw_spec, error))
149
150 def _validate_specifier(self):
151 # Everything after '#' is the probe label, ignore it
152 spec = self.raw_spec.split('#')[0]
153 parts = spec.strip().split(':')
154 if len(parts) < 3:
155 self._bail("at least the probe type, library, and " +
156 "function signature must be specified")
157 if len(parts) > 6:
158 self._bail("extraneous ':'-separated parts detected")
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700159 if parts[0] not in ["r", "p", "t", "u"]:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300160 self._bail("probe type must be 'p', 'r', 't', or 'u'" +
161 " but got '%s'" % parts[0])
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800162 if re.match(r"\w+\(.*\)", parts[2]) is None:
163 self._bail(("function signature '%s' has an invalid " +
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800164 "format") % parts[2])
165
166 def _parse_expr_types(self, expr_types):
167 if len(expr_types) == 0:
168 self._bail("no expr types specified")
169 self.expr_types = expr_types.split(',')
170
171 def _parse_exprs(self, exprs):
172 if len(exprs) == 0:
173 self._bail("no exprs specified")
174 self.exprs = exprs.split(',')
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800175
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300176 def __init__(self, tool, type, specifier):
177 self.usdt_ctx = None
Sasha Goldshteinc8f752f2016-10-17 02:18:43 -0700178 self.streq_functions = ""
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300179 self.pid = tool.args.pid
Sasha Goldshteind2f47622016-10-04 18:40:15 +0300180 self.cumulative = tool.args.cumulative or False
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800181 self.raw_spec = specifier
182 self._validate_specifier()
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800183
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800184 spec_and_label = specifier.split('#')
Sasha Goldshteined21adf2016-02-12 03:04:53 -0800185 self.label = spec_and_label[1] \
186 if len(spec_and_label) == 2 else None
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800187
Sasha Goldshteined21adf2016-02-12 03:04:53 -0800188 parts = spec_and_label[0].strip().split(':')
Sasha Goldshtein85384852016-02-12 01:29:39 -0800189 self.type = type # hist or freq
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800190 self.probe_type = parts[0]
Sasha Goldshtein85384852016-02-12 01:29:39 -0800191 fparts = parts[2].split('(')
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800192 self.function = fparts[0].strip()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800193 if self.probe_type == "t":
194 self.library = "" # kernel
195 self.tp_category = parts[1]
196 self.tp_event = self.function
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700197 elif self.probe_type == "u":
198 self.library = parts[1]
Brendan Gregg4f88a942016-07-22 17:11:51 -0700199 self.probe_func_name = "%s_probe%d" % \
200 (self.function, Probe.next_probe_index)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300201 self._enable_usdt_probe()
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800202 else:
203 self.library = parts[1]
204 self.is_user = len(self.library) > 0
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800205 self.signature = fparts[1].strip()[:-1]
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800206 self._parse_signature()
207
208 # If the user didn't specify an expression to probe, we probe
209 # the retval in a ret probe, or simply the value "1" otherwise.
Sasha Goldshtein85384852016-02-12 01:29:39 -0800210 self.is_default_expr = len(parts) < 5
211 if not self.is_default_expr:
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800212 self._parse_expr_types(parts[3])
213 self._parse_exprs(parts[4])
214 if len(self.exprs) != len(self.expr_types):
215 self._bail("mismatched # of exprs and types")
216 if self.type == "hist" and len(self.expr_types) > 1:
217 self._bail("histograms can only have 1 expr")
Sasha Goldshtein85384852016-02-12 01:29:39 -0800218 else:
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800219 if not self.probe_type == "r" and self.type == "hist":
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800220 self._bail("histograms must have expr")
221 self.expr_types = \
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800222 ["u64" if not self.probe_type == "r" else "int"]
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800223 self.exprs = \
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800224 ["1" if not self.probe_type == "r" else "$retval"]
Sasha Goldshteine3501152016-02-13 03:56:29 -0800225 self.filter = "" if len(parts) != 6 else parts[5]
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800226 self._substitute_exprs()
227
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800228 # Do we need to attach an entry probe so that we can collect an
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800229 # argument that is required for an exit (return) probe?
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800230 def check(expr):
231 keywords = ["$entry", "$latency"]
232 return any(map(lambda kw: kw in expr, keywords))
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800233 self.entry_probe_required = self.probe_type == "r" and \
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800234 (any(map(check, self.exprs)) or check(self.filter))
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800235
Sasha Goldshtein85384852016-02-12 01:29:39 -0800236 self.probe_func_name = "%s_probe%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700237 (self.function, Probe.next_probe_index)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800238 self.probe_hash_name = "%s_hash%d" % \
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700239 (self.function, Probe.next_probe_index)
240 Probe.next_probe_index += 1
241
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300242 def _enable_usdt_probe(self):
243 self.usdt_ctx = USDT(path=self.library, pid=self.pid)
244 self.usdt_ctx.enable_probe(
245 self.function, self.probe_func_name)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800246
Sasha Goldshteinc8f752f2016-10-17 02:18:43 -0700247 def _generate_streq_function(self, string):
248 fname = "streq_%d" % Probe.streq_index
249 Probe.streq_index += 1
250 self.streq_functions += """
251static inline bool %s(char const *ignored, char const *str) {
252 char needle[] = %s;
253 char haystack[sizeof(needle)];
254 bpf_probe_read(&haystack, sizeof(haystack), (void *)str);
255 for (int i = 0; i < sizeof(needle); ++i) {
256 if (needle[i] != haystack[i]) {
257 return false;
258 }
259 }
260 return true;
261}
262 """ % (fname, string)
263 return fname
264
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800265 def _substitute_exprs(self):
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800266 def repl(expr):
267 expr = self._substitute_aliases(expr)
Sasha Goldshteinc8f752f2016-10-17 02:18:43 -0700268 matches = re.finditer('STRCMP\\(("[^"]+\\")', expr)
269 for match in matches:
270 string = match.group(1)
271 fname = self._generate_streq_function(string)
272 expr = expr.replace("STRCMP", fname, 1)
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530273 return expr.replace("$retval", "PT_REGS_RC(ctx)")
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800274 for i in range(0, len(self.exprs)):
275 self.exprs[i] = repl(self.exprs[i])
276 self.filter = repl(self.filter)
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800277
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800278 def _is_string(self, expr_type):
279 return expr_type == "char*" or expr_type == "char *"
Sasha Goldshtein85384852016-02-12 01:29:39 -0800280
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800281 def _generate_hash_field(self, i):
282 if self._is_string(self.expr_types[i]):
283 return "struct __string_t v%d;\n" % i
284 else:
285 return "%s v%d;\n" % (self.expr_types[i], i)
286
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300287 def _generate_usdt_arg_assignment(self, i):
288 expr = self.exprs[i]
289 if self.probe_type == "u" and expr[0:3] == "arg":
290 return (" u64 %s = 0;\n" +
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300291 " bpf_usdt_readarg(%s, ctx, &%s);\n") \
292 % (expr, expr[3], expr)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300293 else:
294 return ""
295
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800296 def _generate_field_assignment(self, i):
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300297 text = self._generate_usdt_arg_assignment(i)
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800298 if self._is_string(self.expr_types[i]):
Brendan Gregg4f88a942016-07-22 17:11:51 -0700299 return (text + " bpf_probe_read(&__key.v%d.s," +
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700300 " sizeof(__key.v%d.s), (void *)%s);\n") % \
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800301 (i, i, self.exprs[i])
302 else:
Brendan Gregg4f88a942016-07-22 17:11:51 -0700303 return text + " __key.v%d = %s;\n" % \
304 (i, self.exprs[i])
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800305
306 def _generate_hash_decl(self):
307 if self.type == "hist":
308 return "BPF_HISTOGRAM(%s, %s);" % \
309 (self.probe_hash_name, self.expr_types[0])
310 else:
311 text = "struct %s_key_t {\n" % self.probe_hash_name
312 for i in range(0, len(self.expr_types)):
313 text += self._generate_hash_field(i)
314 text += "};\n"
315 text += "BPF_HASH(%s, struct %s_key_t, u64);\n" % \
316 (self.probe_hash_name, self.probe_hash_name)
317 return text
318
319 def _generate_key_assignment(self):
320 if self.type == "hist":
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300321 return self._generate_usdt_arg_assignment(0) + \
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300322 ("%s __key = %s;\n" %
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300323 (self.expr_types[0], self.exprs[0]))
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800324 else:
325 text = "struct %s_key_t __key = {};\n" % \
326 self.probe_hash_name
327 for i in range(0, len(self.exprs)):
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800328 text += self._generate_field_assignment(i)
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800329 return text
330
331 def _generate_hash_update(self):
332 if self.type == "hist":
333 return "%s.increment(bpf_log2l(__key));" % \
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800334 self.probe_hash_name
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800335 else:
336 return "%s.increment(__key);" % self.probe_hash_name
337
338 def _generate_pid_filter(self):
339 # Kernel probes need to explicitly filter pid, because the
340 # attach interface doesn't support pid filtering
341 if self.pid is not None and not self.is_user:
342 return "u32 pid = bpf_get_current_pid_tgid();\n" + \
343 "if (pid != %d) { return 0; }" % self.pid
344 else:
345 return ""
346
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800347 def generate_text(self):
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800348 program = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700349 probe_text = """
350DATA_DECL
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300351 """ + (
352 "TRACEPOINT_PROBE(%s, %s)" %
353 (self.tp_category, self.tp_event)
354 if self.probe_type == "t"
355 else "int PROBENAME(struct pt_regs *ctx SIGNATURE)") + """
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700356{
357 PID_FILTER
358 PREFIX
359 if (!(FILTER)) return 0;
360 KEY_EXPR
361 COLLECT
362 return 0;
363}
364"""
365 prefix = ""
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700366 signature = ""
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800367
368 # If any entry arguments are probed in a ret probe, we need
369 # to generate an entry probe to collect them
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800370 if self.entry_probe_required:
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800371 program += self._generate_entry_probe()
372 prefix += self._generate_retprobe_prefix()
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800373 # Replace $entry(paramname) with a reference to the
374 # value we collected when entering the function:
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800375 self._replace_entry_exprs()
376
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300377 if self.probe_type == "p" and len(self.signature) > 0:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700378 # Only entry uprobes/kprobes can have user-specified
379 # signatures. Other probes force it to ().
380 signature = ", " + self.signature
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800381
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300382 program += probe_text.replace("PROBENAME",
383 self.probe_func_name)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800384 program = program.replace("SIGNATURE", signature)
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800385 program = program.replace("PID_FILTER",
386 self._generate_pid_filter())
387
388 decl = self._generate_hash_decl()
389 key_expr = self._generate_key_assignment()
390 collect = self._generate_hash_update()
Sasha Goldshtein85384852016-02-12 01:29:39 -0800391 program = program.replace("DATA_DECL", decl)
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800392 program = program.replace("KEY_EXPR", key_expr)
Sasha Goldshteine3501152016-02-13 03:56:29 -0800393 program = program.replace("FILTER",
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800394 "1" if len(self.filter) == 0 else self.filter)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800395 program = program.replace("COLLECT", collect)
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800396 program = program.replace("PREFIX", prefix)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700397
Sasha Goldshteinc8f752f2016-10-17 02:18:43 -0700398 return self.streq_functions + program
Sasha Goldshtein85384852016-02-12 01:29:39 -0800399
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700400 def _attach_u(self):
401 libpath = BPF.find_library(self.library)
402 if libpath is None:
Sasha Goldshteinec679712016-10-04 18:33:36 +0300403 libpath = BPF.find_exe(self.library)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700404 if libpath is None or len(libpath) == 0:
Sasha Goldshtein5a1d2e32016-03-30 08:14:44 -0700405 self._bail("unable to find library %s" % self.library)
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700406
Brendan Gregg4f88a942016-07-22 17:11:51 -0700407 if self.probe_type == "r":
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700408 self.bpf.attach_uretprobe(name=libpath,
409 sym=self.function,
410 fn_name=self.probe_func_name,
411 pid=self.pid or -1)
412 else:
413 self.bpf.attach_uprobe(name=libpath,
414 sym=self.function,
415 fn_name=self.probe_func_name,
416 pid=self.pid or -1)
417
418 def _attach_k(self):
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300419 if self.probe_type == "t":
420 pass # Nothing to do for tracepoints
421 elif self.probe_type == "r":
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700422 self.bpf.attach_kretprobe(event=self.function,
423 fn_name=self.probe_func_name)
424 else:
425 self.bpf.attach_kprobe(event=self.function,
426 fn_name=self.probe_func_name)
427
Sasha Goldshtein85384852016-02-12 01:29:39 -0800428 def attach(self, bpf):
429 self.bpf = bpf
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300430 if self.probe_type == "u":
431 return
Sasha Goldshtein85384852016-02-12 01:29:39 -0800432 if self.is_user:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700433 self._attach_u()
Sasha Goldshtein85384852016-02-12 01:29:39 -0800434 else:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700435 self._attach_k()
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800436 if self.entry_probe_required:
437 self._attach_entry_probe()
Sasha Goldshtein85384852016-02-12 01:29:39 -0800438
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800439 def _v2s(self, v):
440 # Most fields can be converted with plain str(), but strings
441 # are wrapped in a __string_t which has an .s field
442 if "__string_t" in type(v).__name__:
443 return str(v.s)
444 return str(v)
445
446 def _display_expr(self, i):
447 # Replace ugly latency calculation with $latency
448 expr = self.exprs[i].replace(
449 "(bpf_ktime_get_ns() - *____latency_val)", "$latency")
450 # Replace alias values back with the alias name
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700451 for alias, subst in Probe.aliases.items():
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800452 expr = expr.replace(subst, alias)
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800453 # Replace retval expression with $retval
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530454 expr = expr.replace("PT_REGS_RC(ctx)", "$retval")
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800455 # Replace ugly (*__param_val) expressions with param name
456 return re.sub(r"\(\*__(\w+)_val\)", r"\1", expr)
457
458 def _display_key(self, key):
459 if self.is_default_expr:
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800460 if not self.probe_type == "r":
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800461 return "total calls"
462 else:
463 return "retval = %s" % str(key.v0)
464 else:
465 # The key object has v0, ..., vk fields containing
466 # the values of the expressions from self.exprs
467 def str_i(i):
468 key_i = self._v2s(getattr(key, "v%d" % i))
469 return "%s = %s" % \
470 (self._display_expr(i), key_i)
471 return ", ".join(map(str_i, range(0, len(self.exprs))))
472
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800473 def display(self, top):
Sasha Goldshtein85384852016-02-12 01:29:39 -0800474 data = self.bpf.get_table(self.probe_hash_name)
475 if self.type == "freq":
Sasha Goldshteine3501152016-02-13 03:56:29 -0800476 print(self.label or self.raw_spec)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800477 print("\t%-10s %s" % ("COUNT", "EVENT"))
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300478 sdata = sorted(data.items(), key=lambda p: p[1].value)
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800479 if top is not None:
Sasha Goldshteind2f47622016-10-04 18:40:15 +0300480 sdata = sdata[-top:]
481 for key, value in sdata:
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800482 # Print some nice values if the user didn't
483 # specify an expression to probe
Sasha Goldshtein85384852016-02-12 01:29:39 -0800484 if self.is_default_expr:
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800485 if not self.probe_type == "r":
Sasha Goldshtein85384852016-02-12 01:29:39 -0800486 key_str = "total calls"
487 else:
488 key_str = "retval = %s" % \
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800489 self._v2s(key.v0)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800490 else:
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800491 key_str = self._display_key(key)
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300492 print("\t%-10s %s" %
Sasha Goldshtein85384852016-02-12 01:29:39 -0800493 (str(value.value), key_str))
494 elif self.type == "hist":
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800495 label = self.label or (self._display_expr(0)
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300496 if not self.is_default_expr else "retval")
Sasha Goldshtein85384852016-02-12 01:29:39 -0800497 data.print_log2_hist(val_type=label)
Sasha Goldshteind2f47622016-10-04 18:40:15 +0300498 if not self.cumulative:
499 data.clear()
Sasha Goldshtein85384852016-02-12 01:29:39 -0800500
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700501 def __str__(self):
502 return self.label or self.raw_spec
503
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800504class Tool(object):
505 examples = """
Sasha Goldshtein85384852016-02-12 01:29:39 -0800506Probe specifier syntax:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700507 {p,r,t,u}:{[library],category}:function(signature)[:type[,type...]:expr[,expr...][:filter]][#label]
Sasha Goldshtein85384852016-02-12 01:29:39 -0800508Where:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300509 p,r,t,u -- probe at function entry, function exit, kernel
510 tracepoint, or USDT probe
Sasha Goldshteine3501152016-02-13 03:56:29 -0800511 in exit probes: can use $retval, $entry(param), $latency
Sasha Goldshtein85384852016-02-12 01:29:39 -0800512 library -- the library that contains the function
513 (leave empty for kernel functions)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800514 category -- the category of the kernel tracepoint (e.g. net, sched)
515 function -- the function name to trace (or tracepoint name)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800516 signature -- the function's parameters, as in the C header
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800517 type -- the type of the expression to collect (supports multiple)
518 expr -- the expression to collect (supports multiple)
Sasha Goldshteined21adf2016-02-12 03:04:53 -0800519 filter -- the filter that is applied to collected values
520 label -- the label for this probe in the resulting output
Sasha Goldshtein85384852016-02-12 01:29:39 -0800521
522EXAMPLES:
523
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800524argdist -H 'p::__kmalloc(u64 size):u64:size'
Sasha Goldshtein85384852016-02-12 01:29:39 -0800525 Print a histogram of allocation sizes passed to kmalloc
526
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800527argdist -p 1005 -C 'p:c:malloc(size_t size):size_t:size:size==16'
Sasha Goldshtein85384852016-02-12 01:29:39 -0800528 Print a frequency count of how many times process 1005 called malloc
529 with an allocation size of 16 bytes
530
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800531argdist -C 'r:c:gets():char*:(char*)$retval#snooped strings'
Sasha Goldshtein85384852016-02-12 01:29:39 -0800532 Snoop on all strings returned by gets()
533
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800534argdist -H 'r::__kmalloc(size_t size):u64:$latency/$entry(size)#ns per byte'
Sasha Goldshteine3501152016-02-13 03:56:29 -0800535 Print a histogram of nanoseconds per byte from kmalloc allocations
536
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300537argdist -C 'p::__kmalloc(size_t sz, gfp_t flags):size_t:sz:flags&GFP_ATOMIC'
Sasha Goldshtein7983d6b2016-02-13 23:14:18 -0800538 Print frequency count of kmalloc allocation sizes that have GFP_ATOMIC
539
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800540argdist -p 1005 -C 'p:c:write(int fd):int:fd' -T 5
Sasha Goldshtein85384852016-02-12 01:29:39 -0800541 Print frequency counts of how many times writes were issued to a
Sasha Goldshtein392d5c82016-02-12 11:14:20 -0800542 particular file descriptor number, in process 1005, but only show
543 the top 5 busiest fds
Sasha Goldshtein85384852016-02-12 01:29:39 -0800544
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800545argdist -p 1005 -H 'r:c:read()'
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800546 Print a histogram of results (sizes) returned by read() in process 1005
Sasha Goldshtein85384852016-02-12 01:29:39 -0800547
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800548argdist -C 'r::__vfs_read():u32:$PID:$latency > 100000'
Sasha Goldshteine3501152016-02-13 03:56:29 -0800549 Print frequency of reads by process where the latency was >0.1ms
550
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300551argdist -H 'r::__vfs_read(void *file, void *buf, size_t count):size_t
552 $entry(count):$latency > 1000000'
Sasha Goldshteine3501152016-02-13 03:56:29 -0800553 Print a histogram of read sizes that were longer than 1ms
554
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800555argdist -H \\
Sasha Goldshteined21adf2016-02-12 03:04:53 -0800556 'p:c:write(int fd, const void *buf, size_t count):size_t:count:fd==1'
Sasha Goldshtein85384852016-02-12 01:29:39 -0800557 Print a histogram of buffer sizes passed to write() across all
558 processes, where the file descriptor was 1 (STDOUT)
559
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800560argdist -C 'p:c:fork()#fork calls'
Sasha Goldshtein85384852016-02-12 01:29:39 -0800561 Count fork() calls in libc across all processes
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800562 Can also use funccount.py, which is easier and more flexible
Sasha Goldshtein85384852016-02-12 01:29:39 -0800563
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300564argdist -H 't:block:block_rq_complete():u32:args->nr_sector'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800565 Print histogram of number of sectors in completing block I/O requests
566
Sasha Goldshtein376ae5c2016-10-04 19:49:57 +0300567argdist -C 't:irq:irq_handler_entry():int:args->irq'
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800568 Aggregate interrupts by interrupt request (IRQ)
569
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700570argdist -C 'u:pthread:pthread_start():u64:arg2' -p 1337
571 Print frequency of function addresses used as a pthread start function,
572 relying on the USDT pthread_start probe in process 1337
573
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300574argdist -H 'p:c:sleep(u32 seconds):u32:seconds' \\
575 -H 'p:c:nanosleep(struct timespec *req):long:req->tv_nsec'
Sasha Goldshtein85384852016-02-12 01:29:39 -0800576 Print histograms of sleep() and nanosleep() parameter values
577
Sasha Goldshtein7df65da2016-02-14 05:12:27 -0800578argdist -p 2780 -z 120 \\
Sasha Goldshteined21adf2016-02-12 03:04:53 -0800579 -C 'p:c:write(int fd, char* buf, size_t len):char*:buf:fd==1'
Sasha Goldshtein85384852016-02-12 01:29:39 -0800580 Spy on writes to STDOUT performed by process 2780, up to a string size
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800581 of 120 characters
Sasha Goldshtein85384852016-02-12 01:29:39 -0800582"""
583
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800584 def __init__(self):
585 parser = argparse.ArgumentParser(description="Trace a " +
586 "function and display a summary of its parameter values.",
587 formatter_class=argparse.RawDescriptionHelpFormatter,
588 epilog=Tool.examples)
589 parser.add_argument("-p", "--pid", type=int,
590 help="id of the process to trace (optional)")
591 parser.add_argument("-z", "--string-size", default=80,
592 type=int,
593 help="maximum string size to read from char* arguments")
594 parser.add_argument("-i", "--interval", default=1, type=int,
595 help="output interval, in seconds")
596 parser.add_argument("-n", "--number", type=int, dest="count",
597 help="number of outputs")
598 parser.add_argument("-v", "--verbose", action="store_true",
599 help="print resulting BPF program code before executing")
Sasha Goldshteind2f47622016-10-04 18:40:15 +0300600 parser.add_argument("-c", "--cumulative", action="store_true",
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300601 help="do not clear histograms and freq counts at " +
602 "each interval")
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800603 parser.add_argument("-T", "--top", type=int,
604 help="number of top results to show (not applicable to " +
605 "histograms)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300606 parser.add_argument("-H", "--histogram", action="append",
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800607 dest="histspecifier", metavar="specifier",
608 help="probe specifier to capture histogram of " +
609 "(see examples below)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300610 parser.add_argument("-C", "--count", action="append",
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800611 dest="countspecifier", metavar="specifier",
612 help="probe specifier to capture count of " +
613 "(see examples below)")
Sasha Goldshtein4725a722016-10-18 20:54:47 +0300614 parser.add_argument("-I", "--include", action="append",
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800615 metavar="header",
616 help="additional header files to include in the BPF program")
617 self.args = parser.parse_args()
Brendan Gregg4f88a942016-07-22 17:11:51 -0700618 self.usdt_ctx = None
Sasha Goldshtein85384852016-02-12 01:29:39 -0800619
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700620 def _create_probes(self):
621 self.probes = []
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800622 for specifier in (self.args.countspecifier or []):
Brendan Gregg4f88a942016-07-22 17:11:51 -0700623 self.probes.append(Probe(self, "freq", specifier))
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800624 for histspecifier in (self.args.histspecifier or []):
Brendan Gregg4f88a942016-07-22 17:11:51 -0700625 self.probes.append(Probe(self, "hist", histspecifier))
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700626 if len(self.probes) == 0:
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800627 print("at least one specifier is required")
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800628 exit()
Sasha Goldshtein85384852016-02-12 01:29:39 -0800629
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800630 def _generate_program(self):
631 bpf_source = """
Sasha Goldshteincc27edf2016-02-14 03:49:01 -0800632struct __string_t { char s[%d]; };
633
634#include <uapi/linux/ptrace.h>
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800635 """ % self.args.string_size
636 for include in (self.args.include or []):
637 bpf_source += "#include <%s>\n" % include
Sasha Goldshteinb950d6f2016-03-21 04:06:15 -0700638 bpf_source += BPF.generate_auto_includes(
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700639 map(lambda p: p.raw_spec, self.probes))
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700640 for probe in self.probes:
641 bpf_source += probe.generate_text()
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800642 if self.args.verbose:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300643 for text in [probe.usdt_ctx.get_text()
644 for probe in self.probes
645 if probe.usdt_ctx]:
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300646 print(text)
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800647 print(bpf_source)
Sasha Goldshtein69e361a2016-09-27 19:40:00 +0300648 usdt_contexts = [probe.usdt_ctx
649 for probe in self.probes if probe.usdt_ctx]
650 self.bpf = BPF(text=bpf_source, usdt_contexts=usdt_contexts)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800651
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800652 def _attach(self):
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700653 for probe in self.probes:
654 probe.attach(self.bpf)
Sasha Goldshteinfd60d552016-03-01 12:15:34 -0800655 if self.args.verbose:
Mark Draytoncb679d72016-07-15 23:55:22 +0100656 print("open uprobes: %s" % self.bpf.open_uprobes)
657 print("open kprobes: %s" % self.bpf.open_kprobes)
Sasha Goldshtein85384852016-02-12 01:29:39 -0800658
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800659 def _main_loop(self):
660 count_so_far = 0
661 while True:
662 try:
663 sleep(self.args.interval)
664 except KeyboardInterrupt:
665 exit()
666 print("[%s]" % strftime("%H:%M:%S"))
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700667 for probe in self.probes:
668 probe.display(self.args.top)
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800669 count_so_far += 1
670 if self.args.count is not None and \
671 count_so_far >= self.args.count:
672 exit()
Sasha Goldshtein85384852016-02-12 01:29:39 -0800673
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800674 def run(self):
675 try:
Sasha Goldshtein3e39a082016-03-24 08:39:47 -0700676 self._create_probes()
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800677 self._generate_program()
678 self._attach()
679 self._main_loop()
680 except:
681 if self.args.verbose:
682 traceback.print_exc()
Brenden Blancobc94d4c2016-05-05 12:05:07 -0700683 elif sys.exc_info()[0] is not SystemExit:
684 print(sys.exc_info()[1])
Sasha Goldshtein85384852016-02-12 01:29:39 -0800685
Sasha Goldshteinc9551302016-02-21 02:21:46 -0800686if __name__ == "__main__":
687 Tool().run()