probe-event.c 41.1 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 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
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;

	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;
	} else {
		dso = machine.vmlinux_maps[MAP__FUNCTION]->dso;
		if (dso__load_vmlinux_path(dso,
			 machine.vmlinux_maps[MAP__FUNCTION], NULL) < 0) {
			pr_debug("Failed to load kernel map.\n");
			return NULL;
		}
	}
found:
	return dso->long_name;
}

138
#ifdef DWARF_SUPPORT
139
static int open_vmlinux(const char *module)
140
{
141 142
	const char *path = kernel_get_module_path(module);
	if (!path) {
M
Masami Hiramatsu 已提交
143 144
		pr_err("Failed to find path of %s module.\n",
		       module ?: "kernel");
145
		return -ENOENT;
146
	}
147 148
	pr_debug("Try to open %s\n", path);
	return open(path, O_RDONLY);
149
}
150

151 152 153 154 155
/*
 * Convert trace point to probe point with debuginfo
 * Currently only handles kprobes.
 */
static int kprobe_convert_to_perf_probe(struct probe_trace_point *tp,
156
					struct perf_probe_point *pp)
157 158
{
	struct symbol *sym;
159 160 161
	struct map *map;
	u64 addr;
	int ret = -ENOENT;
162

163
	sym = __find_kernel_function_by_name(tp->symbol, &map);
164
	if (sym) {
165 166 167 168
		addr = map->unmap_ip(map, sym->start + tp->offset);
		pr_debug("try to find %s+%ld@%llx\n", tp->symbol,
			 tp->offset, addr);
		ret = find_perf_probe_point((unsigned long)addr, pp);
169 170
	}
	if (ret <= 0) {
171 172
		pr_debug("Failed to find corresponding probes from "
			 "debuginfo. Use kprobe event information.\n");
173 174 175
		pp->function = strdup(tp->symbol);
		if (pp->function == NULL)
			return -ENOMEM;
176 177 178
		pp->offset = tp->offset;
	}
	pp->retprobe = tp->retprobe;
179 180

	return 0;
181 182 183
}

/* Try to find perf_probe_event with debuginfo */
184 185
static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
					   struct probe_trace_event **tevs,
186
					   int max_tevs, const char *module)
187 188 189 190
{
	bool need_dwarf = perf_probe_event_need_dwarf(pev);
	int fd, ntevs;

191
	fd = open_vmlinux(module);
192
	if (fd < 0) {
193 194 195 196
		if (need_dwarf) {
			pr_warning("Failed to open debuginfo file.\n");
			return fd;
		}
197 198 199 200 201
		pr_debug("Could not open vmlinux. Try to use symbols.\n");
		return 0;
	}

	/* Searching trace events corresponding to probe event */
202
	ntevs = find_probe_trace_events(fd, pev, tevs, max_tevs);
203 204
	close(fd);

205
	if (ntevs > 0) {	/* Succeeded to find trace events */
206
		pr_debug("find %d probe_trace_events.\n", ntevs);
207
		return ntevs;
208
	}
209

210 211 212 213 214 215
	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 */
216 217 218 219 220
	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 已提交
221
			pr_debug("Trying to use symbols.\n");
222 223
			return 0;
		}
224
	}
225
	return ntevs;
226 227
}

228 229 230 231 232 233
/*
 * 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.
 */
234 235
static int get_real_path(const char *raw_path, const char *comp_dir,
			 char **new_path)
236
{
237 238 239 240 241 242 243 244 245 246 247 248 249
	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;
		}
250 251
	}

252
	*new_path = malloc((strlen(prefix) + strlen(raw_path) + 2));
253 254 255 256
	if (!*new_path)
		return -ENOMEM;

	for (;;) {
257
		sprintf(*new_path, "%s/%s", prefix, raw_path);
258 259 260 261

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

262 263 264 265
		if (!symbol_conf.source_prefix)
			/* In case of searching comp_dir, don't retry */
			return -errno;

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
		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;
		}
	}
}

287 288 289
#define LINEBUF_SIZE 256
#define NR_ADDITIONAL_LINES 2

290
static int show_one_line(FILE *fp, int l, bool skip, bool show_num)
291 292 293 294 295 296 297 298
{
	char buf[LINEBUF_SIZE];
	const char *color = PERF_COLOR_BLUE;

	if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
		goto error;
	if (!skip) {
		if (show_num)
299
			fprintf(stdout, "%7d  %s", l, buf);
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
		else
			color_fprintf(stdout, color, "         %s", buf);
	}

	while (strlen(buf) == LINEBUF_SIZE - 1 &&
	       buf[LINEBUF_SIZE - 2] != '\n') {
		if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
			goto error;
		if (!skip) {
			if (show_num)
				fprintf(stdout, "%s", buf);
			else
				color_fprintf(stdout, color, "%s", buf);
		}
	}
315 316

	return 0;
317 318
error:
	if (feof(fp))
319
		pr_warning("Source file is shorter than expected.\n");
320
	else
321 322 323
		pr_warning("File read error: %s\n", strerror(errno));

	return -1;
324 325 326 327 328 329
}

/*
 * Show line-range always requires debuginfo to find source file and
 * line number.
 */
330
int show_line_range(struct line_range *lr, const char *module)
331
{
332
	int l = 1;
333 334 335
	struct line_node *ln;
	FILE *fp;
	int fd, ret;
336
	char *tmp;
337 338

	/* Search a line range */
339 340 341 342
	ret = init_vmlinux();
	if (ret < 0)
		return ret;

343
	fd = open_vmlinux(module);
344 345 346 347 348
	if (fd < 0) {
		pr_warning("Failed to open debuginfo file.\n");
		return fd;
	}

349 350
	ret = find_line_range(fd, lr);
	close(fd);
351 352 353 354 355 356 357
	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;
	}
358

359 360
	/* Convert source file path */
	tmp = lr->path;
361
	ret = get_real_path(tmp, lr->comp_dir, &lr->path);
