probe-event.c 41.9 KB
Newer Older
1
/*
2
 * probe-event.c : perf-probe definition to probe_events format converter
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 *
 * Written by Masami Hiramatsu <mhiramat@redhat.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 */

#define _GNU_SOURCE
#include <sys/utsname.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
32 33
#include <stdarg.h>
#include <limits.h>
34 35

#undef _GNU_SOURCE
36
#include "util.h"
37
#include "event.h"
38
#include "string.h"
39
#include "strlist.h"
40
#include "debug.h"
41
#include "cache.h"
42
#include "color.h"
43 44
#include "symbol.h"
#include "thread.h"
45
#include "debugfs.h"
46
#include "trace-event.h"	/* For __unused */
47
#include "probe-event.h"
48
#include "probe-finder.h"
49 50 51 52 53

#define MAX_CMDLEN 256
#define MAX_PROBE_ARGS 128
#define PERFPROBE_GROUP "probe"

54 55
bool probe_event_dry_run;	/* Dry run flag */

56
#define semantic_error(msg ...) pr_err("Semantic error :" msg)
57

58
/* If there is no space to write, returns -E2BIG. */
59 60 61
static int e_snprintf(char *str, size_t size, const char *format, ...)
	__attribute__((format(printf, 3, 4)));

62 63 64 65 66 67 68 69 70 71 72 73
static int e_snprintf(char *str, size_t size, const char *format, ...)
{
	int ret;
	va_list ap;
	va_start(ap, format);
	ret = vsnprintf(str, size, format, ap);
	va_end(ap);
	if (ret >= (int)size)
		ret = -E2BIG;
	return ret;
}

74
static char *synthesize_perf_probe_point(struct perf_probe_point *pp);
75
static struct machine machine;
76

77
/* Initialize symbol maps and path of vmlinux/modules */
78
static int init_vmlinux(void)
79
{
80 81
	int ret;

82 83 84 85 86
	symbol_conf.sort_by_name = true;
	if (symbol_conf.vmlinux_name == NULL)
		symbol_conf.try_vmlinux_path = true;
	else
		pr_debug("Use vmlinux: %s\n", symbol_conf.vmlinux_name);
87 88 89 90 91
	ret = symbol__init();
	if (ret < 0) {
		pr_debug("Failed to init symbol map.\n");
		goto out;
	}
92

93
	ret = machine__init(&machine, "", HOST_KERNEL_ID);
94 95 96
	if (ret < 0)
		goto out;

97
	if (machine__create_kernel_maps(&machine) < 0) {
M
Masami Hiramatsu 已提交
98
		pr_debug("machine__create_kernel_maps() failed.\n");
99 100
		goto out;
	}
101 102 103 104
out:
	if (ret < 0)
		pr_warning("Failed to init vmlinux path.\n");
	return ret;
105 106
}

107 108 109 110 111 112 113 114 115 116
static struct symbol *__find_kernel_function_by_name(const char *name,
						     struct map **mapp)
{
	return machine__find_kernel_function_by_name(&machine, name, mapp,
						     NULL);
}

const char *kernel_get_module_path(const char *module)
{
	struct dso *dso;
117 118
	struct map *map;
	const char *vmlinux_name;
119 120 121 122 123 124 125 126 127

	if (module) {
		list_for_each_entry(dso, &machine.kernel_dsos, node) {
			if (strncmp(dso->short_name + 1, module,
				    dso->short_name_len - 2) == 0)
				goto found;
		}
		pr_debug("Failed to find module %s.\n", module);
		return NULL;
128 129 130 131 132 133 134 135 136
	}

	map = machine.vmlinux_maps[MAP__FUNCTION];
	dso = map->dso;

	vmlinux_name = symbol_conf.vmlinux_name;
	if (vmlinux_name) {
		if (dso__load_vmlinux(dso, map, vmlinux_name, NULL) <= 0)
			return NULL;
137
	} else {
138
		if (dso__load_vmlinux_path(dso, map, NULL) <= 0) {
139 140 141 142 143 144 145 146
			pr_debug("Failed to load kernel map.\n");
			return NULL;
		}
	}
found:
	return dso->long_name;
}

147
#ifdef DWARF_SUPPORT
148
static int open_vmlinux(const char *module)
149
{
150 151
	const char *path = kernel_get_module_path(module);
	if (!path) {
M
Masami Hiramatsu 已提交
152 153
		pr_err("Failed to find path of %s module.\n",
		       module ?: "kernel");
154
		return -ENOENT;
155
	}
156 157
	pr_debug("Try to open %s\n", path);
	return open(path, O_RDONLY);
158
}
159

160 161 162 163 164
/*
 * Convert trace point to probe point with debuginfo
 * Currently only handles kprobes.
 */
static int kprobe_convert_to_perf_probe(struct probe_trace_point *tp,
165
					struct perf_probe_point *pp)
166 167
{
	struct symbol *sym;
168 169 170
	struct map *map;
	u64 addr;
	int ret = -ENOENT;
171

172
	sym = __find_kernel_function_by_name(tp->symbol, &map);
173
	if (sym) {
174
		addr = map->unmap_ip(map, sym->start + tp->offset);
175
		pr_debug("try to find %s+%ld@%" PRIx64 "\n", tp->symbol,
176 177
			 tp->offset, addr);
		ret = find_perf_probe_point((unsigned long)addr, pp);
178 179
	}
	if (ret <= 0) {
180 181
		pr_debug("Failed to find corresponding probes from "
			 "debuginfo. Use kprobe event information.\n");
182 183 184
		pp->function = strdup(tp->symbol);
		if (pp->function == NULL)
			return -ENOMEM;
185 186 187
		pp->offset = tp->offset;
	}
	pp->retprobe = tp->retprobe;
188 189

	return 0;
190 191 192
}

/* Try to find perf_probe_event with debuginfo */
193 194
static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
					   struct probe_trace_event **tevs,
195
					   int max_tevs, const char *module)
196 197 198 199
{
	bool need_dwarf = perf_probe_event_need_dwarf(pev);
	int fd, ntevs;

200
	fd = open_vmlinux(module);
201
	if (fd < 0) {
202 203 204 205
		if (need_dwarf) {
			pr_warning("Failed to open debuginfo file.\n");
			return fd;
		}
206 207 208 209 210
		pr_debug("Could not open vmlinux. Try to use symbols.\n");
		return 0;
	}

	/* Searching trace events corresponding to probe event */
211
	ntevs = find_probe_trace_events(fd, pev, tevs, max_tevs);
212 213
	close(fd);

214
	if (ntevs > 0) {	/* Succeeded to find trace events */
215
		pr_debug("find %d probe_trace_events.\n", ntevs);
216
		return ntevs;
217
	}
218

219 220 221 222 223 224
	if (ntevs == 0)	{	/* No error but failed to find probe point. */
		pr_warning("Probe point '%s' not found.\n",
			   synthesize_perf_probe_point(&pev->point));
		return -ENOENT;
	}
	/* Error path : ntevs < 0 */
225 226 227 228 229
	pr_debug("An error occurred in debuginfo analysis (%d).\n", ntevs);
	if (ntevs == -EBADF) {
		pr_warning("Warning: No dwarf info found in the vmlinux - "
			"please rebuild kernel with CONFIG_DEBUG_INFO=y.\n");
		if (!need_dwarf) {
M
Masami Hiramatsu 已提交
230
			pr_debug("Trying to use symbols.\n");
231 232
			return 0;
		}
233
	}
234
	return ntevs;
235 236
}

237 238 239 240 241 242
/*
 * Find a src file from a DWARF tag path. Prepend optional source path prefix
 * and chop off leading directories that do not exist. Result is passed back as
 * a newly allocated path on success.
 * Return 0 if file was found and readable, -errno otherwise.
 */
243 244
static int get_real_path(const char *raw_path, const char *comp_dir,
			 char **new_path)
