probe-event.c 41.0 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 98 99 100
	if (machine__create_kernel_maps(&machine) < 0) {
		pr_debug("machine__create_kernel_maps ");
		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 143 144
	const char *path = kernel_get_module_path(module);
	if (!path) {
		pr_err("Failed to find path of %s module", module ?: "kernel");
		return -ENOENT;
145
	}
146 147
	pr_debug("Try to open %s\n", path);
	return open(path, O_RDONLY);
148
}
149

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

162
	sym = __find_kernel_function_by_name(tp->symbol, &map);
163
	if (sym) {
164 165 166 167
		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);
168 169
	}
	if (ret <= 0) {
170 171
		pr_debug("Failed to find corresponding probes from "
			 "debuginfo. Use kprobe event information.\n");
172 173 174
		pp->function = strdup(tp->symbol);
		if (pp->function == NULL)
			return -ENOMEM;
175 176 177
		pp->offset = tp->offset;
	}
	pp->retprobe = tp->retprobe;
178 179

	return 0;
180 181 182
}

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

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

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

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

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

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

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

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

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

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

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

286 287 288
#define LINEBUF_SIZE 256
#define NR_ADDITIONAL_LINES 2

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

	if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
		goto error;
	if (!skip) {
		if (show_num)
298
			fprintf(stdout, "%7d  %s", l, buf);
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
		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);
		}
	}
314 315

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

	return -1;
323 324 325 326 327 328
}

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

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

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

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

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

367 368 369 370 371 372 373 374 375
	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");
376 377 378 379 380
	if (fp == NULL) {
		pr_warning("Failed to open %s: %s\n", lr->path,
			   strerror(errno));
		return -errno;
	}
381
	/* Skip to starting line number */
382 383 384 385
	while (l < lr->start && ret >= 0)
		ret = show_one_line(fp, l++, true, false);
	if (ret < 0)
		goto end;
386 387

	list_for_each_entry(ln, &lr->line_list, list) {
388 389 390 391 392 393 394 395
		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;
396 397 398 399
	}

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

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

420
	ret = find_available_vars_at(fd, pev, &vls, max_vls, externs);
421 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
	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,
450
			int max_vls, const char *module, bool externs)
451 452 453 454 455 456 457
{
	int i, fd, ret = 0;

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

458
	fd = open_vmlinux(module);
459 460 461 462 463 464 465 466
	if (fd < 0) {
		pr_warning("Failed to open debuginfo file.\n");
		return fd;
	}

	setup_pager();

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

	close(fd);
	return ret;
}

473 474
#else	/* !DWARF_SUPPORT */

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

	return 0;
492 493
}

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

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

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

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

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

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

	return 0;
570 571
}

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

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

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

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

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

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

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

	/* Exclusion check */
692
	if (pp->lazy_line && pp->line) {
693
		semantic_error("Lazy pattern can't be used with line number.");
694 695
		return -EINVAL;
	}
696

697
	if (pp->lazy_line && pp->offset) {
698
		semantic_error("Lazy pattern can't be used with offset.");
699 700
		return -EINVAL;
	}
701

702
	if (pp->line && pp->offset) {
703
		semantic_error("Offset can't be used with line number.");
704 705
		return -EINVAL;
	}
706

707
	if (!pp->line && !pp->lazy_line && pp->file && !pp->function) {
708 709
		semantic_error("File always requires line number or "
			       "lazy pattern.");
710 711
		return -EINVAL;
	}
712

713
	if (pp->offset && !pp->function) {
714
		semantic_error("Offset requires an entry function.");
715 716
		return -EINVAL;
	}
717

718
	if (pp->retprobe && !pp->function) {
719
		semantic_error("Return probe requires an entry function.");
720 721
		return -EINVAL;
	}
722

723
	if ((pp->offset || pp->line || pp->lazy_line) && pp->retprobe) {
724 725
		semantic_error("Offset/Line/Lazy pattern can't be used with "
			       "return probe.");
726 727
		return -EINVAL;
	}
728

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

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

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

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

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

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

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

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

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

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

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

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

	return ret;
876 877
}

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

	return false;
}

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

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

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

926
	tp->retprobe = (pr == 'r');
927 928

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

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

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

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

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

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

997 998
	return tmp - buf;
error:
999 1000 1001
	pr_debug("Failed to synthesize perf probe argument: %s",
		 strerror(-ret));
	return ret;
1002 1003
}

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

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

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

	return buf;
1048
error:
1049 1050
	pr_debug("Failed to synthesize perf probe point: %s",
		 strerror(-ret));
1051 1052
	if (buf)
		free(buf);
1053
	return NULL;
1054 1055
}

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

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

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

1077 1078 1079 1080
	return buf;
}
#endif

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

}

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

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

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

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

	return buf - tmp;
}

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

1170 1171 1172 1173
	buf = zalloc(MAX_CMDLEN);
	if (buf == NULL)
		return NULL;

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

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

1189
	return buf;
1190
error:
1191 1192 1193
	free(buf);
	return NULL;
}
1194

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

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

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

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

	if (ret < 0)
		clear_perf_probe_event(pev);

	return ret;
1233 1234 1235 1236 1237
}

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

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

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

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

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

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

	return sl;
}

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

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

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

1382
	printf("  %-20s (on %s", buf, place);
1383

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

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

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

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

1416
	fd = open_kprobe_events(false);
1417 1418 1419
	if (fd < 0)
		return fd;

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

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

	return ret;
1440 1441
}

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

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

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

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

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

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

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

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

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

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

	return ret;
1535 1536
}

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

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

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

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

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

1618
	strlist__delete(namelist);
1619
	close(fd);
1620
	return ret;
1621
}
1622

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

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

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

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

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

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

struct __event_package {
	struct perf_probe_event		*pev;
1699
	struct probe_trace_event	*tevs;
1700 1701 1702
	int				ntevs;
};

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

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

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

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

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

	return ret;
1747 1748
}

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

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

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

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

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

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

1788 1789 1790 1791 1792
	ret = e_snprintf(buf, 128, "%s:%s", group, event);
	if (ret < 0) {
		pr_err("Failed to copy event.");
		return ret;
	}
1793

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

	return ret;
1816 1817
}

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

1826
	fd = open_kprobe_events(true);
1827 1828 1829
	if (fd < 0)
		return fd;

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

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

	return ret;
1861 1862
}