362 363 364 365 366 367
	free(tmp);	/* Free old path */
	if (ret < 0) {
		pr_warning("Failed to find source file. (%d)\n", ret);
		return ret;
	}

368 369 370 371 372 373 374 375 376
	setup_pager();

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

	fp = fopen(lr->path, "r");
377 378 379 380 381
	if (fp == NULL) {
		pr_warning("Failed to open %s: %s\n", lr->path,
			   strerror(errno));
		return -errno;
	}
382
	/* Skip to starting line number */
383 384 385 386
	while (l < lr->start && ret >= 0)
		ret = show_one_line(fp, l++, true, false);
	if (ret < 0)
		goto end;
387 388

	list_for_each_entry(ln, &lr->line_list, list) {
389 390 391 392 393 394 395 396
		while (ln->line > l && ret >= 0)
			ret = show_one_line(fp, (l++) - lr->offset,
					    false, false);
		if (ret >= 0)
			ret = show_one_line(fp, (l++) - lr->offset,
					    false, true);
		if (ret < 0)
			goto end;
397 398 399 400
	}

	if (lr->end == INT_MAX)
		lr->end = l + NR_ADDITIONAL_LINES;
401
	while (l <= lr->end && !feof(fp) && ret >= 0)
402 403
		ret = show_one_line(fp, (l++) - lr->offset, false, false);
end:
404
	fclose(fp);
405
	return ret;
406 407
}

408
static int show_available_vars_at(int fd, struct perf_probe_event *pev,
409
				  int max_vls, bool externs)
410 411 412 413 414 415 416 417 418 419 420
{
	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);

421
	ret = find_available_vars_at(fd, pev, &vls, max_vls, externs);
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
	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,
451
			int max_vls, const char *module, bool externs)
452 453 454 455 456 457 458
{
	int i, fd, ret = 0;

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

459
	fd = open_vmlinux(module);
460
	if (fd < 0) {
M
Masami Hiramatsu 已提交
461
		pr_warning("Failed to open debug information file.\n");
462 463 464 465 466 467
		return fd;
	}

	setup_pager();

	for (i = 0; i < npevs && ret >= 0; i++)
468
		ret = show_available_vars_at(fd, &pevs[i], max_vls, externs);
469 470 471 472 473

	close(fd);
	return ret;
}

474 475
#else	/* !DWARF_SUPPORT */

476
static int kprobe_convert_to_perf_probe(struct probe_trace_point *tp,
477
					struct perf_probe_point *pp)
478
{
479 480 481 482 483 484 485
	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;
	}
486 487 488
	pp->function = strdup(tp->symbol);
	if (pp->function == NULL)
		return -ENOMEM;
489 490
	pp->offset = tp->offset;
	pp->retprobe = tp->retprobe;
491 492

	return 0;
493 494
}

495 496
static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
				struct probe_trace_event **tevs __unused,
497
				int max_tevs __unused, const char *mod __unused)
498
{
499 500 501 502
	if (perf_probe_event_need_dwarf(pev)) {
		pr_warning("Debuginfo-analysis is not supported.\n");
		return -ENOSYS;
	}
503 504 505
	return 0;
}

506
int show_line_range(struct line_range *lr __unused, const char *module __unused)
507
{
508 509
	pr_warning("Debuginfo-analysis is not supported.\n");
	return -ENOSYS;
510 511
}

512
int show_available_vars(struct perf_probe_event *pevs __unused,
513 514
			int npevs __unused, int max_vls __unused,
			const char *module __unused, bool externs __unused)
515 516 517 518
{
	pr_warning("Debuginfo-analysis is not supported.\n");
	return -ENOSYS;
}
519 520
#endif

521
int parse_line_range_desc(const char *arg, struct line_range *lr)
522 523 524 525 526 527 528 529 530 531
{
	const char *ptr;
	char *tmp;
	/*
	 * <Syntax>
	 * SRC:SLN[+NUM|-ELN]
	 * FUNC[:SLN[+NUM|-ELN]]
	 */
	ptr = strchr(arg, ':');
	if (ptr) {
532
		lr->start = (int)strtoul(ptr + 1, &tmp, 0);
533
		if (*tmp == '+') {
534
			lr->end = lr->start + (int)strtoul(tmp + 1, &tmp, 0);
535 536 537 538 539 540 541
			lr->end--;	/*
					 * 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.
					 */
		} else if (*tmp == '-')
542
			lr->end = (int)strtoul(tmp + 1, &tmp, 0);
543
		else
544 545 546
			lr->end = INT_MAX;
		pr_debug("Line range is %d to %d\n", lr->start, lr->end);
		if (lr->start > lr->end) {
547
			semantic_error("Start line must be smaller"
548 549 550 551 552
				       " than end line.\n");
			return -EINVAL;
		}
		if (*tmp != '\0') {
			semantic_error("Tailing with invalid character '%d'.\n",
553
				       *tmp);
554 555
			return -EINVAL;
		}
556
		tmp = strndup(arg, (ptr - arg));
557
	} else {
558
		tmp = strdup(arg);
559 560
		lr->end = INT_MAX;
	}
561 562 563

	if (tmp == NULL)
		return -ENOMEM;
564 565 566 567 568

	if (strchr(tmp, '.'))
		lr->file = tmp;
	else
		lr->function = tmp;
569 570

	return 0;
571 572
}