245
{
246 247 248 249 250 251 252 253 254 255 256 257 258
	const char *prefix = symbol_conf.source_prefix;

	if (!prefix) {
		if (raw_path[0] != '/' && comp_dir)
			/* If not an absolute path, try to use comp_dir */
			prefix = comp_dir;
		else {
			if (access(raw_path, R_OK) == 0) {
				*new_path = strdup(raw_path);
				return 0;
			} else
				return -errno;
		}
259 260
	}

261
	*new_path = malloc((strlen(prefix) + strlen(raw_path) + 2));
262 263 264 265
	if (!*new_path)
		return -ENOMEM;

	for (;;) {
266
		sprintf(*new_path, "%s/%s", prefix, raw_path);
267 268 269 270

		if (access(*new_path, R_OK) == 0)
			return 0;

271 272 273 274
		if (!symbol_conf.source_prefix)
			/* In case of searching comp_dir, don't retry */
			return -errno;

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
		switch (errno) {
		case ENAMETOOLONG:
		case ENOENT:
		case EROFS:
		case EFAULT:
			raw_path = strchr(++raw_path, '/');
			if (!raw_path) {
				free(*new_path);
				*new_path = NULL;
				return -ENOENT;
			}
			continue;

		default:
			free(*new_path);
			*new_path = NULL;
			return -errno;
		}
	}
}

296 297 298
#define LINEBUF_SIZE 256
#define NR_ADDITIONAL_LINES 2

299
static int __show_one_line(FILE *fp, int l, bool skip, bool show_num)
300 301
{
	char buf[LINEBUF_SIZE];
302 303
	const char *color = show_num ? "" : PERF_COLOR_BLUE;
	const char *prefix = NULL;
304

305
	do {
306 307
		if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
			goto error;
308 309 310 311 312
		if (skip)
			continue;
		if (!prefix) {
			prefix = show_num ? "%7d  " : "         ";
			color_fprintf(stdout, color, prefix, l);
313
		}
314 315 316
		color_fprintf(stdout, color, "%s", buf);

	} while (strchr(buf, '\n') == NULL);
317

318
	return 1;
319
error:
320
	if (ferror(fp)) {
321
		pr_warning("File read error: %s\n", strerror(errno));
322 323 324 325
		return -1;
	}
	return 0;
}
326

327 328 329 330 331 332 333 334
static int _show_one_line(FILE *fp, int l, bool skip, bool show_num)
{
	int rv = __show_one_line(fp, l, skip, show_num);
	if (rv == 0) {
		pr_warning("Source file is shorter than expected.\n");
		rv = -1;
	}
	return rv;
335 336
}

337 338 339 340 341
#define show_one_line_with_num(f,l)	_show_one_line(f,l,false,true)
#define show_one_line(f,l)		_show_one_line(f,l,false,false)
#define skip_one_line(f,l)		_show_one_line(f,l,true,false)
#define show_one_line_or_eof(f,l)	__show_one_line(f,l,false,false)

342 343 344 345
/*
 * Show line-range always requires debuginfo to find source file and
 * line number.
 */
346
int show_line_range(struct line_range *lr, const char *module)
347
{
348
	int l = 1;
349 350 351
	struct line_node *ln;
	FILE *fp;
	int fd, ret;
352
	char *tmp;
353 354

	/* Search a line range */
355 356 357 358
	ret = init_vmlinux();
	if (ret < 0)
		return ret;

359
	fd = open_vmlinux(module);
360 361 362 363 364
	if (fd < 0) {
		pr_warning("Failed to open debuginfo file.\n");
		return fd;
	}

365 366
	ret = find_line_range(fd, lr);
	close(fd);
367 368 369 370 371 372 373
	if (ret == 0) {
		pr_warning("Specified source line is not found.\n");
		return -ENOENT;
	} else if (ret < 0) {
		pr_warning("Debuginfo analysis failed. (%d)\n", ret);
		return ret;
	}
374

375 376
	/* Convert source file path */
	tmp = lr->path;
377
	ret = get_real_path(tmp, lr->comp_dir, &lr->path);
378 379 380 381 382 383
	free(tmp);	/* Free old path */
	if (ret < 0) {
		pr_warning("Failed to find source file. (%d)\n", ret);
		return ret;
	}

384 385 386 387 388 389
	setup_pager();

	if (lr->function)
		fprintf(stdout, "<%s:%d>\n", lr->function,
			lr->start - lr->offset);
	else
390
		fprintf(stdout, "<%s:%d>\n", lr->path, lr->start);
391 392

	fp = fopen(lr->path, "r");
393 394 395 396 397
	if (fp == NULL) {
		pr_warning("Failed to open %s: %s\n", lr->path,
			   strerror(errno));
		return -errno;
	}
398
	/* Skip to starting line number */
399
	while (l < lr->start) {
400
		ret = skip_one_line(fp, l++);
401 402 403
		if (ret < 0)
			goto end;
	}
404 405

	list_for_each_entry(ln, &lr->line_list, list) {
406
		for (; ln->line > l; l++) {
407
			ret = show_one_line(fp, l - lr->offset);
408 409 410
			if (ret < 0)
				goto end;
		}
411
		ret = show_one_line_with_num(fp, l++ - lr->offset);
412 413
		if (ret < 0)
			goto end;
414 415 416 417
	}

	if (lr->end == INT_MAX)
		lr->end = l + NR_ADDITIONAL_LINES;
418 419 420
	while (l <= lr->end) {
		ret = show_one_line_or_eof(fp, l++ - lr->offset);
		if (ret <= 0)
421 422
			break;
	}
423
end:
424
	fclose(fp);
425
	return ret;
426 427
}

428
static int show_available_vars_at(int fd, struct perf_probe_event *pev,
429
				  int max_vls, bool externs)
430 431 432 433 434 435 436 437 438 439 440
{
	char *buf;
	int ret, i;
	struct str_node *node;
	struct variable_list *vls = NULL, *vl;

	buf = synthesize_perf_probe_point(&pev->point);
	if (!buf)
		return -EINVAL;
	pr_debug("Searching variables at %s\n", buf);

441
	ret = find_available_vars_at(fd, pev, &vls, max_vls, externs);
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
	if (ret > 0) {
		/* Some variables were found */
		fprintf(stdout, "Available variables at %s\n", buf);
		for (i = 0; i < ret; i++) {
			vl = &vls[i];
			/*
			 * A probe point might be converted to
			 * several trace points.
			 */
			fprintf(stdout, "\t@<%s+%lu>\n", vl->point.symbol,
				vl->point.offset);
			free(vl->point.symbol);
			if (vl->vars) {
				strlist__for_each(node, vl->vars)
					fprintf(stdout, "\t\t%s\n", node->s);
				strlist__delete(vl->vars);
			} else
				fprintf(stdout, "(No variables)\n");
		}
		free(vls);
	} else
		pr_err("Failed to find variables at %s (%d)\n", buf, ret);

	free(buf);
	return ret;
}

/* Show available variables on given probe point */
int show_available_vars(struct perf_probe_event *pevs, int npevs,
471
			int max_vls, const char *module, bool externs)
472 473 474 475 476 477 478
{
	int i, fd, ret = 0;

	ret = init_vmlinux();
	if (ret < 0)
		return ret;

479
	fd = open_vmlinux(module);
480
	if (fd < 0) {
M
Masami Hiramatsu 已提交
481
		pr_warning("Failed to open debug information file.\n");
482 483 484 485 486 487
		return fd;
	}

	setup_pager();

	for (i = 0; i < npevs && ret >= 0; i++)
488
		ret = show_available_vars_at(fd, &pevs[i], max_vls, externs);
489 490 491 492 493

	close(fd);
	return ret;
}

494 495
#else	/* !DWARF_SUPPORT */

496
static int kprobe_convert_to_perf_probe(struct probe_trace_point *tp,
497
					struct perf_probe_point *pp)
