xref: /linux/tools/perf/builtin-probe.c (revision cf2f33a4e54096f90652cca3511fd6a456ea5abe)
1 /*
2  * builtin-probe.c
3  *
4  * Builtin probe command: Set up probe events by C expression
5  *
6  * Written by Masami Hiramatsu <mhiramat@redhat.com>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21  *
22  */
23 #include <sys/utsname.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <stdio.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <string.h>
32 
33 #include "perf.h"
34 #include "builtin.h"
35 #include "util/util.h"
36 #include "util/strlist.h"
37 #include "util/strfilter.h"
38 #include "util/symbol.h"
39 #include "util/debug.h"
40 #include <api/fs/debugfs.h>
41 #include "util/parse-options.h"
42 #include "util/probe-finder.h"
43 #include "util/probe-event.h"
44 #include "util/probe-file.h"
45 
46 #define DEFAULT_VAR_FILTER "!__k???tab_* & !__crc_*"
47 #define DEFAULT_FUNC_FILTER "!_*"
48 #define DEFAULT_LIST_FILTER "*:*"
49 
50 /* Session management structure */
51 static struct {
52 	int command;	/* Command short_name */
53 	bool list_events;
54 	bool uprobes;
55 	bool quiet;
56 	bool target_used;
57 	int nevents;
58 	struct perf_probe_event events[MAX_PROBES];
59 	struct line_range line_range;
60 	char *target;
61 	struct strfilter *filter;
62 } params;
63 
64 /* Parse an event definition. Note that any error must die. */
65 static int parse_probe_event(const char *str)
66 {
67 	struct perf_probe_event *pev = &params.events[params.nevents];
68 	int ret;
69 
70 	pr_debug("probe-definition(%d): %s\n", params.nevents, str);
71 	if (++params.nevents == MAX_PROBES) {
72 		pr_err("Too many probes (> %d) were specified.", MAX_PROBES);
73 		return -1;
74 	}
75 
76 	pev->uprobes = params.uprobes;
77 	if (params.target) {
78 		pev->target = strdup(params.target);
79 		if (!pev->target)
80 			return -ENOMEM;
81 		params.target_used = true;
82 	}
83 
84 	/* Parse a perf-probe command into event */
85 	ret = parse_perf_probe_command(str, pev);
86 	pr_debug("%d arguments\n", pev->nargs);
87 
88 	return ret;
89 }
90 
91 static int params_add_filter(const char *str)
92 {
93 	const char *err = NULL;
94 	int ret = 0;
95 
96 	pr_debug2("Add filter: %s\n", str);
97 	if (!params.filter) {
98 		params.filter = strfilter__new(str, &err);
99 		if (!params.filter)
100 			ret = err ? -EINVAL : -ENOMEM;
101 	} else
102 		ret = strfilter__or(params.filter, str, &err);
103 
104 	if (ret == -EINVAL) {
105 		pr_err("Filter parse error at %td.\n", err - str + 1);
106 		pr_err("Source: \"%s\"\n", str);
107 		pr_err("         %*c\n", (int)(err - str + 1), '^');
108 	}
109 
110 	return ret;
111 }
112 
113 static int set_target(const char *ptr)
114 {
115 	int found = 0;
116 	const char *buf;
117 
118 	/*
119 	 * The first argument after options can be an absolute path
120 	 * to an executable / library or kernel module.
121 	 *
122 	 * TODO: Support relative path, and $PATH, $LD_LIBRARY_PATH,
123 	 * short module name.
124 	 */
125 	if (!params.target && ptr && *ptr == '/') {
126 		params.target = strdup(ptr);
127 		if (!params.target)
128 			return -ENOMEM;
129 		params.target_used = false;
130 
131 		found = 1;
132 		buf = ptr + (strlen(ptr) - 3);
133 
134 		if (strcmp(buf, ".ko"))
135 			params.uprobes = true;
136 
137 	}
138 
139 	return found;
140 }
141 
142 static int parse_probe_event_argv(int argc, const char **argv)
143 {
144 	int i, len, ret, found_target;
145 	char *buf;
146 
147 	found_target = set_target(argv[0]);
148 	if (found_target < 0)
149 		return found_target;
150 
151 	if (found_target && argc == 1)
152 		return 0;
153 
154 	/* Bind up rest arguments */
155 	len = 0;
156 	for (i = 0; i < argc; i++) {
157 		if (i == 0 && found_target)
158 			continue;
159 
160 		len += strlen(argv[i]) + 1;
161 	}
162 	buf = zalloc(len + 1);
163 	if (buf == NULL)
164 		return -ENOMEM;
165 	len = 0;
166 	for (i = 0; i < argc; i++) {
167 		if (i == 0 && found_target)
168 			continue;
169 
170 		len += sprintf(&buf[len], "%s ", argv[i]);
171 	}
172 	ret = parse_probe_event(buf);
173 	free(buf);
174 	return ret;
175 }
176 
177 static int opt_set_target(const struct option *opt, const char *str,
178 			int unset __maybe_unused)
179 {
180 	int ret = -ENOENT;
181 	char *tmp;
182 
183 	if  (str) {
184 		if (!strcmp(opt->long_name, "exec"))
185 			params.uprobes = true;
186 #ifdef HAVE_DWARF_SUPPORT
187 		else if (!strcmp(opt->long_name, "module"))
188 			params.uprobes = false;
189 #endif
190 		else
191 			return ret;
192 
193 		/* Expand given path to absolute path, except for modulename */
194 		if (params.uprobes || strchr(str, '/')) {
195 			tmp = realpath(str, NULL);
196 			if (!tmp) {
197 				pr_warning("Failed to get the absolute path of %s: %m\n", str);
198 				return ret;
199 			}
200 		} else {
201 			tmp = strdup(str);
202 			if (!tmp)
203 				return -ENOMEM;
204 		}
205 		free(params.target);
206 		params.target = tmp;
207 		params.target_used = false;
208 		ret = 0;
209 	}
210 
211 	return ret;
212 }
213 
214 /* Command option callbacks */
215 
216 #ifdef HAVE_DWARF_SUPPORT
217 static int opt_show_lines(const struct option *opt,
218 			  const char *str, int unset __maybe_unused)
219 {
220 	int ret = 0;
221 
222 	if (!str)
223 		return 0;
224 
225 	if (params.command == 'L') {
226 		pr_warning("Warning: more than one --line options are"
227 			   " detected. Only the first one is valid.\n");
228 		return 0;
229 	}
230 
231 	params.command = opt->short_name;
232 	ret = parse_line_range_desc(str, &params.line_range);
233 
234 	return ret;
235 }
236 
237 static int opt_show_vars(const struct option *opt,
238 			 const char *str, int unset __maybe_unused)
239 {
240 	struct perf_probe_event *pev = &params.events[params.nevents];
241 	int ret;
242 
243 	if (!str)
244 		return 0;
245 
246 	ret = parse_probe_event(str);
247 	if (!ret && pev->nargs != 0) {
248 		pr_err("  Error: '--vars' doesn't accept arguments.\n");
249 		return -EINVAL;
250 	}
251 	params.command = opt->short_name;
252 
253 	return ret;
254 }
255 #endif
256 static int opt_add_probe_event(const struct option *opt,
257 			      const char *str, int unset __maybe_unused)
258 {
259 	if (str) {
260 		params.command = opt->short_name;
261 		return parse_probe_event(str);
262 	}
263 
264 	return 0;
265 }
266 
267 static int opt_set_filter_with_command(const struct option *opt,
268 				       const char *str, int unset)
269 {
270 	if (!unset)
271 		params.command = opt->short_name;
272 
273 	if (str)
274 		return params_add_filter(str);
275 
276 	return 0;
277 }
278 
279 static int opt_set_filter(const struct option *opt __maybe_unused,
280 			  const char *str, int unset __maybe_unused)
281 {
282 	if (str)
283 		return params_add_filter(str);
284 
285 	return 0;
286 }
287 
288 static int init_params(void)
289 {
290 	return line_range__init(&params.line_range);
291 }
292 
293 static void cleanup_params(void)
294 {
295 	int i;
296 
297 	for (i = 0; i < params.nevents; i++)
298 		clear_perf_probe_event(params.events + i);
299 	line_range__clear(&params.line_range);
300 	free(params.target);
301 	strfilter__delete(params.filter);
302 	memset(&params, 0, sizeof(params));
303 }
304 
305 static void pr_err_with_code(const char *msg, int err)
306 {
307 	char sbuf[STRERR_BUFSIZE];
308 
309 	pr_err("%s", msg);
310 	pr_debug(" Reason: %s (Code: %d)",
311 		 strerror_r(-err, sbuf, sizeof(sbuf)), err);
312 	pr_err("\n");
313 }
314 
315 static int perf_add_probe_events(struct perf_probe_event *pevs, int npevs)
316 {
317 	int ret;
318 	int i, k;
319 	const char *event = NULL, *group = NULL;
320 
321 	ret = convert_perf_probe_events(pevs, npevs);
322 	if (ret < 0)
323 		goto out_cleanup;
324 
325 	ret = apply_perf_probe_events(pevs, npevs);
326 	if (ret < 0)
327 		goto out_cleanup;
328 
329 	for (i = k = 0; i < npevs; i++)
330 		k += pevs[i].ntevs;
331 
332 	pr_info("Added new event%s\n", (k > 1) ? "s:" : ":");
333 	for (i = 0; i < npevs; i++) {
334 		struct perf_probe_event *pev = &pevs[i];
335 
336 		for (k = 0; k < pev->ntevs; k++) {
337 			struct probe_trace_event *tev = &pev->tevs[k];
338 
339 			/* We use tev's name for showing new events */
340 			show_perf_probe_event(tev->group, tev->event, pev,
341 					      tev->point.module, false);
342 
343 			/* Save the last valid name */
344 			event = tev->event;
345 			group = tev->group;
346 		}
347 	}
348 
349 	/* Note that it is possible to skip all events because of blacklist */
350 	if (event) {
351 		/* Show how to use the event. */
352 		pr_info("\nYou can now use it in all perf tools, such as:\n\n");
353 		pr_info("\tperf record -e %s:%s -aR sleep 1\n\n", group, event);
354 	}
355 
356 out_cleanup:
357 	cleanup_perf_probe_events(pevs, npevs);
358 	return ret;
359 }
360 
361 static int perf_del_probe_events(struct strfilter *filter)
362 {
363 	int ret, ret2, ufd = -1, kfd = -1;
364 	char *str = strfilter__string(filter);
365 	struct strlist *klist = NULL, *ulist = NULL;
366 	struct str_node *ent;
367 
368 	if (!str)
369 		return -EINVAL;
370 
371 	pr_debug("Delete filter: \'%s\'\n", str);
372 
373 	/* Get current event names */
374 	ret = probe_file__open_both(&kfd, &ufd, PF_FL_RW);
375 	if (ret < 0)
376 		goto out;
377 
378 	klist = strlist__new(NULL, NULL);
379 	if (!klist)
380 		return -ENOMEM;
381 
382 	ret = probe_file__get_events(kfd, filter, klist);
383 	if (ret == 0) {
384 		strlist__for_each(ent, klist)
385 			pr_info("Removed event: %s\n", ent->s);
386 
387 		ret = probe_file__del_strlist(kfd, klist);
388 		if (ret < 0)
389 			goto error;
390 	}
391 
392 	ret2 = probe_file__get_events(ufd, filter, ulist);
393 	if (ret2 == 0) {
394 		strlist__for_each(ent, ulist)
395 			pr_info("Removed event: %s\n", ent->s);
396 
397 		ret2 = probe_file__del_strlist(ufd, ulist);
398 		if (ret2 < 0)
399 			goto error;
400 	}
401 
402 	if (ret == -ENOENT && ret2 == -ENOENT)
403 		pr_debug("\"%s\" does not hit any event.\n", str);
404 		/* Note that this is silently ignored */
405 	ret = 0;
406 
407 error:
408 	if (kfd >= 0)
409 		close(kfd);
410 	if (ufd >= 0)
411 		close(ufd);
412 out:
413 	strlist__delete(klist);
414 	strlist__delete(ulist);
415 	free(str);
416 
417 	return ret;
418 }
419 
420 static int
421 __cmd_probe(int argc, const char **argv, const char *prefix __maybe_unused)
422 {
423 	const char * const probe_usage[] = {
424 		"perf probe [<options>] 'PROBEDEF' ['PROBEDEF' ...]",
425 		"perf probe [<options>] --add 'PROBEDEF' [--add 'PROBEDEF' ...]",
426 		"perf probe [<options>] --del '[GROUP:]EVENT' ...",
427 		"perf probe --list [GROUP:]EVENT ...",
428 #ifdef HAVE_DWARF_SUPPORT
429 		"perf probe [<options>] --line 'LINEDESC'",
430 		"perf probe [<options>] --vars 'PROBEPOINT'",
431 #endif
432 		"perf probe [<options>] --funcs",
433 		NULL
434 	};
435 	struct option options[] = {
436 	OPT_INCR('v', "verbose", &verbose,
437 		    "be more verbose (show parsed arguments, etc)"),
438 	OPT_BOOLEAN('q', "quiet", &params.quiet,
439 		    "be quiet (do not show any mesages)"),
440 	OPT_CALLBACK_DEFAULT('l', "list", NULL, "[GROUP:]EVENT",
441 			     "list up probe events",
442 			     opt_set_filter_with_command, DEFAULT_LIST_FILTER),
443 	OPT_CALLBACK('d', "del", NULL, "[GROUP:]EVENT", "delete a probe event.",
444 		     opt_set_filter_with_command),
445 	OPT_CALLBACK('a', "add", NULL,
446 #ifdef HAVE_DWARF_SUPPORT
447 		"[EVENT=]FUNC[@SRC][+OFF|%return|:RL|;PT]|SRC:AL|SRC;PT"
448 		" [[NAME=]ARG ...]",
449 #else
450 		"[EVENT=]FUNC[+OFF|%return] [[NAME=]ARG ...]",
451 #endif
452 		"probe point definition, where\n"
453 		"\t\tGROUP:\tGroup name (optional)\n"
454 		"\t\tEVENT:\tEvent name\n"
455 		"\t\tFUNC:\tFunction name\n"
456 		"\t\tOFF:\tOffset from function entry (in byte)\n"
457 		"\t\t%return:\tPut the probe at function return\n"
458 #ifdef HAVE_DWARF_SUPPORT
459 		"\t\tSRC:\tSource code path\n"
460 		"\t\tRL:\tRelative line number from function entry.\n"
461 		"\t\tAL:\tAbsolute line number in file.\n"
462 		"\t\tPT:\tLazy expression of line code.\n"
463 		"\t\tARG:\tProbe argument (local variable name or\n"
464 		"\t\t\tkprobe-tracer argument format.)\n",
465 #else
466 		"\t\tARG:\tProbe argument (kprobe-tracer argument format.)\n",
467 #endif
468 		opt_add_probe_event),
469 	OPT_BOOLEAN('f', "force", &probe_conf.force_add, "forcibly add events"
470 		    " with existing name"),
471 #ifdef HAVE_DWARF_SUPPORT
472 	OPT_CALLBACK('L', "line", NULL,
473 		     "FUNC[:RLN[+NUM|-RLN2]]|SRC:ALN[+NUM|-ALN2]",
474 		     "Show source code lines.", opt_show_lines),
475 	OPT_CALLBACK('V', "vars", NULL,
476 		     "FUNC[@SRC][+OFF|%return|:RL|;PT]|SRC:AL|SRC;PT",
477 		     "Show accessible variables on PROBEDEF", opt_show_vars),
478 	OPT_BOOLEAN('\0', "externs", &probe_conf.show_ext_vars,
479 		    "Show external variables too (with --vars only)"),
480 	OPT_BOOLEAN('\0', "range", &probe_conf.show_location_range,
481 		"Show variables location range in scope (with --vars only)"),
482 	OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
483 		   "file", "vmlinux pathname"),
484 	OPT_STRING('s', "source", &symbol_conf.source_prefix,
485 		   "directory", "path to kernel source"),
486 	OPT_CALLBACK('m', "module", NULL, "modname|path",
487 		"target module name (for online) or path (for offline)",
488 		opt_set_target),
489 	OPT_BOOLEAN('\0', "no-inlines", &probe_conf.no_inlines,
490 		"Don't search inlined functions"),
491 #endif
492 	OPT__DRY_RUN(&probe_event_dry_run),
493 	OPT_INTEGER('\0', "max-probes", &probe_conf.max_probes,
494 		 "Set how many probe points can be found for a probe."),
495 	OPT_CALLBACK_DEFAULT('F', "funcs", NULL, "[FILTER]",
496 			     "Show potential probe-able functions.",
497 			     opt_set_filter_with_command, DEFAULT_FUNC_FILTER),
498 	OPT_CALLBACK('\0', "filter", NULL,
499 		     "[!]FILTER", "Set a filter (with --vars/funcs only)\n"
500 		     "\t\t\t(default: \"" DEFAULT_VAR_FILTER "\" for --vars,\n"
501 		     "\t\t\t \"" DEFAULT_FUNC_FILTER "\" for --funcs)",
502 		     opt_set_filter),
503 	OPT_CALLBACK('x', "exec", NULL, "executable|path",
504 			"target executable name or path", opt_set_target),
505 	OPT_BOOLEAN(0, "demangle", &symbol_conf.demangle,
506 		    "Enable symbol demangling"),
507 	OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
508 		    "Enable kernel symbol demangling"),
509 	OPT_END()
510 	};
511 	int ret;
512 
513 	set_option_flag(options, 'a', "add", PARSE_OPT_EXCLUSIVE);
514 	set_option_flag(options, 'd', "del", PARSE_OPT_EXCLUSIVE);
515 	set_option_flag(options, 'l', "list", PARSE_OPT_EXCLUSIVE);
516 #ifdef HAVE_DWARF_SUPPORT
517 	set_option_flag(options, 'L', "line", PARSE_OPT_EXCLUSIVE);
518 	set_option_flag(options, 'V', "vars", PARSE_OPT_EXCLUSIVE);
519 #endif
520 	set_option_flag(options, 'F', "funcs", PARSE_OPT_EXCLUSIVE);
521 
522 	argc = parse_options(argc, argv, options, probe_usage,
523 			     PARSE_OPT_STOP_AT_NON_OPTION);
524 	if (argc > 0) {
525 		if (strcmp(argv[0], "-") == 0) {
526 			pr_warning("  Error: '-' is not supported.\n");
527 			usage_with_options(probe_usage, options);
528 		}
529 		if (params.command && params.command != 'a') {
530 			pr_warning("  Error: another command except --add is set.\n");
531 			usage_with_options(probe_usage, options);
532 		}
533 		ret = parse_probe_event_argv(argc, argv);
534 		if (ret < 0) {
535 			pr_err_with_code("  Error: Command Parse Error.", ret);
536 			return ret;
537 		}
538 		params.command = 'a';
539 	}
540 
541 	if (params.quiet) {
542 		if (verbose != 0) {
543 			pr_err("  Error: -v and -q are exclusive.\n");
544 			return -EINVAL;
545 		}
546 		verbose = -1;
547 	}
548 
549 	if (probe_conf.max_probes == 0)
550 		probe_conf.max_probes = MAX_PROBES;
551 
552 	/*
553 	 * Only consider the user's kernel image path if given.
554 	 */
555 	symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
556 
557 	switch (params.command) {
558 	case 'l':
559 		if (params.uprobes) {
560 			pr_warning("  Error: Don't use --list with --exec.\n");
561 			usage_with_options(probe_usage, options);
562 		}
563 		ret = show_perf_probe_events(params.filter);
564 		if (ret < 0)
565 			pr_err_with_code("  Error: Failed to show event list.", ret);
566 		return ret;
567 	case 'F':
568 		ret = show_available_funcs(params.target, params.filter,
569 					params.uprobes);
570 		if (ret < 0)
571 			pr_err_with_code("  Error: Failed to show functions.", ret);
572 		return ret;
573 #ifdef HAVE_DWARF_SUPPORT
574 	case 'L':
575 		ret = show_line_range(&params.line_range, params.target,
576 				      params.uprobes);
577 		if (ret < 0)
578 			pr_err_with_code("  Error: Failed to show lines.", ret);
579 		return ret;
580 	case 'V':
581 		if (!params.filter)
582 			params.filter = strfilter__new(DEFAULT_VAR_FILTER,
583 						       NULL);
584 
585 		ret = show_available_vars(params.events, params.nevents,
586 					  params.filter);
587 		if (ret < 0)
588 			pr_err_with_code("  Error: Failed to show vars.", ret);
589 		return ret;
590 #endif
591 	case 'd':
592 		ret = perf_del_probe_events(params.filter);
593 		if (ret < 0) {
594 			pr_err_with_code("  Error: Failed to delete events.", ret);
595 			return ret;
596 		}
597 		break;
598 	case 'a':
599 		/* Ensure the last given target is used */
600 		if (params.target && !params.target_used) {
601 			pr_warning("  Error: -x/-m must follow the probe definitions.\n");
602 			usage_with_options(probe_usage, options);
603 		}
604 
605 		ret = perf_add_probe_events(params.events, params.nevents);
606 		if (ret < 0) {
607 			pr_err_with_code("  Error: Failed to add events.", ret);
608 			return ret;
609 		}
610 		break;
611 	default:
612 		usage_with_options(probe_usage, options);
613 	}
614 	return 0;
615 }
616 
617 int cmd_probe(int argc, const char **argv, const char *prefix)
618 {
619 	int ret;
620 
621 	ret = init_params();
622 	if (!ret) {
623 		ret = __cmd_probe(argc, argv, prefix);
624 		cleanup_params();
625 	}
626 
627 	return ret < 0 ? ret : 0;
628 }
629