573 574 575 576 577 578 579 580 581 582 583 584
/* 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;
}

585
/* Parse probepoint definition. */
586
static int parse_perf_probe_point(char *arg, struct perf_probe_event *pev)
587
{
588
	struct perf_probe_point *pp = &pev->point;
589 590 591 592
	char *ptr, *tmp;
	char c, nc = 0;
	/*
	 * <Syntax>
593 594
	 * perf probe [EVENT=]SRC[:LN|;PTN]
	 * perf probe [EVENT=]FUNC[@SRC][+OFFS|%return|:LN|;PAT]
595 596
	 *
	 * TODO:Group name support
597 598
	 */

599 600
	ptr = strpbrk(arg, ";=@+%");
	if (ptr && *ptr == '=') {	/* Event name */
601 602
		*ptr = '\0';
		tmp = ptr + 1;
603 604 605 606 607
		if (strchr(arg, ':')) {
			semantic_error("Group name is not supported yet.\n");
			return -ENOTSUP;
		}
		if (!check_event_name(arg)) {
608
			semantic_error("%s is bad for event name -it must "
609 610 611
				       "follow C symbol-naming rule.\n", arg);
			return -EINVAL;
		}
612 613 614
		pev->event = strdup(arg);
		if (pev->event == NULL)
			return -ENOMEM;
615
		pev->group = NULL;
616 617 618
		arg = tmp;
	}

619
	ptr = strpbrk(arg, ";:+@%");
620 621 622 623 624
	if (ptr) {
		nc = *ptr;
		*ptr++ = '\0';
	}

625 626 627 628
	tmp = strdup(arg);
	if (tmp == NULL)
		return -ENOMEM;

629
	/* Check arg is function or file and copy it */
630 631
	if (strchr(tmp, '.'))	/* File */
		pp->file = tmp;
632
	else			/* Function */
633
		pp->function = tmp;
634 635 636 637 638

	/* Parse other options */
	while (ptr) {
		arg = ptr;
		c = nc;
639
		if (c == ';') {	/* Lazy pattern must be the last part */
640 641 642
			pp->lazy_line = strdup(arg);
			if (pp->lazy_line == NULL)
				return -ENOMEM;
643 644 645
			break;
		}
		ptr = strpbrk(arg, ";:+@%");
646 647 648 649 650 651 652
		if (ptr) {
			nc = *ptr;
			*ptr++ = '\0';
		}
		switch (c) {
		case ':':	/* Line number */
			pp->line = strtoul(arg, &tmp, 0);
653
			if (*tmp != '\0') {
654
				semantic_error("There is non-digit char"
655 656 657
					       " in line number.\n");
				return -EINVAL;
			}
658 659 660
			break;
		case '+':	/* Byte offset from a symbol */
			pp->offset = strtoul(arg, &tmp, 0);
661
			if (*tmp != '\0') {
662
				semantic_error("There is non-digit character"
663 664 665
						" in offset.\n");
				return -EINVAL;
			}
666 667
			break;
		case '@':	/* File name */
668 669 670 671
			if (pp->file) {
				semantic_error("SRC@SRC is not allowed.\n");
				return -EINVAL;
			}
672 673 674
			pp->file = strdup(arg);
			if (pp->file == NULL)
				return -ENOMEM;
675 676 677 678
			break;
		case '%':	/* Probe places */
			if (strcmp(arg, "return") == 0) {
				pp->retprobe = 1;
679 680 681 682
			} else {	/* Others not supported yet */
				semantic_error("%%%s is not supported.\n", arg);
				return -ENOTSUP;
			}
683
			break;
684 685 686 687
		default:	/* Buggy case */
			pr_err("This program has a bug at %s:%d.\n",
				__FILE__, __LINE__);
			return -ENOTSUP;
688 689 690 691 692
			break;
		}
	}

	/* Exclusion check */
693
	if (pp->lazy_line && pp->line) {
M
Masami Hiramatsu 已提交
694 695
		semantic_error("Lazy pattern can't be used with"
			       " line number.\n");
696 697
		return -EINVAL;
	}
698

699
	if (pp->lazy_line && pp->offset) {
M
Masami Hiramatsu 已提交
700
		semantic_error("Lazy pattern can't be used with offset.\n");
701 702
		return -EINVAL;
	}
703

704
	if (pp->line && pp->offset) {
M
Masami Hiramatsu 已提交
705
		semantic_error("Offset can't be used with line number.\n");
706 707
		return -EINVAL;
	}
708

709
	if (!pp->line && !pp->lazy_line && pp->file && !pp->function) {
710
		semantic_error("File always requires line number or "
M
Masami Hiramatsu 已提交
711
			       "lazy pattern.\n");
712 713
		return -EINVAL;
	}
714

715
	if (pp->offset && !pp->function) {
M
Masami Hiramatsu 已提交
716
		semantic_error("Offset requires an entry function.\n");
717 718
		return -EINVAL;
	}
719

720
	if (pp->retprobe && !pp->function) {
M
Masami Hiramatsu 已提交
721
		semantic_error("Return probe requires an entry function.\n");
722 723
		return -EINVAL;
	}
724

725
	if ((pp->offset || pp->line || pp->lazy_line) && pp->retprobe) {
726
		semantic_error("Offset/Line/Lazy pattern can't be used with "
M
Masami Hiramatsu 已提交
727
			       "return probe.\n");
728 729
		return -EINVAL;
	}
730

731
	pr_debug("symbol:%s file:%s line:%d offset:%lu return:%d lazy:%s\n",
732 733
		 pp->function, pp->file, pp->line, pp->offset, pp->retprobe,
		 pp->lazy_line);
734
	return 0;
735 736
}