498
{
499 500 501 502 503 504 505
	struct symbol *sym;

	sym = __find_kernel_function_by_name(tp->symbol, NULL);
	if (!sym) {
		pr_err("Failed to find symbol %s in kernel.\n", tp->symbol);
		return -ENOENT;
	}
506 507 508
	pp->function = strdup(tp->symbol);
	if (pp->function == NULL)
		return -ENOMEM;
509 510
	pp->offset = tp->offset;
	pp->retprobe = tp->retprobe;
511 512

	return 0;
513 514
}

515 516
static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
				struct probe_trace_event **tevs __unused,
517
				int max_tevs __unused, const char *mod __unused)
518
{
519 520 521 522
	if (perf_probe_event_need_dwarf(pev)) {
		pr_warning("Debuginfo-analysis is not supported.\n");
		return -ENOSYS;
	}
523 524 525
	return 0;
}

526
int show_line_range(struct line_range *lr __unused, const char *module __unused)
527
{
528 529
	pr_warning("Debuginfo-analysis is not supported.\n");
	return -ENOSYS;
530 531
}

532
int show_available_vars(struct perf_probe_event *pevs __unused,
533 534
			int npevs __unused, int max_vls __unused,
			const char *module __unused, bool externs __unused)
535 536 537 538
{
	pr_warning("Debuginfo-analysis is not supported.\n");
	return -ENOSYS;
}
539 540
#endif

541 542 543 544 545 546 547 548 549 550 551 552 553
static int parse_line_num(char **ptr, int *val, const char *what)
{
	const char *start = *ptr;

	errno = 0;
	*val = strtol(*ptr, ptr, 0);
	if (errno || *ptr == start) {
		semantic_error("'%s' is not a valid number.\n", what);
		return -EINVAL;
	}
	return 0;
}

554 555 556 557 558 559 560
/*
 * Stuff 'lr' according to the line range described by 'arg'.
 * The line range syntax is described by:
 *
 *         SRC[:SLN[+NUM|-ELN]]
 *         FNC[:SLN[+NUM|-ELN]]
 */
561
int parse_line_range_desc(const char *arg, struct line_range *lr)
562
{
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
	char *range, *name = strdup(arg);
	int err;

	if (!name)
		return -ENOMEM;

	lr->start = 0;
	lr->end = INT_MAX;

	range = strchr(name, ':');
	if (range) {
		*range++ = '\0';

		err = parse_line_num(&range, &lr->start, "start line");
		if (err)
			goto err;

		if (*range == '+' || *range == '-') {
			const char c = *range++;

			err = parse_line_num(&range, &lr->end, "end line");
			if (err)
				goto err;

			if (c == '+') {
				lr->end += lr->start;
				/*
				 * Adjust the number of lines here.
				 * If the number of lines == 1, the
				 * the end of line should be equal to
				 * the start of line.
				 */
				lr->end--;
			}
		}
598

599
		pr_debug("Line range is %d to %d\n", lr->start, lr->end);
600 601

		err = -EINVAL;
602
		if (lr->start > lr->end) {
603
			semantic_error("Start line must be smaller"
604
				       " than end line.\n");
605
			goto err;
606
		}
607 608 609
		if (*range != '\0') {
			semantic_error("Tailing with invalid str '%s'.\n", range);
			goto err;
610
		}
611
	}
612

613 614
	if (strchr(name, '.'))
		lr->file = name;
615
	else
616
		lr->function = name;
617 618

	return 0;
619 620 621
err:
	free(name);
	return err;
622 623
}

624 625 626 627 628 629 630 631 632 633 634 635
/* Check the name is good for event/group */
static bool check_event_name(const char *name)
{
	if (!isalpha(*name) && *name != '_')
		return false;
	while (*++name != '\0') {
		if (!isalpha(*name) && !isdigit(*name) && *name != '_')
			return false;
	}
	return true;
}

636
/* Parse probepoint definition. */
637
static int parse_perf_probe_point(char *arg, struct perf_probe_event *pev)
638
{
639
	struct perf_probe_point *pp = &pev->point;
640 641 642 643
	char *ptr, *tmp;
	char c, nc = 0;
	/*
	 * <Syntax>
644 645
	 * perf probe [EVENT=]SRC[:LN|;PTN]
	 * perf probe [EVENT=]FUNC[@SRC][+OFFS|%return|:LN|;PAT]
646 647
	 *
	 * TODO:Group name support
648 649
	 */

650 651
	ptr = strpbrk(arg, ";=@+%");
	if (ptr && *ptr == '=') {	/* Event name */
652 653
		*ptr = '\0';
		tmp = ptr + 1;
654 655 656 657 658
		if (strchr(arg, ':')) {
			semantic_error("Group name is not supported yet.\n");
			return -ENOTSUP;
		}
		if (!check_event_name(arg)) {
659
			semantic_error("%s is bad for event name -it must "
660 661 662
				       "follow C symbol-naming rule.\n", arg);
			return -EINVAL;
		}
663 664 665
		pev->event = strdup(arg);
		if (pev->event == NULL)
			return -ENOMEM;
666
		pev->group = NULL;
667 668 669
		arg = tmp;
	}

670
	ptr = strpbrk(arg, ";:+@%");
671 672 673 674 675
	if (ptr) {
		nc = *ptr;
		*ptr++ = '\0';
	}

676 677 678 679
	tmp = strdup(arg);
	if (tmp == NULL)
		return -ENOMEM;

680
	/* Check arg is function or file and copy it */
681 682
	if (strchr(tmp, '.'))	/* File */
		pp->file = tmp;
683
	else			/* Function */
684
		pp->function = tmp;
685 686 687 688 689

	/* Parse other options */
	while (ptr) {
		arg = ptr;
		c = nc;
690
		if (c == ';') {	/* Lazy pattern must be the last part */
691 692 693
			pp->lazy_line = strdup(arg);
			if (pp->lazy_line == NULL)
				return -ENOMEM;
694 695 696
			break;
		}
		ptr = strpbrk(arg, ";:+@%");
697 698 699 700 701 702 703
		if (ptr) {
			nc = *ptr;
			*ptr++ = '\0';
		}
		switch (c) {
		case ':':	/* Line number */
			pp->line = strtoul(arg, &tmp, 0);
704
			if (*tmp != '\0') {
705
				semantic_error("There is non-digit char"
706 707 708
					       " in line number.\n");
				return -EINVAL;
			}
709 710 711
			break;
		case '+':	/* Byte offset from a symbol */
			pp->offset = strtoul(arg, &tmp, 0);
712
			if (*tmp != '\0') {
713
				semantic_error("There is non-digit character"
714 715 716
						" in offset.\n");
				return -EINVAL;
			}
717 718
			break;
		case '@':	/* File name */
719 720 721 722
			if (pp->file) {
				semantic_error("SRC@SRC is not allowed.\n");
				return -EINVAL;
			}
723 724 725
			pp->file = strdup(arg);
			if (pp->file == NULL)
				return -ENOMEM;
726 727 728 729
			break;
		case '%':	/* Probe places */
			if (strcmp(arg, "return") == 0) {
				pp->retprobe = 1;
730 731 732 733
			} else {	/* Others not supported yet */
				semantic_error("%%%s is not supported.\n", arg);
				return -ENOTSUP;
			}
734
			break;
735 736 737 738
		default:	/* Buggy case */
			pr_err("This program has a bug at %s:%d.\n",
				__FILE__, __LINE__);
			return -ENOTSUP;
739 740 741 742 743
			break;
		}
	}

	/* Exclusion check */
744
	if (pp->lazy_line && pp->line) {
M
Masami Hiramatsu 已提交
745 746
		semantic_error("Lazy pattern can't be used with"
			       " line number.\n");
747 748
		return -EINVAL;
	}
749

750
	if (pp->lazy_line && pp->offset) {
M
Masami Hiramatsu 已提交
751
		semantic_error("Lazy pattern can't be used with offset.\n");
752 753
		return -EINVAL;
	}
754

755
	if (pp->line && pp->offset) {
M
Masami Hiramatsu 已提交
756
		semantic_error("Offset can't be used with line number.\n");
757 758
		return -EINVAL;
	}
759

760
	if (!pp->line && !pp->lazy_line && pp->file && !pp->function) {
761
		semantic_error("File always requires line number or "
M
Masami Hiramatsu 已提交
762
			       "lazy pattern.\n");
763 764
		return -EINVAL;
	}
765

766
	if (pp->offset && !pp->function) {
M
Masami Hiramatsu 已提交
767
		semantic_error("Offset requires an entry function.\n");
768 769
		return -EINVAL;
	}
770

771
	if (pp->retprobe && !pp->function) {
M
Masami Hiramatsu 已提交
772
		semantic_error("Return probe requires an entry function.\n");
773 774
		return -EINVAL;
	}
775

776
	if ((pp->offset || pp->line || pp->lazy_line) && pp->retprobe) {
777
		semantic_error("Offset/Line/Lazy pattern can't be used with "
M
Masami Hiramatsu 已提交
778
			       "return probe.\n");
779 780
		return -EINVAL;
	}
781

782
	pr_debug("symbol:%s file:%s line:%d offset:%lu return:%d lazy:%s\n",
783 784
		 pp->function, pp->file, pp->line, pp->offset, pp->retprobe,
		 pp->lazy_line);
785
	return 0;
786 787
}