737
/* Parse perf-probe event argument */
738
static int parse_perf_probe_arg(char *str, struct perf_probe_arg *arg)
739
{
740
	char *tmp, *goodname;
741 742 743 744
	struct perf_probe_arg_field **fieldp;

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

745 746
	tmp = strchr(str, '=');
	if (tmp) {
747 748 749
		arg->name = strndup(str, tmp - str);
		if (arg->name == NULL)
			return -ENOMEM;
750
		pr_debug("name:%s ", arg->name);
751 752 753
		str = tmp + 1;
	}

754 755 756
	tmp = strchr(str, ':');
	if (tmp) {	/* Type setting */
		*tmp = '\0';
757 758 759
		arg->type = strdup(tmp + 1);
		if (arg->type == NULL)
			return -ENOMEM;
760 761 762
		pr_debug("type:%s ", arg->type);
	}

763
	tmp = strpbrk(str, "-.[");
764 765
	if (!is_c_varname(str) || !tmp) {
		/* A variable, register, symbol or special value */
766 767 768
		arg->var = strdup(str);
		if (arg->var == NULL)
			return -ENOMEM;
769
		pr_debug("%s\n", arg->var);
770
		return 0;
771 772
	}

773
	/* Structure fields or array element */
774 775 776
	arg->var = strndup(str, tmp - str);
	if (arg->var == NULL)
		return -ENOMEM;
777
	goodname = arg->var;
778
	pr_debug("%s, ", arg->var);
779 780 781
	fieldp = &arg->field;

	do {
782 783 784
		*fieldp = zalloc(sizeof(struct perf_probe_arg_field));
		if (*fieldp == NULL)
			return -ENOMEM;
785 786 787
		if (*tmp == '[') {	/* Array */
			str = tmp;
			(*fieldp)->index = strtol(str + 1, &tmp, 0);
788
			(*fieldp)->ref = true;
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
			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, "-.[");
810
		}
811
		if (tmp) {
812 813 814
			(*fieldp)->name = strndup(str, tmp - str);
			if ((*fieldp)->name == NULL)
				return -ENOMEM;
815 816
			if (*str != '[')
				goodname = (*fieldp)->name;
817 818 819 820
			pr_debug("%s(%d), ", (*fieldp)->name, (*fieldp)->ref);
			fieldp = &(*fieldp)->next;
		}
	} while (tmp);
821 822 823
	(*fieldp)->name = strdup(str);
	if ((*fieldp)->name == NULL)
		return -ENOMEM;
824 825
	if (*str != '[')
		goodname = (*fieldp)->name;
826
	pr_debug("%s(%d)\n", (*fieldp)->name, (*fieldp)->ref);
827

828
	/* If no name is specified, set the last field name (not array index)*/
829
	if (!arg->name) {
830
		arg->name = strdup(goodname);
831 832 833
		if (arg->name == NULL)
			return -ENOMEM;
	}
834
	return 0;
835 836
}

837
/* Parse perf-probe event command */
838
int parse_perf_probe_command(const char *cmd, struct perf_probe_event *pev)
839
{
840
	char **argv;
841
	int argc, i, ret = 0;
842

843
	argv = argv_split(cmd, &argc);
844 845 846 847 848 849 850 851 852
	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;
	}
853
	/* Parse probe point */
854 855 856
	ret = parse_perf_probe_point(argv[0], pev);
	if (ret < 0)
		goto out;
857

858
	/* Copy arguments and ensure return probe has no C argument */
859
	pev->nargs = argc - 1;
860 861 862 863 864
	pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
	if (pev->args == NULL) {
		ret = -ENOMEM;
		goto out;
	}
865 866 867 868
	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) {
869
			semantic_error("You can't specify local variable for"
870 871 872
				       " kretprobe.\n");
			ret = -EINVAL;
		}
873
	}
874
out:
875
	argv_free(argv);
876 877

	return ret;
878 879
}

880 881 882 883 884 885 886 887 888
/* 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++)
889
		if (is_c_varname(pev->args[i].var))
890 891 892 893 894
			return true;

	return false;
}

895 896 897
/* Parse probe_events event into struct probe_point */
static int parse_probe_trace_command(const char *cmd,
					struct probe_trace_event *tev)
898
{
899
	struct probe_trace_point *tp = &tev->point;
900 901 902 903 904
	char pr;
	char *p;
	int ret, i, argc;
	char **argv;

905
	pr_debug("Parsing probe_events: %s\n", cmd);
906
	argv = argv_split(cmd, &argc);
907 908 909 910 911 912 913 914 915
	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;
	}
916 917

	/* Scan event and group name. */
918
	ret = sscanf(argv[0], "%c:%a[^/ \t]/%a[^ \t]",
919 920
		     &pr, (float *)(void *)&tev->group,
		     (float *)(void *)&tev->event);
921 922 923 924 925
	if (ret != 3) {
		semantic_error("Failed to parse event name: %s\n", argv[0]);
		ret = -EINVAL;
		goto out;
	}
926
	pr_debug("Group:%s Event:%s probe:%c\n", tev->group, tev->event, pr);
927

928
	tp->retprobe = (pr == 'r');
929 930

	/* Scan function name and offset */
931 932
	ret = sscanf(argv[1], "%a[^+]+%lu", (float *)(void *)&tp->symbol,
		     &tp->offset);
933
	if (ret == 1)
934
		tp->offset = 0;
935

936
	tev->nargs = argc - 2;
937
	tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
938 939 940 941
	if (tev->args == NULL) {
		ret = -ENOMEM;
		goto out;
	}
942
	for (i = 0; i < tev->nargs; i++) {
943 944
		p = strchr(argv[i + 2], '=');
		if (p)	/* We don't need which register is assigned. */
945 946 947
			*p++ = '\0';
		else
			p = argv[i + 2];
948
		tev->args[i].name = strdup(argv[i + 2]);
949
		/* TODO: parse regs and offset */
950 951 952 953 954
		tev->args[i].value = strdup(p);
		if (tev->args[i].name == NULL || tev->args[i].value == NULL) {
			ret = -ENOMEM;
			goto out;
		}
955
	}
956 957
	ret = 0;
out:
958
	argv_free(argv);
959
	return ret;
960 961
}