788
/* Parse perf-probe event argument */
789
static int parse_perf_probe_arg(char *str, struct perf_probe_arg *arg)
790
{
791
	char *tmp, *goodname;
792 793 794 795
	struct perf_probe_arg_field **fieldp;

	pr_debug("parsing arg: %s into ", str);

796 797
	tmp = strchr(str, '=');
	if (tmp) {
798 799 800
		arg->name = strndup(str, tmp - str);
		if (arg->name == NULL)
			return -ENOMEM;
801
		pr_debug("name:%s ", arg->name);
802 803 804
		str = tmp + 1;
	}

805 806 807
	tmp = strchr(str, ':');
	if (tmp) {	/* Type setting */
		*tmp = '\0';
808 809 810
		arg->type = strdup(tmp + 1);
		if (arg->type == NULL)
			return -ENOMEM;
811 812 813
		pr_debug("type:%s ", arg->type);
	}

814
	tmp = strpbrk(str, "-.[");
815 816
	if (!is_c_varname(str) || !tmp) {
		/* A variable, register, symbol or special value */
817 818 819
		arg->var = strdup(str);
		if (arg->var == NULL)
			return -ENOMEM;
820
		pr_debug("%s\n", arg->var);
821
		return 0;
822 823
	}

824
	/* Structure fields or array element */
825 826 827
	arg->var = strndup(str, tmp - str);
	if (arg->var == NULL)
		return -ENOMEM;
828
	goodname = arg->var;
829
	pr_debug("%s, ", arg->var);
830 831 832
	fieldp = &arg->field;

	do {
833 834 835
		*fieldp = zalloc(sizeof(struct perf_probe_arg_field));
		if (*fieldp == NULL)
			return -ENOMEM;
836 837 838
		if (*tmp == '[') {	/* Array */
			str = tmp;
			(*fieldp)->index = strtol(str + 1, &tmp, 0);
839
			(*fieldp)->ref = true;
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
			if (*tmp != ']' || tmp == str + 1) {
				semantic_error("Array index must be a"
						" number.\n");
				return -EINVAL;
			}
			tmp++;
			if (*tmp == '\0')
				tmp = NULL;
		} else {		/* Structure */
			if (*tmp == '.') {
				str = tmp + 1;
				(*fieldp)->ref = false;
			} else if (tmp[1] == '>') {
				str = tmp + 2;
				(*fieldp)->ref = true;
			} else {
				semantic_error("Argument parse error: %s\n",
					       str);
				return -EINVAL;
			}
			tmp = strpbrk(str, "-.[");
861
		}
862
		if (tmp) {
863 864 865
			(*fieldp)->name = strndup(str, tmp - str);
			if ((*fieldp)->name == NULL)
				return -ENOMEM;
866 867
			if (*str != '[')
				goodname = (*fieldp)->name;
868 869 870 871
			pr_debug("%s(%d), ", (*fieldp)->name, (*fieldp)->ref);
			fieldp = &(*fieldp)->next;
		}
	} while (tmp);
872 873 874
	(*fieldp)->name = strdup(str);
	if ((*fieldp)->name == NULL)
		return -ENOMEM;
875 876
	if (*str != '[')
		goodname = (*fieldp)->name;
877
	pr_debug("%s(%d)\n", (*fieldp)->name, (*fieldp)->ref);
878

879
	/* If no name is specified, set the last field name (not array index)*/
880
	if (!arg->name) {
881
		arg->name = strdup(goodname);
882 883 884
		if (arg->name == NULL)
			return -ENOMEM;
	}
885
	return 0;
886 887
}

888
/* Parse perf-probe event command */
889
int parse_perf_probe_command(const char *cmd, struct perf_probe_event *pev)
890
{
891
	char **argv;
892
	int argc, i, ret = 0;
893

894
	argv = argv_split(cmd, &argc);
895 896 897 898 899 900 901 902 903
	if (!argv) {
		pr_debug("Failed to split arguments.\n");
		return -ENOMEM;
	}
	if (argc - 1 > MAX_PROBE_ARGS) {
		semantic_error("Too many probe arguments (%d).\n", argc - 1);
		ret = -ERANGE;
		goto out;
	}
904
	/* Parse probe point */
905 906 907
	ret = parse_perf_probe_point(argv[0], pev);
	if (ret < 0)
		goto out;
908

909
	/* Copy arguments and ensure return probe has no C argument */
910
	pev->nargs = argc - 1;
911 912 913 914 915
	pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
	if (pev->args == NULL) {
		ret = -ENOMEM;
		goto out;
	}
916 917 918 919
	for (i = 0; i < pev->nargs && ret >= 0; i++) {
		ret = parse_perf_probe_arg(argv[i + 1], &pev->args[i]);
		if (ret >= 0 &&
		    is_c_varname(pev->args[i].var) && pev->point.retprobe) {
920
			semantic_error("You can't specify local variable for"
921 922 923
				       " kretprobe.\n");
			ret = -EINVAL;
		}
924
	}
925
out:
926
	argv_free(argv);
927 928

	return ret;
929 930
}

931 932 933 934 935 936 937 938 939
/* Return true if this perf_probe_event requires debuginfo */
bool perf_probe_event_need_dwarf(struct perf_probe_event *pev)
{
	int i;

	if (pev->point.file || pev->point.line || pev->point.lazy_line)
		return true;

	for (i = 0; i < pev->nargs; i++)
940
		if (is_c_varname(pev->args[i].var))
941 942 943 944 945
			return true;

	return false;
}

946 947 948
/* Parse probe_events event into struct probe_point */
static int parse_probe_trace_command(const char *cmd,
					struct probe_trace_event *tev)
949
{
950
	struct probe_trace_point *tp = &tev->point;
951 952 953 954 955
	char pr;
	char *p;
	int ret, i, argc;
	char **argv;

956
	pr_debug("Parsing probe_events: %s\n", cmd);
957
	argv = argv_split(cmd, &argc);
958 959 960 961 962 963 964 965 966
	if (!argv) {
		pr_debug("Failed to split arguments.\n");
		return -ENOMEM;
	}
	if (argc < 2) {
		semantic_error("Too few probe arguments.\n");
		ret = -ERANGE;
		goto out;
	}
967 968

	/* Scan event and group name. */
969
	ret = sscanf(argv[0], "%c:%a[^/ \t]/%a[^ \t]",
970 971
		     &pr, (float *)(void *)&tev->group,
		     (float *)(void *)&tev->event);
972 973 974 975 976
	if (ret != 3) {
		semantic_error("Failed to parse event name: %s\n", argv[0]);
		ret = -EINVAL;
		goto out;
	}
977
	pr_debug("Group:%s Event:%s probe:%c\n", tev->group, tev->event, pr);
978

979
	tp->retprobe = (pr == 'r');
980 981

	/* Scan function name and offset */
982 983
	ret = sscanf(argv[1], "%a[^+]+%lu", (float *)(void *)&tp->symbol,
		     &tp->offset);
984
	if (ret == 1)
985
		tp->offset = 0;
986

987
	tev->nargs = argc - 2;
988
	tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
989 990 991 992
	if (tev->args == NULL) {
		ret = -ENOMEM;
		goto out;
	}
993
	for (i = 0; i < tev->nargs; i++) {
994 995
		p = strchr(argv[i + 2], '=');
		if (p)	/* We don't need which register is assigned. */
996 997 998
			*p++ = '\0';
		else
			p = argv[i + 2];
999
		tev->args[i].name = strdup(argv[i + 2]);
1000
		/* TODO: parse regs and offset */
1001 1002 1003 1004 1005
		tev->args[i].value = strdup(p);
		if (tev->args[i].name == NULL || tev->args[i].value == NULL) {
			ret = -ENOMEM;
			goto out;
		}
1006
	}
1007 1008
	ret = 0;
out:
1009
	argv_free(argv);
1010
	return ret;
1011 1012
}

1013 1014 1015 1016 1017 1018 1019
/* Compose only probe arg */
int synthesize_perf_probe_arg(struct perf_probe_arg *pa, char *buf, size_t len)
{
	struct perf_probe_arg_field *field = pa->field;
	int ret;
	char *tmp = buf;

1020 1021 1022 1023
	if (pa->name && pa->var)
		ret = e_snprintf(tmp, len, "%s=%s", pa->name, pa->var);
	else
		ret = e_snprintf(tmp, len, "%s", pa->name ? pa->name : pa->var);
1024 1025 1026 1027 1028 1029
	if (ret <= 0)
		goto error;
	tmp += ret;
	len -= ret;

	while (field) {
1030 1031 1032 1033 1034
		if (field->name[0] == '[')
			ret = e_snprintf(tmp, len, "%s", field->name);
		else
			ret = e_snprintf(tmp, len, "%s%s",
					 field->ref ? "->" : ".", field->name);
1035 1036 1037 1038 1039 1040
		if (ret <= 0)
			goto error;
		tmp += ret;
		len -= ret;
		field = field->next;
	}
1041 1042 1043 1044 1045 1046 1047 1048 1049

	if (pa->type) {
		ret = e_snprintf(tmp, len, ":%s", pa->type);
		if (ret <= 0)
			goto error;
		tmp += ret;
		len -= ret;
	}

1050 1051
	return tmp - buf;
error:
M
Masami Hiramatsu 已提交
1052
	pr_debug("Failed to synthesize perf probe argument: %s\n",
1053 1054
		 strerror(-ret));
	return ret;
1055 1056
}

1057 1058
/* Compose only probe point (not argument) */
static char *synthesize_perf_probe_point(struct perf_probe_point *pp)
1059
{
1060 1061 1062
	char *buf, *tmp;
	char offs[32] = "", line[32] = "", file[32] = "";
	int ret, len;
1063

1064 1065 1066 1067 1068
	buf = zalloc(MAX_CMDLEN);
	if (buf == NULL) {
		ret = -ENOMEM;
		goto error;
	}
1069
	if (pp->offset) {
1070
		ret = e_snprintf(offs, 32, "+%lu", pp->offset);
1071 1072 1073 1074
		if (ret <= 0)
			goto error;
	}
	if (pp->line) {
1075 1076 1077 1078 1079
		ret = e_snprintf(line, 32, ":%d", pp->line);
		if (ret <= 0)
			goto error;
	}
	if (pp->file) {
1080 1081 1082 1083 1084 1085 1086
		tmp = pp->file;
		len = strlen(tmp);
		if (len > 30) {
			tmp = strchr(pp->file + len - 30, '/');
			tmp = tmp ? tmp + 1 : pp->file + len - 30;
		}
		ret = e_snprintf(file, 32, "@%s", tmp);
1087 1088 1089 1090 1091
		if (ret <= 0)
			goto error;
	}

	if (pp->function)
1092 1093 1094
		ret = e_snprintf(buf, MAX_CMDLEN, "%s%s%s%s%s", pp->function,
				 offs, pp->retprobe ? "%return" : "", line,
				 file);
1095
	else
1096
		ret = e_snprintf(buf, MAX_CMDLEN, "%s%s", file, line);
1097 1098 1099 1100
	if (ret <= 0)
		goto error;

	return buf;
1101
error:
M
Masami Hiramatsu 已提交
1102
	pr_debug("Failed to synthesize perf probe point: %s\n",
1103
		 strerror(-ret));
1104 1105
	if (buf)
		free(buf);
1106
	return NULL;
1107 1108
}

1109 1110
#if 0
char *synthesize_perf_probe_command(struct perf_probe_event *pev)
1111 1112 1113 1114
{
	char *buf;
	int i, len, ret;

1115 1116 1117
	buf = synthesize_perf_probe_point(&pev->point);
	if (!buf)
		return NULL;
1118

1119 1120
	len = strlen(buf);
	for (i = 0; i < pev->nargs; i++) {
1121
		ret = e_snprintf(&buf[len], MAX_CMDLEN - len, " %s",
1122 1123 1124 1125 1126
				 pev->args[i].name);
		if (ret <= 0) {
			free(buf);
			return NULL;
		}
1127 1128 1129
		len += ret;
	}

1130 1131 1132 1133
	return buf;
}
#endif

1134
static int __synthesize_probe_trace_arg_ref(struct probe_trace_arg_ref *ref,
1135 1136 1137 1138 1139
					     char **buf, size_t *buflen,
					     int depth)
{
	int ret;
	if (ref->next) {
1140
		depth = __synthesize_probe_trace_arg_ref(ref->next, buf,
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
							 buflen, depth + 1);
		if (depth < 0)
			goto out;
	}

	ret = e_snprintf(*buf, *buflen, "%+ld(", ref->offset);
	if (ret < 0)
		depth = ret;
	else {
		*buf += ret;
		*buflen -= ret;
	}
out:
	return depth;
1155 1156 1157

}

1158
static int synthesize_probe_trace_arg(struct probe_trace_arg *arg,
1159
				       char *buf, size_t buflen)
1160
{
1161
	struct probe_trace_arg_ref *ref = arg->ref;
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
	int ret, depth = 0;
	char *tmp = buf;

	/* Argument name or separator */
	if (arg->name)
		ret = e_snprintf(buf, buflen, " %s=", arg->name);
	else
		ret = e_snprintf(buf, buflen, " ");
	if (ret < 0)
		return ret;
	buf += ret;
	buflen -= ret;

1175 1176 1177 1178
	/* Special case: @XXX */
	if (arg->value[0] == '@' && arg->ref)
			ref = ref->next;

1179
	/* Dereferencing arguments */
1180
	if (ref) {
1181
		depth = __synthesize_probe_trace_arg_ref(ref, &buf,
1182 1183 1184 1185 1186 1187
							  &buflen, 1);
		if (depth < 0)
			return depth;
	}

	/* Print argument value */
1188 1189 1190 1191 1192
	if (arg->value[0] == '@' && arg->ref)
		ret = e_snprintf(buf, buflen, "%s%+ld", arg->value,
				 arg->ref->offset);
	else
		ret = e_snprintf(buf, buflen, "%s", arg->value);
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
	if (ret < 0)
		return ret;
	buf += ret;
	buflen -= ret;

	/* Closing */
	while (depth--) {
		ret = e_snprintf(buf, buflen, ")");
		if (ret < 0)
			return ret;
		buf += ret;
		buflen -= ret;
	}
1206 1207 1208 1209 1210 1211 1212
	/* Print argument type */
	if (arg->type) {
		ret = e_snprintf(buf, buflen, ":%s", arg->type);
		if (ret <= 0)
			return ret;
		buf += ret;
	}
1213 1214 1215 1216

	return buf - tmp;
}