962 963 964 965 966 967 968
/* 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;

969 970 971 972
	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);
973 974 975 976 977 978
	if (ret <= 0)
		goto error;
	tmp += ret;
	len -= ret;

	while (field) {
979 980 981 982 983
		if (field->name[0] == '[')
			ret = e_snprintf(tmp, len, "%s", field->name);
		else
			ret = e_snprintf(tmp, len, "%s%s",
					 field->ref ? "->" : ".", field->name);
984 985 986 987 988 989
		if (ret <= 0)
			goto error;
		tmp += ret;
		len -= ret;
		field = field->next;
	}
990 991 992 993 994 995 996 997 998

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

999 1000
	return tmp - buf;
error:
M
Masami Hiramatsu 已提交
1001
	pr_debug("Failed to synthesize perf probe argument: %s\n",
1002 1003
		 strerror(-ret));
	return ret;
1004 1005
}

1006 1007
/* Compose only probe point (not argument) */
static char *synthesize_perf_probe_point(struct perf_probe_point *pp)
1008
{
1009 1010 1011
	char *buf, *tmp;
	char offs[32] = "", line[32] = "", file[32] = "";
	int ret, len;
1012

1013 1014 1015 1016 1017
	buf = zalloc(MAX_CMDLEN);
	if (buf == NULL) {
		ret = -ENOMEM;
		goto error;
	}
1018
	if (pp->offset) {
1019
		ret = e_snprintf(offs, 32, "+%lu", pp->offset);
1020 1021 1022 1023
		if (ret <= 0)
			goto error;
	}
	if (pp->line) {
1024 1025 1026 1027 1028
		ret = e_snprintf(line, 32, ":%d", pp->line);
		if (ret <= 0)
			goto error;
	}
	if (pp->file) {
1029
		len = strlen(pp->file) - 31;
1030 1031 1032 1033
		if (len < 0)
			len = 0;
		tmp = strchr(pp->file + len, '/');
		if (!tmp)
1034
			tmp = pp->file + len;
1035
		ret = e_snprintf(file, 32, "@%s", tmp + 1);
1036 1037 1038 1039 1040
		if (ret <= 0)
			goto error;
	}

	if (pp->function)
1041 1042 1043
		ret = e_snprintf(buf, MAX_CMDLEN, "%s%s%s%s%s", pp->function,
				 offs, pp->retprobe ? "%return" : "", line,
				 file);
1044
	else
1045
		ret = e_snprintf(buf, MAX_CMDLEN, "%s%s", file, line);
1046 1047 1048 1049
	if (ret <= 0)
		goto error;

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

1058 1059
#if 0
char *synthesize_perf_probe_command(struct perf_probe_event *pev)
1060 1061 1062 1063
{
	char *buf;
	int i, len, ret;

1064 1065 1066
	buf = synthesize_perf_probe_point(&pev->point);
	if (!buf)
		return NULL;
1067

1068 1069
	len = strlen(buf);
	for (i = 0; i < pev->nargs; i++) {
1070
		ret = e_snprintf(&buf[len], MAX_CMDLEN - len, " %s",
1071 1072 1073 1074 1075
				 pev->args[i].name);
		if (ret <= 0) {
			free(buf);
			return NULL;
		}
1076 1077 1078
		len += ret;
	}

1079 1080 1081 1082
	return buf;
}
#endif

1083
static int __synthesize_probe_trace_arg_ref(struct probe_trace_arg_ref *ref,
1084 1085 1086 1087 1088
					     char **buf, size_t *buflen,
					     int depth)
{
	int ret;
	if (ref->next) {
1089
		depth = __synthesize_probe_trace_arg_ref(ref->next, buf,
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
							 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;
1104 1105 1106

}

1107
static int synthesize_probe_trace_arg(struct probe_trace_arg *arg,
1108
				       char *buf, size_t buflen)
1109
{
1110
	struct probe_trace_arg_ref *ref = arg->ref;
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
	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;

1124 1125 1126 1127
	/* Special case: @XXX */
	if (arg->value[0] == '@' && arg->ref)
			ref = ref->next;

1128
	/* Dereferencing arguments */
1129
	if (ref) {
1130
		depth = __synthesize_probe_trace_arg_ref(ref, &buf,
1131 1132 1133 1134 1135 1136
							  &buflen, 1);
		if (depth < 0)
			return depth;
	}

	/* Print argument value */
1137 1138 1139 1140 1141
	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);
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
	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;
	}
1155 1156 1157 1158 1159 1160 1161
	/* Print argument type */
	if (arg->type) {
		ret = e_snprintf(buf, buflen, ":%s", arg->type);
		if (ret <= 0)
			return ret;
		buf += ret;
	}
1162 1163 1164 1165

	return buf - tmp;
}

1166
char *synthesize_probe_trace_command(struct probe_trace_event *tev)
1167
{
1168
	struct probe_trace_point *tp = &tev->point;
1169 1170 1171
	char *buf;
	int i, len, ret;

1172 1173 1174 1175
	buf = zalloc(MAX_CMDLEN);
	if (buf == NULL)
		return NULL;

1176 1177 1178 1179 1180
	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)
1181 1182
		goto error;

1183
	for (i = 0; i < tev->nargs; i++) {
1184
		ret = synthesize_probe_trace_arg(&tev->args[i], buf + len,
1185
						  MAX_CMDLEN - len);
1186
		if (ret <= 0)
1187 1188 1189 1190
			goto error;
		len += ret;
	}

1191
	return buf;
1192
error:
1193 1194 1195
	free(buf);
	return NULL;
}
1196

1197
static int convert_to_perf_probe_event(struct probe_trace_event *tev,
1198
				       struct perf_probe_event *pev)
1199
{
1200
	char buf[64] = "";
1201
	int i, ret;
1202

1203
	/* Convert event/group name */
1204 1205 1206 1207
	pev->event = strdup(tev->event);
	pev->group = strdup(tev->group);
	if (pev->event == NULL || pev->group == NULL)
		return -ENOMEM;
1208

1209
	/* Convert trace_point to probe_point */
1210
	ret = kprobe_convert_to_perf_probe(&tev->point, &pev->point);
1211 1212
	if (ret < 0)
		return ret;
1213

1214 1215
	/* Convert trace_arg to probe_arg */
	pev->nargs = tev->nargs;
1216 1217 1218
	pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
	if (pev->args == NULL)
		return -ENOMEM;
1219
	for (i = 0; i < tev->nargs && ret >= 0; i++) {
1220
		if (tev->args[i].name)
1221
			pev->args[i].name = strdup(tev->args[i].name);
1222
		else {
1223
			ret = synthesize_probe_trace_arg(&tev->args[i],
1224
							  buf, 64);
1225
			pev->args[i].name = strdup(buf);
1226
		}
1227 1228 1229
		if (pev->args[i].name == NULL && ret >= 0)
			ret = -ENOMEM;
	}
1230 1231 1232 1233 1234

	if (ret < 0)
		clear_perf_probe_event(pev);

	return ret;
1235 1236 1237 1238 1239
}