1217
char *synthesize_probe_trace_command(struct probe_trace_event *tev)
1218
{
1219
	struct probe_trace_point *tp = &tev->point;
1220 1221 1222
	char *buf;
	int i, len, ret;

1223 1224 1225 1226
	buf = zalloc(MAX_CMDLEN);
	if (buf == NULL)
		return NULL;

1227 1228 1229 1230 1231
	len = e_snprintf(buf, MAX_CMDLEN, "%c:%s/%s %s+%lu",
			 tp->retprobe ? 'r' : 'p',
			 tev->group, tev->event,
			 tp->symbol, tp->offset);
	if (len <= 0)
1232 1233
		goto error;

1234
	for (i = 0; i < tev->nargs; i++) {
1235
		ret = synthesize_probe_trace_arg(&tev->args[i], buf + len,
1236
						  MAX_CMDLEN - len);
1237
		if (ret <= 0)
1238 1239 1240 1241
			goto error;
		len += ret;
	}

1242
	return buf;
1243
error:
1244 1245 1246
	free(buf);
	return NULL;
}
1247

1248
static int convert_to_perf_probe_event(struct probe_trace_event *tev,
1249
				       struct perf_probe_event *pev)
1250
{
1251
	char buf[64] = "";
1252
	int i, ret;
1253

1254
	/* Convert event/group name */
1255 1256 1257 1258
	pev->event = strdup(tev->event);
	pev->group = strdup(tev->group);
	if (pev->event == NULL || pev->group == NULL)
		return -ENOMEM;
1259

1260
	/* Convert trace_point to probe_point */
1261
	ret = kprobe_convert_to_perf_probe(&tev->point, &pev->point);
1262 1263
	if (ret < 0)
		return ret;
1264

1265 1266
	/* Convert trace_arg to probe_arg */
	pev->nargs = tev->nargs;
1267 1268 1269
	pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
	if (pev->args == NULL)
		return -ENOMEM;
1270
	for (i = 0; i < tev->nargs && ret >= 0; i++) {
1271
		if (tev->args[i].name)
1272
			pev->args[i].name = strdup(tev->args[i].name);
1273
		else {
1274
			ret = synthesize_probe_trace_arg(&tev->args[i],
1275
							  buf, 64);
1276
			pev->args[i].name = strdup(buf);
1277
		}
1278 1279 1280
		if (pev->args[i].name == NULL && ret >= 0)
			ret = -ENOMEM;
	}
1281 1282 1283 1284 1285

	if (ret < 0)
		clear_perf_probe_event(pev);

	return ret;
1286 1287 1288 1289 1290
}

void clear_perf_probe_event(struct perf_probe_event *pev)
{
	struct perf_probe_point *pp = &pev->point;
1291
	struct perf_probe_arg_field *field, *next;
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
	int i;

	if (pev->event)
		free(pev->event);
	if (pev->group)
		free(pev->group);
	if (pp->file)
		free(pp->file);
	if (pp->function)
		free(pp->function);
	if (pp->lazy_line)
		free(pp->lazy_line);
1304
	for (i = 0; i < pev->nargs; i++) {
1305 1306
		if (pev->args[i].name)
			free(pev->args[i].name);
1307 1308
		if (pev->args[i].var)
			free(pev->args[i].var);
1309 1310
		if (pev->args[i].type)
			free(pev->args[i].type);
1311 1312 1313 1314 1315 1316 1317 1318 1319
		field = pev->args[i].field;
		while (field) {
			next = field->next;
			if (field->name)
				free(field->name);
			free(field);
			field = next;
		}
	}
1320 1321 1322 1323 1324
	if (pev->args)
		free(pev->args);
	memset(pev, 0, sizeof(*pev));
}

1325
static void clear_probe_trace_event(struct probe_trace_event *tev)
1326
{
1327
	struct probe_trace_arg_ref *ref, *next;
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
	int i;

	if (tev->event)
		free(tev->event);
	if (tev->group)
		free(tev->group);
	if (tev->point.symbol)
		free(tev->point.symbol);
	for (i = 0; i < tev->nargs; i++) {
		if (tev->args[i].name)
			free(tev->args[i].name);
		if (tev->args[i].value)
			free(tev->args[i].value);
1341 1342
		if (tev->args[i].type)
			free(tev->args[i].type);
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
		ref = tev->args[i].ref;
		while (ref) {
			next = ref->next;
			free(ref);
			ref = next;
		}
	}
	if (tev->args)
		free(tev->args);
	memset(tev, 0, sizeof(*tev));
1353 1354
}

1355
static int open_kprobe_events(bool readwrite)
1356 1357
{
	char buf[PATH_MAX];
1358
	const char *__debugfs;
1359 1360
	int ret;

1361 1362 1363 1364 1365 1366 1367
	__debugfs = debugfs_find_mountpoint();
	if (__debugfs == NULL) {
		pr_warning("Debugfs is not mounted.\n");
		return -ENOENT;
	}

	ret = e_snprintf(buf, PATH_MAX, "%stracing/kprobe_events", __debugfs);
1368
	if (ret >= 0) {
1369
		pr_debug("Opening %s write=%d\n", buf, readwrite);
1370 1371 1372 1373 1374
		if (readwrite && !probe_event_dry_run)
			ret = open(buf, O_RDWR, O_APPEND);
		else
			ret = open(buf, O_RDONLY, 0);
	}
1375

1376 1377
	if (ret < 0) {
		if (errno == ENOENT)
1378 1379
			pr_warning("kprobe_events file does not exist - please"
				 " rebuild kernel with CONFIG_KPROBE_EVENT.\n");
1380
		else
1381 1382
			pr_warning("Failed to open kprobe_events file: %s\n",
				   strerror(errno));
1383 1384 1385 1386 1387
	}
	return ret;
}

/* Get raw string list of current kprobe_events */
1388
static struct strlist *get_probe_trace_command_rawlist(int fd)
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
{
	int ret, idx;
	FILE *fp;
	char buf[MAX_CMDLEN];
	char *p;
	struct strlist *sl;

	sl = strlist__new(true, NULL);

	fp = fdopen(dup(fd), "r");
	while (!feof(fp)) {
		p = fgets(buf, MAX_CMDLEN, fp);
		if (!p)
			break;

		idx = strlen(p) - 1;
		if (p[idx] == '\n')
			p[idx] = '\0';
		ret = strlist__add(sl, buf);
1408 1409 1410 1411 1412
		if (ret < 0) {
			pr_debug("strlist__add failed: %s\n", strerror(-ret));
			strlist__delete(sl);
			return NULL;
		}
1413 1414 1415 1416 1417 1418
	}
	fclose(fp);

	return sl;
}

1419
/* Show an event */
1420
static int show_perf_probe_event(struct perf_probe_event *pev)
1421
{
1422
	int i, ret;
1423
	char buf[128];
1424
	char *place;
1425

1426 1427
	/* Synthesize only event probe point */
	place = synthesize_perf_probe_point(&pev->point);
1428 1429
	if (!place)
		return -EINVAL;
1430 1431

	ret = e_snprintf(buf, 128, "%s:%s", pev->group, pev->event);
1432
	if (ret < 0)
1433 1434
		return ret;

1435
	printf("  %-20s (on %s", buf, place);
1436

1437
	if (pev->nargs > 0) {
1438
		printf(" with");
1439
		for (i = 0; i < pev->nargs; i++) {
1440 1441 1442 1443
			ret = synthesize_perf_probe_arg(&pev->args[i],
							buf, 128);
			if (ret < 0)
				break;
1444 1445
			printf(" %s", buf);
		}
1446 1447
	}
	printf(")\n");
1448
	free(place);
1449
	return ret;
1450 1451
}

1452
/* List up current perf-probe events */
1453
int show_perf_probe_events(void)
1454
{
1455
	int fd, ret;
1456
	struct probe_trace_event tev;
1457
	struct perf_probe_event pev;
1458 1459 1460
	struct strlist *rawlist;
	struct str_node *ent;

1461
	setup_pager();
1462 1463 1464
	ret = init_vmlinux();
	if (ret < 0)
		return ret;
1465 1466 1467

	memset(&tev, 0, sizeof(tev));
	memset(&pev, 0, sizeof(pev));
1468

1469
	fd = open_kprobe_events(false);
1470 1471 1472
	if (fd < 0)
		return fd;

1473
	rawlist = get_probe_trace_command_rawlist(fd);
1474
	close(fd);
1475 1476
	if (!rawlist)
		return -ENOENT;
1477

1478
	strlist__for_each(ent, rawlist) {
1479
		ret = parse_probe_trace_command(ent->s, &tev);
1480 1481 1482 1483 1484
		if (ret >= 0) {
			ret = convert_to_perf_probe_event(&tev, &pev);
			if (ret >= 0)
				ret = show_perf_probe_event(&pev);
		}
1485
		clear_perf_probe_event(&pev);
1486
		clear_probe_trace_event(&tev);
1487 1488
		if (ret < 0)
			break;
1489 1490
	}
	strlist__delete(rawlist);
1491 1492

	return ret;
1493 1494
}

1495
/* Get current perf-probe event names */
1496
static struct strlist *get_probe_trace_event_names(int fd, bool include_group)
1497
{
1498
	char buf[128];
1499 1500
	struct strlist *sl, *rawlist;
	struct str_node *ent;
1501
	struct probe_trace_event tev;
1502
	int ret = 0;
1503

1504
	memset(&tev, 0, sizeof(tev));
1505
	rawlist = get_probe_trace_command_rawlist(fd);
1506
	sl = strlist__new(true, NULL);
1507
	strlist__for_each(ent, rawlist) {
1508
		ret = parse_probe_trace_command(ent->s, &tev);
1509 1510
		if (ret < 0)
			break;
1511
		if (include_group) {
1512 1513 1514 1515
			ret = e_snprintf(buf, 128, "%s:%s", tev.group,
					tev.event);
			if (ret >= 0)
				ret = strlist__add(sl, buf);
1516
		} else
1517
			ret = strlist__add(sl, tev.event);
1518
		clear_probe_trace_event(&tev);
1519 1520
		if (ret < 0)
			break;
1521 1522 1523
	}
	strlist__delete(rawlist);

1524 1525 1526 1527
	if (ret < 0) {
		strlist__delete(sl);
		return NULL;
	}
1528 1529 1530
	return sl;
}

1531
static int write_probe_trace_event(int fd, struct probe_trace_event *tev)
1532
{
1533
	int ret = 0;
1534
	char *buf = synthesize_probe_trace_command(tev);
1535

1536
	if (!buf) {
1537
		pr_debug("Failed to synthesize probe trace event.\n");
1538 1539 1540
		return -EINVAL;
	}

1541
	pr_debug("Writing event: %s\n", buf);
1542 1543 1544
	if (!probe_event_dry_run) {
		ret = write(fd, buf, strlen(buf));
		if (ret <= 0)
1545 1546
			pr_warning("Failed to write event: %s\n",
				   strerror(errno));
1547
	}
1548
	free(buf);
1549
	return ret;
1550 1551
}

1552 1553
static int get_new_event_name(char *buf, size_t len, const char *base,
			      struct strlist *namelist, bool allow_suffix)
1554 1555
{
	int i, ret;
1556 1557 1558

	/* Try no suffix */
	ret = e_snprintf(buf, len, "%s", base);
1559 1560 1561 1562
	if (ret < 0) {
		pr_debug("snprintf() failed: %s\n", strerror(-ret));
		return ret;
	}
1563
	if (!strlist__has_entry(namelist, buf))
1564
		return 0;
1565

1566 1567 1568
	if (!allow_suffix) {
		pr_warning("Error: event \"%s\" already exists. "
			   "(Use -f to force duplicates.)\n", base);
1569
		return -EEXIST;
1570 1571
	}

1572 1573
	/* Try to add suffix */
	for (i = 1; i < MAX_EVENT_INDEX; i++) {
1574
		ret = e_snprintf(buf, len, "%s_%d", base, i);
1575 1576 1577 1578
		if (ret < 0) {
			pr_debug("snprintf() failed: %s\n", strerror(-ret));
			return ret;
		}
1579 1580 1581
		if (!strlist__has_entry(namelist, buf))
			break;
	}
1582 1583 1584 1585 1586 1587
	if (i == MAX_EVENT_INDEX) {
		pr_warning("Too many events are on the same function.\n");
		ret = -ERANGE;
	}

	return ret;
1588 1589
}

1590 1591
static int __add_probe_trace_events(struct perf_probe_event *pev,
				     struct probe_trace_event *tevs,
1592
				     int ntevs, bool allow_suffix)
1593
{
1594
	int i, fd, ret;
1595
	struct probe_trace_event *tev = NULL;
1596 1597
	char buf[64];
	const char *event, *group;
1598
	struct strlist *namelist;
1599

1600
	fd = open_kprobe_events(true);
1601 1602
	if (fd < 0)
		return fd;
1603
	/* Get current event names */
1604
	namelist = get_probe_trace_event_names(fd, false);
1605 1606 1607 1608
	if (!namelist) {
		pr_debug("Failed to get current event list.\n");
		return -EIO;
	}
1609

1610
	ret = 0;
1611
	printf("Add new event%s\n", (ntevs > 1) ? "s:" : ":");
1612
	for (i = 0; i < ntevs; i++) {
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
		tev = &tevs[i];
		if (pev->event)
			event = pev->event;
		else
			if (pev->point.function)
				event = pev->point.function;
			else
				event = tev->point.symbol;
		if (pev->group)
			group = pev->group;
		else
			group = PERFPROBE_GROUP;

		/* Get an unused new event name */
1627 1628 1629 1630
		ret = get_new_event_name(buf, 64, event,
					 namelist, allow_suffix);
		if (ret < 0)
			break;
1631 1632
		event = buf;

1633 1634 1635 1636 1637 1638
		tev->event = strdup(event);
		tev->group = strdup(group);
		if (tev->event == NULL || tev->group == NULL) {
			ret = -ENOMEM;
			break;
		}
1639
		ret = write_probe_trace_event(fd, tev);
1640 1641
		if (ret < 0)
			break;
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
		/* Add added event name to namelist */
		strlist__add(namelist, event);

		/* Trick here - save current event/group */
		event = pev->event;
		group = pev->group;
		pev->event = tev->event;
		pev->group = tev->group;
		show_perf_probe_event(pev);
		/* Trick here - restore current event/group */
		pev->event = (char *)event;
		pev->group = (char *)group;

		/*
		 * Probes after the first probe which comes from same
		 * user input are always allowed to add suffix, because
		 * there might be several addresses corresponding to
		 * one code line.
		 */
		allow_suffix = true;
1662
	}
1663 1664 1665 1666 1667 1668 1669

	if (ret >= 0) {
		/* Show how to use the event. */
		printf("\nYou can now use it on all perf tools, such as:\n\n");
		printf("\tperf record -e %s:%s -aR sleep 1\n\n", tev->group,
			 tev->event);
	}
1670

1671
	strlist__delete(namelist);
1672
	close(fd);
1673
	return ret;
1674
}
1675

1676 1677
static int convert_to_probe_trace_events(struct perf_probe_event *pev,
					  struct probe_trace_event **tevs,
1678
					  int max_tevs, const char *module)