void clear_perf_probe_event(struct perf_probe_event *pev)
{
	struct perf_probe_point *pp = &pev->point;
1240
	struct perf_probe_arg_field *field, *next;
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
	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);
1253
	for (i = 0; i < pev->nargs; i++) {
1254 1255
		if (pev->args[i].name)
			free(pev->args[i].name);
1256 1257
		if (pev->args[i].var)
			free(pev->args[i].var);
1258 1259
		if (pev->args[i].type)
			free(pev->args[i].type);
1260 1261 1262 1263 1264 1265 1266 1267 1268
		field = pev->args[i].field;
		while (field) {
			next = field->next;
			if (field->name)
				free(field->name);
			free(field);
			field = next;
		}
	}
1269 1270 1271 1272 1273
	if (pev->args)
		free(pev->args);
	memset(pev, 0, sizeof(*pev));
}

1274
static void clear_probe_trace_event(struct probe_trace_event *tev)
1275
{
1276
	struct probe_trace_arg_ref *ref, *next;
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
	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);
1290 1291
		if (tev->args[i].type)
			free(tev->args[i].type);
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
		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));
1302 1303
}

1304
static int open_kprobe_events(bool readwrite)
1305 1306
{
	char buf[PATH_MAX];
1307
	const char *__debugfs;
1308 1309
	int ret;

1310 1311 1312 1313 1314 1315 1316
	__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);
1317
	if (ret >= 0) {
1318
		pr_debug("Opening %s write=%d\n", buf, readwrite);
1319 1320 1321 1322 1323
		if (readwrite && !probe_event_dry_run)
			ret = open(buf, O_RDWR, O_APPEND);
		else
			ret = open(buf, O_RDONLY, 0);
	}
1324

1325 1326
	if (ret < 0) {
		if (errno == ENOENT)
1327 1328
			pr_warning("kprobe_events file does not exist - please"
				 " rebuild kernel with CONFIG_KPROBE_EVENT.\n");
1329
		else
1330 1331
			pr_warning("Failed to open kprobe_events file: %s\n",
				   strerror(errno));
1332 1333 1334 1335 1336
	}
	return ret;
}

/* Get raw string list of current kprobe_events */
1337
static struct strlist *get_probe_trace_command_rawlist(int fd)
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
{
	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);
1357 1358 1359 1360 1361
		if (ret < 0) {
			pr_debug("strlist__add failed: %s\n", strerror(-ret));
			strlist__delete(sl);
			return NULL;
		}
1362 1363 1364 1365 1366 1367
	}
	fclose(fp);

	return sl;
}

1368
/* Show an event */
1369
static int show_perf_probe_event(struct perf_probe_event *pev)
1370
{
1371
	int i, ret;
1372
	char buf[128];
1373
	char *place;
1374

1375 1376
	/* Synthesize only event probe point */
	place = synthesize_perf_probe_point(&pev->point);
1377 1378
	if (!place)
		return -EINVAL;
1379 1380

	ret = e_snprintf(buf, 128, "%s:%s", pev->group, pev->event);
1381
	if (ret < 0)
1382 1383
		return ret;

1384
	printf("  %-20s (on %s", buf, place);
1385

1386
	if (pev->nargs > 0) {
1387
		printf(" with");
1388
		for (i = 0; i < pev->nargs; i++) {
1389 1390 1391 1392
			ret = synthesize_perf_probe_arg(&pev->args[i],
							buf, 128);
			if (ret < 0)
				break;
1393 1394
			printf(" %s", buf);
		}
1395 1396
	}
	printf(")\n");
1397
	free(place);
1398
	return ret;
1399 1400
}

1401
/* List up current perf-probe events */
1402
int show_perf_probe_events(void)
1403
{
1404
	int fd, ret;
1405
	struct probe_trace_event tev;
1406
	struct perf_probe_event pev;
1407 1408 1409
	struct strlist *rawlist;
	struct str_node *ent;

1410
	setup_pager();
1411 1412 1413
	ret = init_vmlinux();
	if (ret < 0)
		return ret;
1414 1415 1416

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

1418
	fd = open_kprobe_events(false);
1419 1420 1421
	if (fd < 0)
		return fd;

1422
	rawlist = get_probe_trace_command_rawlist(fd);
1423
	close(fd);
1424 1425
	if (!rawlist)
		return -ENOENT;
1426

1427
	strlist__for_each(ent, rawlist) {
1428
		ret = parse_probe_trace_command(ent->s, &tev);
1429 1430 1431 1432 1433
		if (ret >= 0) {
			ret = convert_to_perf_probe_event(&tev, &pev);
			if (ret >= 0)
				ret = show_perf_probe_event(&pev);
		}
1434
		clear_perf_probe_event(&pev);
1435
		clear_probe_trace_event(&tev);
1436 1437
		if (ret < 0)
			break;
1438 1439
	}
	strlist__delete(rawlist);
1440 1441

	return ret;
1442 1443
}

1444
/* Get current perf-probe event names */
1445
static struct strlist *get_probe_trace_event_names(int fd, bool include_group)
1446
{
1447
	char buf[128];
1448 1449
	struct strlist *sl, *rawlist;
	struct str_node *ent;
1450
	struct probe_trace_event tev;
1451
	int ret = 0;
1452

1453
	memset(&tev, 0, sizeof(tev));
1454
	rawlist = get_probe_trace_command_rawlist(fd);
1455
	sl = strlist__new(true, NULL);
1456
	strlist__for_each(ent, rawlist) {
1457
		ret = parse_probe_trace_command(ent->s, &tev);
1458 1459
		if (ret < 0)
			break;
1460
		if (include_group) {
1461 1462 1463 1464
			ret = e_snprintf(buf, 128, "%s:%s", tev.group,
					tev.event);
			if (ret >= 0)
				ret = strlist__add(sl, buf);
1465
		} else
1466
			ret = strlist__add(sl, tev.event);
1467
		clear_probe_trace_event(&tev);
1468 1469
		if (ret < 0)
			break;
1470 1471 1472
	}
	strlist__delete(rawlist);

1473 1474 1475 1476
	if (ret < 0) {
		strlist__delete(sl);
		return NULL;
	}
1477 1478 1479
	return sl;
}