1679 1680
{
	struct symbol *sym;
1681
	int ret = 0, i;
1682
	struct probe_trace_event *tev;
1683

1684
	/* Convert perf_probe_event with debuginfo */
1685
	ret = try_to_find_probe_trace_events(pev, tevs, max_tevs, module);
1686 1687
	if (ret != 0)
		return ret;
1688

1689
	/* Allocate trace event buffer */
1690
	tev = *tevs = zalloc(sizeof(struct probe_trace_event));
1691 1692
	if (tev == NULL)
		return -ENOMEM;
1693 1694

	/* Copy parameters */
1695 1696 1697 1698 1699
	tev->point.symbol = strdup(pev->point.function);
	if (tev->point.symbol == NULL) {
		ret = -ENOMEM;
		goto error;
	}
1700
	tev->point.offset = pev->point.offset;
1701
	tev->point.retprobe = pev->point.retprobe;
1702 1703
	tev->nargs = pev->nargs;
	if (tev->nargs) {
1704
		tev->args = zalloc(sizeof(struct probe_trace_arg)
1705 1706
				   * tev->nargs);
		if (tev->args == NULL) {
1707 1708
			ret = -ENOMEM;
			goto error;
1709
		}
1710
		for (i = 0; i < tev->nargs; i++) {
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
			if (pev->args[i].name) {
				tev->args[i].name = strdup(pev->args[i].name);
				if (tev->args[i].name == NULL) {
					ret = -ENOMEM;
					goto error;
				}
			}
			tev->args[i].value = strdup(pev->args[i].var);
			if (tev->args[i].value == NULL) {
				ret = -ENOMEM;
				goto error;
			}
			if (pev->args[i].type) {
				tev->args[i].type = strdup(pev->args[i].type);
				if (tev->args[i].type == NULL) {
					ret = -ENOMEM;
					goto error;
				}
			}
1730
		}
1731 1732 1733
	}

	/* Currently just checking function name from symbol map */
1734
	sym = __find_kernel_function_by_name(tev->point.symbol, NULL);
1735 1736 1737
	if (!sym) {
		pr_warning("Kernel symbol \'%s\' not found.\n",
			   tev->point.symbol);
1738 1739 1740
		ret = -ENOENT;
		goto error;
	}
1741

1742 1743
	return 1;
error:
1744
	clear_probe_trace_event(tev);
1745 1746
	free(tev);
	*tevs = NULL;
1747
	return ret;
1748 1749 1750 1751
}

struct __event_package {
	struct perf_probe_event		*pev;
1752
	struct probe_trace_event	*tevs;
1753 1754 1755
	int				ntevs;
};

1756
int add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
1757
			  int max_tevs, const char *module, bool force_add)
1758
{
1759
	int i, j, ret;
1760 1761
	struct __event_package *pkgs;

1762 1763 1764
	pkgs = zalloc(sizeof(struct __event_package) * npevs);
	if (pkgs == NULL)
		return -ENOMEM;
1765 1766

	/* Init vmlinux path */
1767
	ret = init_vmlinux();
1768 1769
	if (ret < 0) {
		free(pkgs);
1770
		return ret;
1771
	}
1772 1773 1774 1775 1776

	/* Loop 1: convert all events */
	for (i = 0; i < npevs; i++) {
		pkgs[i].pev = &pevs[i];
		/* Convert with or without debuginfo */
1777
		ret  = convert_to_probe_trace_events(pkgs[i].pev,
1778 1779 1780
						     &pkgs[i].tevs,
						     max_tevs,
						     module);
1781 1782 1783
		if (ret < 0)
			goto end;
		pkgs[i].ntevs = ret;
1784 1785
	}

1786
	/* Loop 2: add all events */
1787
	for (i = 0; i < npevs && ret >= 0; i++)
1788
		ret = __add_probe_trace_events(pkgs[i].pev, pkgs[i].tevs,
1789 1790
						pkgs[i].ntevs, force_add);
end:
1791 1792
	/* Loop 3: cleanup and free trace events  */
	for (i = 0; i < npevs; i++) {
1793
		for (j = 0; j < pkgs[i].ntevs; j++)
1794
			clear_probe_trace_event(&pkgs[i].tevs[j]);
1795 1796 1797
		free(pkgs[i].tevs);
	}
	free(pkgs);
1798 1799

	return ret;
1800 1801
}

1802
static int __del_trace_probe_event(int fd, struct str_node *ent)
1803 1804 1805
{
	char *p;
	char buf[128];
1806
	int ret;
1807

1808
	/* Convert from perf-probe event to trace-probe event */
1809 1810 1811 1812
	ret = e_snprintf(buf, 128, "-:%s", ent->s);
	if (ret < 0)
		goto error;

1813
	p = strchr(buf + 2, ':');
1814 1815 1816 1817 1818 1819
	if (!p) {
		pr_debug("Internal error: %s should have ':' but not.\n",
			 ent->s);
		ret = -ENOTSUP;
		goto error;
	}
1820 1821
	*p = '/';

1822 1823
	pr_debug("Writing event: %s\n", buf);
	ret = write(fd, buf, strlen(buf));
1824 1825 1826
	if (ret < 0)
		goto error;

1827
	printf("Remove event: %s\n", ent->s);
1828 1829 1830 1831
	return 0;
error:
	pr_warning("Failed to delete event: %s\n", strerror(-ret));
	return ret;
1832 1833
}

1834
static int del_trace_probe_event(int fd, const char *group,
1835
				  const char *event, struct strlist *namelist)
1836 1837
{
	char buf[128];
1838
	struct str_node *ent, *n;
1839
	int found = 0, ret = 0;
1840

1841 1842
	ret = e_snprintf(buf, 128, "%s:%s", group, event);
	if (ret < 0) {
M
Masami Hiramatsu 已提交
1843
		pr_err("Failed to copy event.\n");
1844 1845
		return ret;
	}
1846

1847 1848 1849 1850
	if (strpbrk(buf, "*?")) { /* Glob-exp */
		strlist__for_each_safe(ent, n, namelist)
			if (strglobmatch(ent->s, buf)) {
				found++;
1851
				ret = __del_trace_probe_event(fd, ent);
1852 1853
				if (ret < 0)
					break;
1854 1855 1856 1857 1858 1859
				strlist__remove(namelist, ent);
			}
	} else {
		ent = strlist__find(namelist, buf);
		if (ent) {
			found++;
1860
			ret = __del_trace_probe_event(fd, ent);
1861 1862
			if (ret >= 0)
				strlist__remove(namelist, ent);
1863 1864
		}
	}
1865 1866 1867 1868
	if (found == 0 && ret >= 0)
		pr_info("Info: Event \"%s\" does not exist.\n", buf);

	return ret;
1869 1870
}

1871
int del_perf_probe_events(struct strlist *dellist)
1872
{
1873
	int fd, ret = 0;
1874 1875 1876 1877 1878
	const char *group, *event;
	char *p, *str;
	struct str_node *ent;
	struct strlist *namelist;

1879
	fd = open_kprobe_events(true);
1880 1881 1882
	if (fd < 0)
		return fd;

1883
	/* Get current event names */
1884
	namelist = get_probe_trace_event_names(fd, true);
1885 1886
	if (namelist == NULL)
		return -EINVAL;
1887

1888
	strlist__for_each(ent, dellist) {
1889 1890 1891 1892 1893
		str = strdup(ent->s);
		if (str == NULL) {
			ret = -ENOMEM;
			break;
		}
1894
		pr_debug("Parsing: %s\n", str);
1895 1896 1897 1898 1899 1900
		p = strchr(str, ':');
		if (p) {
			group = str;
			*p = '\0';
			event = p + 1;
		} else {
1901
			group = "*";
1902 1903
			event = str;
		}
1904
		pr_debug("Group: %s, Event: %s\n", group, event);
1905
		ret = del_trace_probe_event(fd, group, event, namelist);
1906
		free(str);
1907 1908
		if (ret < 0)
			break;
1909 1910 1911
	}
	strlist__delete(namelist);
	close(fd);
1912 1913

	return ret;
1914 1915
}