1480
static int write_probe_trace_event(int fd, struct probe_trace_event *tev)
1481
{
1482
	int ret = 0;
1483
	char *buf = synthesize_probe_trace_command(tev);
1484

1485
	if (!buf) {
1486
		pr_debug("Failed to synthesize probe trace event.\n");
1487 1488 1489
		return -EINVAL;
	}

1490
	pr_debug("Writing event: %s\n", buf);
1491 1492 1493
	if (!probe_event_dry_run) {
		ret = write(fd, buf, strlen(buf));
		if (ret <= 0)
1494 1495
			pr_warning("Failed to write event: %s\n",
				   strerror(errno));
1496
	}
1497
	free(buf);
1498
	return ret;
1499 1500
}

1501 1502
static int get_new_event_name(char *buf, size_t len, const char *base,
			      struct strlist *namelist, bool allow_suffix)
1503 1504
{
	int i, ret;
1505 1506 1507

	/* Try no suffix */
	ret = e_snprintf(buf, len, "%s", base);
1508 1509 1510 1511
	if (ret < 0) {
		pr_debug("snprintf() failed: %s\n", strerror(-ret));
		return ret;
	}
1512
	if (!strlist__has_entry(namelist, buf))
1513
		return 0;
1514

1515 1516 1517
	if (!allow_suffix) {
		pr_warning("Error: event \"%s\" already exists. "
			   "(Use -f to force duplicates.)\n", base);
1518
		return -EEXIST;
1519 1520
	}

1521 1522
	/* Try to add suffix */
	for (i = 1; i < MAX_EVENT_INDEX; i++) {
1523
		ret = e_snprintf(buf, len, "%s_%d", base, i);
1524 1525 1526 1527
		if (ret < 0) {
			pr_debug("snprintf() failed: %s\n", strerror(-ret));
			return ret;
		}
1528 1529 1530
		if (!strlist__has_entry(namelist, buf))
			break;
	}
1531 1532 1533 1534 1535 1536
	if (i == MAX_EVENT_INDEX) {
		pr_warning("Too many events are on the same function.\n");
		ret = -ERANGE;
	}

	return ret;
1537 1538
}

1539 1540
static int __add_probe_trace_events(struct perf_probe_event *pev,
				     struct probe_trace_event *tevs,
1541
				     int ntevs, bool allow_suffix)
1542
{
1543
	int i, fd, ret;
1544
	struct probe_trace_event *tev = NULL;
1545 1546
	char buf[64];
	const char *event, *group;
1547
	struct strlist *namelist;
1548

1549
	fd = open_kprobe_events(true);
1550 1551
	if (fd < 0)
		return fd;
1552
	/* Get current event names */
1553
	namelist = get_probe_trace_event_names(fd, false);
1554 1555 1556 1557
	if (!namelist) {
		pr_debug("Failed to get current event list.\n");
		return -EIO;
	}
1558

1559
	ret = 0;
1560
	printf("Add new event%s\n", (ntevs > 1) ? "s:" : ":");
1561
	for (i = 0; i < ntevs; i++) {
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
		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 */
1576 1577 1578 1579
		ret = get_new_event_name(buf, 64, event,
					 namelist, allow_suffix);
		if (ret < 0)
			break;
1580 1581
		event = buf;

1582 1583 1584 1585 1586 1587
		tev->event = strdup(event);
		tev->group = strdup(group);
		if (tev->event == NULL || tev->group == NULL) {
			ret = -ENOMEM;
			break;
		}
1588
		ret = write_probe_trace_event(fd, tev);
1589 1590
		if (ret < 0)
			break;
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
		/* 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;
1611
	}
1612 1613 1614 1615 1616 1617 1618

	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);
	}
1619

1620
	strlist__delete(namelist);
1621
	close(fd);
1622
	return ret;
1623
}
1624

1625 1626
static int convert_to_probe_trace_events(struct perf_probe_event *pev,
					  struct probe_trace_event **tevs,
1627
					  int max_tevs, const char *module)
1628 1629
{
	struct symbol *sym;
1630
	int ret = 0, i;
1631
	struct probe_trace_event *tev;
1632

1633
	/* Convert perf_probe_event with debuginfo */
1634
	ret = try_to_find_probe_trace_events(pev, tevs, max_tevs, module);
1635 1636
	if (ret != 0)
		return ret;
1637

1638
	/* Allocate trace event buffer */
1639
	tev = *tevs = zalloc(sizeof(struct probe_trace_event));
1640 1641
	if (tev == NULL)
		return -ENOMEM;
1642 1643

	/* Copy parameters */
1644 1645 1646 1647 1648
	tev->point.symbol = strdup(pev->point.function);
	if (tev->point.symbol == NULL) {
		ret = -ENOMEM;
		goto error;
	}
1649
	tev->point.offset = pev->point.offset;
1650
	tev->point.retprobe = pev->point.retprobe;
1651 1652
	tev->nargs = pev->nargs;
	if (tev->nargs) {
1653
		tev->args = zalloc(sizeof(struct probe_trace_arg)
1654 1655
				   * tev->nargs);
		if (tev->args == NULL) {
1656 1657
			ret = -ENOMEM;
			goto error;
1658
		}
1659
		for (i = 0; i < tev->nargs; i++) {
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
			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;
				}
			}
1679
		}
1680 1681 1682
	}

	/* Currently just checking function name from symbol map */
1683
	sym = __find_kernel_function_by_name(tev->point.symbol, NULL);
1684 1685 1686
	if (!sym) {
		pr_warning("Kernel symbol \'%s\' not found.\n",
			   tev->point.symbol);
1687 1688 1689
		ret = -ENOENT;
		goto error;
	}
1690

1691 1692
	return 1;
error:
1693
	clear_probe_trace_event(tev);
1694 1695
	free(tev);
	*tevs = NULL;
1696
	return ret;
1697 1698 1699 1700
}

struct __event_package {
	struct perf_probe_event		*pev;
1701
	struct probe_trace_event	*tevs;
1702 1703 1704
	int				ntevs;
};

1705
int add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
1706
			  int max_tevs, const char *module, bool force_add)
1707
{
1708
	int i, j, ret;
1709 1710
	struct __event_package *pkgs;

1711 1712 1713
	pkgs = zalloc(sizeof(struct __event_package) * npevs);
	if (pkgs == NULL)
		return -ENOMEM;
1714 1715

	/* Init vmlinux path */
1716
	ret = init_vmlinux();
1717 1718
	if (ret < 0) {
		free(pkgs);
1719
		return ret;
1720
	}
1721 1722 1723 1724 1725

	/* Loop 1: convert all events */
	for (i = 0; i < npevs; i++) {
		pkgs[i].pev = &pevs[i];
		/* Convert with or without debuginfo */
1726
		ret  = convert_to_probe_trace_events(pkgs[i].pev,
1727 1728 1729
						     &pkgs[i].tevs,
						     max_tevs,
						     module);
1730 1731 1732
		if (ret < 0)
			goto end;
		pkgs[i].ntevs = ret;
1733 1734
	}

1735
	/* Loop 2: add all events */
1736
	for (i = 0; i < npevs && ret >= 0; i++)
1737
		ret = __add_probe_trace_events(pkgs[i].pev, pkgs[i].tevs,
1738 1739
						pkgs[i].ntevs, force_add);
end:
1740 1741
	/* Loop 3: cleanup and free trace events  */
	for (i = 0; i < npevs; i++) {
1742
		for (j = 0; j < pkgs[i].ntevs; j++)
1743
			clear_probe_trace_event(&pkgs[i].tevs[j]);
1744 1745 1746
		free(pkgs[i].tevs);
	}
	free(pkgs);
1747 1748

	return ret;
1749 1750
}

1751
static int __del_trace_probe_event(int fd, struct str_node *ent)
1752 1753 1754
{
	char *p;
	char buf[128];
1755
	int ret;
1756

1757
	/* Convert from perf-probe event to trace-probe event */
1758 1759 1760 1761
	ret = e_snprintf(buf, 128, "-:%s", ent->s);
	if (ret < 0)
		goto error;

1762
	p = strchr(buf + 2, ':');
1763 1764 1765 1766 1767 1768
	if (!p) {
		pr_debug("Internal error: %s should have ':' but not.\n",
			 ent->s);
		ret = -ENOTSUP;
		goto error;
	}
1769 1770
	*p = '/';

1771 1772
	pr_debug("Writing event: %s\n", buf);
	ret = write(fd, buf, strlen(buf));
1773 1774 1775
	if (ret < 0)
		goto error;

1776
	printf("Remove event: %s\n", ent->s);
1777 1778 1779 1780
	return 0;
error:
	pr_warning("Failed to delete event: %s\n", strerror(-ret));
	return ret;
1781 1782
}

1783
static int del_trace_probe_event(int fd, const char *group,
1784
				  const char *event, struct strlist *namelist)
1785 1786
{
	char buf[128];
1787
	struct str_node *ent, *n;
1788
	int found = 0, ret = 0;
1789

1790 1791
	ret = e_snprintf(buf, 128, "%s:%s", group, event);
	if (ret < 0) {
M
Masami Hiramatsu 已提交
1792
		pr_err("Failed to copy event.\n");
1793 1794
		return ret;
	}
1795

1796 1797 1798 1799
	if (strpbrk(buf, "*?")) { /* Glob-exp */
		strlist__for_each_safe(ent, n, namelist)
			if (strglobmatch(ent->s, buf)) {
				found++;
1800
				ret = __del_trace_probe_event(fd, ent);
1801 1802
				if (ret < 0)
					break;
1803 1804 1805 1806 1807 1808
				strlist__remove(namelist, ent);
			}
	} else {
		ent = strlist__find(namelist, buf);
		if (ent) {
			found++;
1809
			ret = __del_trace_probe_event(fd, ent);
1810 1811
			if (ret >= 0)
				strlist__remove(namelist, ent);
1812 1813
		}
	}
1814 1815 1816 1817
	if (found == 0 && ret >= 0)
		pr_info("Info: Event \"%s\" does not exist.\n", buf);

	return ret;
1818 1819
}

1820
int del_perf_probe_events(struct strlist *dellist)
1821
{
1822
	int fd, ret = 0;
1823 1824 1825 1826 1827
	const char *group, *event;
	char *p, *str;
	struct str_node *ent;
	struct strlist *namelist;

1828
	fd = open_kprobe_events(true);
1829 1830 1831
	if (fd < 0)
		return fd;

1832
	/* Get current event names */
1833
	namelist = get_probe_trace_event_names(fd, true);
1834 1835
	if (namelist == NULL)
		return -EINVAL;
1836

1837
	strlist__for_each(ent, dellist) {
1838 1839 1840 1841 1842
		str = strdup(ent->s);
		if (str == NULL) {
			ret = -ENOMEM;
			break;
		}
1843
		pr_debug("Parsing: %s\n", str);
1844 1845 1846 1847 1848 1849
		p = strchr(str, ':');
		if (p) {
			group = str;
			*p = '\0';
			event = p + 1;
		} else {
1850
			group = "*";
1851 1852
			event = str;
		}
1853
		pr_debug("Group: %s, Event: %s\n", group, event);
1854
		ret = del_trace_probe_event(fd, group, event, namelist);
1855
		free(str);
1856 1857
		if (ret < 0)
			break;
1858 1859 1860
	}
	strlist__delete(namelist);
	close(fd);
1861 1862

	return ret;
1863 1864
}