File Index
Files and directories
Sign in
FILE

probe-event.c

File preview with syntax highlighting.

linux-6.19.14/tools/perf/util/probe-event.c C
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2/*
   3 * probe-event.c : perf-probe definition to probe_events format converter
   4 *
   5 * Written by Masami Hiramatsu <mhiramat@redhat.com>
   6 */
   7
   8#include <inttypes.h>
   9#include <sys/utsname.h>
  10#include <sys/types.h>
  11#include <sys/stat.h>
  12#include <fcntl.h>
  13#include <errno.h>
  14#include <libgen.h>
  15#include <stdio.h>
  16#include <unistd.h>
  17#include <stdlib.h>
  18#include <string.h>
  19#include <stdarg.h>
  20#include <limits.h>
  21#include <elf.h>
  22
  23#include "build-id.h"
  24#include "event.h"
  25#include "namespaces.h"
  26#include "strlist.h"
  27#include "strfilter.h"
  28#include "debug.h"
  29#include "dso.h"
  30#include "color.h"
  31#include "map.h"
  32#include "maps.h"
  33#include "mutex.h"
  34#include "symbol.h"
  35#include <api/fs/fs.h>
  36#include "trace-event.h"	/* For __maybe_unused */
  37#include "probe-event.h"
  38#include "probe-finder.h"
  39#include "probe-file.h"
  40#include "session.h"
  41#include "string2.h"
  42#include "strbuf.h"
  43#include "parse-events.h"
  44
  45#include <subcmd/pager.h>
  46#include <linux/ctype.h>
  47#include <linux/zalloc.h>
  48
  49#ifdef HAVE_DEBUGINFOD_SUPPORT
  50#include <elfutils/debuginfod.h>
  51#endif
  52
  53#define PERFPROBE_GROUP "probe"
  54
  55/* Defined in kernel/trace/trace.h */
  56#define MAX_EVENT_NAME_LEN	64
  57
  58bool probe_event_dry_run;	/* Dry run flag */
  59struct probe_conf probe_conf = { .magic_num = DEFAULT_PROBE_MAGIC_NUM };
  60
  61static char *synthesize_perf_probe_point(struct perf_probe_point *pp);
  62
  63#define semantic_error(msg ...) pr_err("Semantic error :" msg)
  64
  65int e_snprintf(char *str, size_t size, const char *format, ...)
  66{
  67	int ret;
  68	va_list ap;
  69	va_start(ap, format);
  70	ret = vsnprintf(str, size, format, ap);
  71	va_end(ap);
  72	if (ret >= (int)size)
  73		ret = -E2BIG;
  74	return ret;
  75}
  76
  77static struct machine *host_machine;
  78static struct perf_env host_env;
  79
  80/* Initialize symbol maps and path of vmlinux/modules */
  81int init_probe_symbol_maps(bool user_only)
  82{
  83	int ret;
  84
  85	perf_env__init(&host_env);
  86	symbol_conf.allow_aliases = true;
  87	ret = symbol__init(NULL);
  88	if (ret < 0) {
  89		pr_debug("Failed to init symbol map.\n");
  90		goto out;
  91	}
  92
  93	if (host_machine || user_only)	/* already initialized */
  94		return 0;
  95
  96	if (symbol_conf.vmlinux_name)
  97		pr_debug("Use vmlinux: %s\n", symbol_conf.vmlinux_name);
  98
  99	host_machine = machine__new_host(&host_env);
 100	if (!host_machine) {
 101		pr_debug("machine__new_host() failed.\n");
 102		symbol__exit();
 103		ret = -1;
 104	}
 105out:
 106	if (ret < 0)
 107		pr_warning("Failed to init vmlinux path.\n");
 108	return ret;
 109}
 110
 111void exit_probe_symbol_maps(void)
 112{
 113	machine__delete(host_machine);
 114	host_machine = NULL;
 115	symbol__exit();
 116	perf_env__exit(&host_env);
 117}
 118
 119static struct ref_reloc_sym *kernel_get_ref_reloc_sym(struct map **pmap)
 120{
 121	struct kmap *kmap;
 122	struct map *map = machine__kernel_map(host_machine);
 123
 124	if (map__load(map) < 0)
 125		return NULL;
 126
 127	kmap = map__kmap(map);
 128	if (!kmap)
 129		return NULL;
 130
 131	if (pmap)
 132		*pmap = map;
 133
 134	return kmap->ref_reloc_sym;
 135}
 136
 137static int kernel_get_symbol_address_by_name(const char *name, u64 *addr,
 138					     bool reloc, bool reladdr)
 139{
 140	struct ref_reloc_sym *reloc_sym;
 141	struct symbol *sym;
 142	struct map *map;
 143
 144	/* ref_reloc_sym is just a label. Need a special fix*/
 145	reloc_sym = kernel_get_ref_reloc_sym(&map);
 146	if (reloc_sym && strcmp(name, reloc_sym->name) == 0)
 147		*addr = (!map__reloc(map) || reloc) ? reloc_sym->addr :
 148			reloc_sym->unrelocated_addr;
 149	else {
 150		sym = machine__find_kernel_symbol_by_name(host_machine, name, &map);
 151		if (!sym)
 152			return -ENOENT;
 153		*addr = map__unmap_ip(map, sym->start) -
 154			((reloc) ? 0 : map__reloc(map)) -
 155			((reladdr) ? map__start(map) : 0);
 156	}
 157	return 0;
 158}
 159
 160struct kernel_get_module_map_cb_args {
 161	const char *module;
 162	struct map *result;
 163};
 164
 165static int kernel_get_module_map_cb(struct map *map, void *data)
 166{
 167	struct kernel_get_module_map_cb_args *args = data;
 168	struct dso *dso = map__dso(map);
 169	const char *short_name = dso__short_name(dso);
 170	u16 short_name_len =  dso__short_name_len(dso);
 171
 172	if (strncmp(short_name + 1, args->module, short_name_len - 2) == 0 &&
 173	    args->module[short_name_len - 2] == '\0') {
 174		args->result = map__get(map);
 175		return 1;
 176	}
 177	return 0;
 178}
 179
 180static struct map *kernel_get_module_map(const char *module)
 181{
 182	struct kernel_get_module_map_cb_args args = {
 183		.module = module,
 184		.result = NULL,
 185	};
 186
 187	/* A file path -- this is an offline module */
 188	if (module && strchr(module, '/'))
 189		return dso__new_map(module);
 190
 191	if (!module) {
 192		struct map *map = machine__kernel_map(host_machine);
 193
 194		return map__get(map);
 195	}
 196
 197	maps__for_each_map(machine__kernel_maps(host_machine), kernel_get_module_map_cb, &args);
 198
 199	return args.result;
 200}
 201
 202struct map *get_target_map(const char *target, struct nsinfo *nsi, bool user)
 203{
 204	/* Init maps of given executable or kernel */
 205	if (user) {
 206		struct map *map;
 207		struct dso *dso;
 208
 209		map = dso__new_map(target);
 210		dso = map ? map__dso(map) : NULL;
 211		if (dso) {
 212			mutex_lock(dso__lock(dso));
 213			dso__set_nsinfo(dso, nsinfo__get(nsi));
 214			mutex_unlock(dso__lock(dso));
 215		}
 216		return map;
 217	} else {
 218		return kernel_get_module_map(target);
 219	}
 220}
 221
 222static int convert_exec_to_group(const char *exec, char **result)
 223{
 224	char *ptr1, *ptr2, *exec_copy;
 225	char buf[64];
 226	int ret;
 227
 228	exec_copy = strdup(exec);
 229	if (!exec_copy)
 230		return -ENOMEM;
 231
 232	ptr1 = basename(exec_copy);
 233	if (!ptr1) {
 234		ret = -EINVAL;
 235		goto out;
 236	}
 237
 238	for (ptr2 = ptr1; *ptr2 != '\0'; ptr2++) {
 239		if (!isalnum(*ptr2) && *ptr2 != '_') {
 240			*ptr2 = '\0';
 241			break;
 242		}
 243	}
 244
 245	ret = e_snprintf(buf, sizeof(buf), "%s_%s", PERFPROBE_GROUP, ptr1);
 246	if (ret < 0)
 247		goto out;
 248
 249	*result = strdup(buf);
 250	ret = *result ? 0 : -ENOMEM;
 251
 252out:
 253	free(exec_copy);
 254	return ret;
 255}
 256
 257static void clear_perf_probe_point(struct perf_probe_point *pp)
 258{
 259	zfree(&pp->file);
 260	zfree(&pp->function);
 261	zfree(&pp->lazy_line);
 262}
 263
 264static void clear_probe_trace_events(struct probe_trace_event *tevs, int ntevs)
 265{
 266	int i;
 267
 268	for (i = 0; i < ntevs; i++)
 269		clear_probe_trace_event(tevs + i);
 270}
 271
 272static bool kprobe_blacklist__listed(u64 address);
 273static bool kprobe_warn_out_range(const char *symbol, u64 address)
 274{
 275	struct map *map;
 276	bool ret = false;
 277
 278	map = kernel_get_module_map(NULL);
 279	if (map) {
 280		ret = address <= map__start(map) || map__end(map) < address;
 281		if (ret)
 282			pr_warning("%s is out of .text, skip it.\n", symbol);
 283		map__put(map);
 284	}
 285	if (!ret && kprobe_blacklist__listed(address)) {
 286		pr_warning("%s is blacklisted function, skip it.\n", symbol);
 287		ret = true;
 288	}
 289
 290	return ret;
 291}
 292
 293/*
 294 * @module can be module name of module file path. In case of path,
 295 * inspect elf and find out what is actual module name.
 296 * Caller has to free mod_name after using it.
 297 */
 298static char *find_module_name(const char *module)
 299{
 300	int fd;
 301	Elf *elf;
 302	GElf_Ehdr ehdr;
 303	GElf_Shdr shdr;
 304	Elf_Data *data;
 305	Elf_Scn *sec;
 306	char *mod_name = NULL;
 307	int name_offset;
 308
 309	fd = open(module, O_RDONLY);
 310	if (fd < 0)
 311		return NULL;
 312
 313	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
 314	if (elf == NULL)
 315		goto elf_err;
 316
 317	if (gelf_getehdr(elf, &ehdr) == NULL)
 318		goto ret_err;
 319
 320	sec = elf_section_by_name(elf, &ehdr, &shdr,
 321			".gnu.linkonce.this_module", NULL);
 322	if (!sec)
 323		goto ret_err;
 324
 325	data = elf_getdata(sec, NULL);
 326	if (!data || !data->d_buf)
 327		goto ret_err;
 328
 329	/*
 330	 * NOTE:
 331	 * '.gnu.linkonce.this_module' section of kernel module elf directly
 332	 * maps to 'struct module' from linux/module.h. This section contains
 333	 * actual module name which will be used by kernel after loading it.
 334	 * But, we cannot use 'struct module' here since linux/module.h is not
 335	 * exposed to user-space. Offset of 'name' has remained same from long
 336	 * time, so hardcoding it here.
 337	 */
 338	if (ehdr.e_ident[EI_CLASS] == ELFCLASS32)
 339		name_offset = 12;
 340	else	/* expect ELFCLASS64 by default */
 341		name_offset = 24;
 342
 343	mod_name = strdup((char *)data->d_buf + name_offset);
 344
 345ret_err:
 346	elf_end(elf);
 347elf_err:
 348	close(fd);
 349	return mod_name;
 350}
 351
 352#ifdef HAVE_LIBDW_SUPPORT
 353
 354static int kernel_get_module_dso(const char *module, struct dso **pdso)
 355{
 356	struct dso *dso;
 357	struct map *map;
 358	const char *vmlinux_name;
 359	int ret = 0;
 360
 361	if (module) {
 362		char module_name[128];
 363
 364		snprintf(module_name, sizeof(module_name), "[%s]", module);
 365		map = maps__find_by_name(machine__kernel_maps(host_machine), module_name);
 366		if (map) {
 367			dso = map__dso(map);
 368			map__put(map);
 369			goto found;
 370		}
 371		pr_debug("Failed to find module %s.\n", module);
 372		return -ENOENT;
 373	}
 374
 375	map = machine__kernel_map(host_machine);
 376	dso = map__dso(map);
 377	if (!dso__has_build_id(dso))
 378		dso__read_running_kernel_build_id(dso, host_machine);
 379
 380	vmlinux_name = symbol_conf.vmlinux_name;
 381	*dso__load_errno(dso) = 0;
 382	if (vmlinux_name)
 383		ret = dso__load_vmlinux(dso, map, vmlinux_name, false);
 384	else
 385		ret = dso__load_vmlinux_path(dso, map);
 386found:
 387	*pdso = dso;
 388	return ret;
 389}
 390
 391/*
 392 * Some binaries like glibc have special symbols which are on the symbol
 393 * table, but not in the debuginfo. If we can find the address of the
 394 * symbol from map, we can translate the address back to the probe point.
 395 */
 396static int find_alternative_probe_point(struct debuginfo *dinfo,
 397					struct perf_probe_point *pp,
 398					struct perf_probe_point *result,
 399					const char *target, struct nsinfo *nsi,
 400					bool uprobes)
 401{
 402	struct map *map = NULL;
 403	struct symbol *sym;
 404	u64 address = 0;
 405	int ret = -ENOENT;
 406	size_t idx;
 407
 408	/* This can work only for function-name based one */
 409	if (!pp->function || pp->file)
 410		return -ENOTSUP;
 411
 412	map = get_target_map(target, nsi, uprobes);
 413	if (!map)
 414		return -EINVAL;
 415
 416	/* Find the address of given function */
 417	map__for_each_symbol_by_name(map, pp->function, sym, idx) {
 418		if (uprobes) {
 419			address = sym->start;
 420			if (sym->type == STT_GNU_IFUNC)
 421				pr_warning("Warning: The probe function (%s) is a GNU indirect function.\n"
 422					   "Consider identifying the final function used at run time and set the probe directly on that.\n",
 423					   pp->function);
 424		} else
 425			address = map__unmap_ip(map, sym->start) - map__reloc(map);
 426		break;
 427	}
 428	if (!address) {
 429		ret = -ENOENT;
 430		goto out;
 431	}
 432	pr_debug("Symbol %s address found : %" PRIx64 "\n",
 433			pp->function, address);
 434
 435	ret = debuginfo__find_probe_point(dinfo, address, result);
 436	if (ret <= 0)
 437		ret = (!ret) ? -ENOENT : ret;
 438	else {
 439		result->offset += pp->offset;
 440		result->line += pp->line;
 441		result->retprobe = pp->retprobe;
 442		ret = 0;
 443	}
 444
 445out:
 446	map__put(map);
 447	return ret;
 448
 449}
 450
 451static int get_alternative_probe_event(struct debuginfo *dinfo,
 452				       struct perf_probe_event *pev,
 453				       struct perf_probe_point *tmp)
 454{
 455	int ret;
 456
 457	memcpy(tmp, &pev->point, sizeof(*tmp));
 458	memset(&pev->point, 0, sizeof(pev->point));
 459	ret = find_alternative_probe_point(dinfo, tmp, &pev->point, pev->target,
 460					   pev->nsi, pev->uprobes);
 461	if (ret < 0)
 462		memcpy(&pev->point, tmp, sizeof(*tmp));
 463
 464	return ret;
 465}
 466
 467static int get_alternative_line_range(struct debuginfo *dinfo,
 468				      struct line_range *lr,
 469				      const char *target, bool user)
 470{
 471	struct perf_probe_point pp = { .function = lr->function,
 472				       .file = lr->file,
 473				       .line = lr->start };
 474	struct perf_probe_point result;
 475	int ret, len = 0;
 476
 477	memset(&result, 0, sizeof(result));
 478
 479	if (lr->end != INT_MAX)
 480		len = lr->end - lr->start;
 481	ret = find_alternative_probe_point(dinfo, &pp, &result,
 482					   target, NULL, user);
 483	if (!ret) {
 484		lr->function = result.function;
 485		lr->file = result.file;
 486		lr->start = result.line;
 487		if (lr->end != INT_MAX)
 488			lr->end = lr->start + len;
 489		clear_perf_probe_point(&pp);
 490	}
 491	return ret;
 492}
 493
 494#ifdef HAVE_DEBUGINFOD_SUPPORT
 495static struct debuginfo *open_from_debuginfod(struct dso *dso, struct nsinfo *nsi,
 496					      bool silent)
 497{
 498	debuginfod_client *c = debuginfod_begin();
 499	char sbuild_id[SBUILD_ID_SIZE + 1];
 500	struct debuginfo *ret = NULL;
 501	struct nscookie nsc;
 502	char *path;
 503	int fd;
 504
 505	if (!c)
 506		return NULL;
 507
 508	build_id__snprintf(dso__bid(dso), sbuild_id, sizeof(sbuild_id));
 509	fd = debuginfod_find_debuginfo(c, (const unsigned char *)sbuild_id,
 510					0, &path);
 511	if (fd >= 0)
 512		close(fd);
 513	debuginfod_end(c);
 514	if (fd < 0) {
 515		if (!silent)
 516			pr_debug("Failed to find debuginfo in debuginfod.\n");
 517		return NULL;
 518	}
 519	if (!silent)
 520		pr_debug("Load debuginfo from debuginfod (%s)\n", path);
 521
 522	nsinfo__mountns_enter(nsi, &nsc);
 523	ret = debuginfo__new((const char *)path);
 524	nsinfo__mountns_exit(&nsc);
 525	return ret;
 526}
 527#else
 528static inline
 529struct debuginfo *open_from_debuginfod(struct dso *dso __maybe_unused,
 530				       struct nsinfo *nsi __maybe_unused,
 531				       bool silent __maybe_unused)
 532{
 533	return NULL;
 534}
 535#endif
 536
 537/* Open new debuginfo of given module */
 538static struct debuginfo *open_debuginfo(const char *module, struct nsinfo *nsi,
 539					bool silent)
 540{
 541	const char *path = module;
 542	char reason[STRERR_BUFSIZE];
 543	struct debuginfo *ret = NULL;
 544	struct dso *dso = NULL;
 545	struct nscookie nsc;
 546	int err;
 547
 548	if (!module || !strchr(module, '/')) {
 549		err = kernel_get_module_dso(module, &dso);
 550		if (err < 0) {
 551			if (!dso || *dso__load_errno(dso) == 0) {
 552				if (!str_error_r(-err, reason, STRERR_BUFSIZE))
 553					strcpy(reason, "(unknown)");
 554			} else
 555				dso__strerror_load(dso, reason, STRERR_BUFSIZE);
 556			if (dso)
 557				ret = open_from_debuginfod(dso, nsi, silent);
 558			if (ret)
 559				return ret;
 560			if (!silent) {
 561				if (module)
 562					pr_err("Module %s is not loaded, please specify its full path name.\n", module);
 563				else
 564					pr_err("Failed to find the path for the kernel: %s\n", reason);
 565			}
 566			return NULL;
 567		}
 568		path = dso__long_name(dso);
 569	}
 570	nsinfo__mountns_enter(nsi, &nsc);
 571	ret = debuginfo__new(path);
 572	if (!ret && !silent) {
 573		pr_warning("The %s file has no debug information.\n", path);
 574		if (!module || !strtailcmp(path, ".ko"))
 575			pr_warning("Rebuild with CONFIG_DEBUG_INFO=y, ");
 576		else
 577			pr_warning("Rebuild with -g, ");
 578		pr_warning("or install an appropriate debuginfo package.\n");
 579	}
 580	nsinfo__mountns_exit(&nsc);
 581	return ret;
 582}
 583
 584/* For caching the last debuginfo */
 585static struct debuginfo *debuginfo_cache;
 586static char *debuginfo_cache_path;
 587
 588static struct debuginfo *debuginfo_cache__open(const char *module, bool silent)
 589{
 590	const char *path = module;
 591
 592	/* If the module is NULL, it should be the kernel. */
 593	if (!module)
 594		path = "kernel";
 595
 596	if (debuginfo_cache_path && !strcmp(debuginfo_cache_path, path))
 597		goto out;
 598
 599	/* Copy module path */
 600	free(debuginfo_cache_path);
 601	debuginfo_cache_path = strdup(path);
 602	if (!debuginfo_cache_path) {
 603		debuginfo__delete(debuginfo_cache);
 604		debuginfo_cache = NULL;
 605		goto out;
 606	}
 607
 608	debuginfo_cache = open_debuginfo(module, NULL, silent);
 609	if (!debuginfo_cache)
 610		zfree(&debuginfo_cache_path);
 611out:
 612	return debuginfo_cache;
 613}
 614
 615static void debuginfo_cache__exit(void)
 616{
 617	debuginfo__delete(debuginfo_cache);
 618	debuginfo_cache = NULL;
 619	zfree(&debuginfo_cache_path);
 620}
 621
 622
 623static int get_text_start_address(const char *exec, u64 *address,
 624				  struct nsinfo *nsi)
 625{
 626	Elf *elf;
 627	GElf_Ehdr ehdr;
 628	GElf_Shdr shdr;
 629	int fd, ret = -ENOENT;
 630	struct nscookie nsc;
 631
 632	nsinfo__mountns_enter(nsi, &nsc);
 633	fd = open(exec, O_RDONLY);
 634	nsinfo__mountns_exit(&nsc);
 635	if (fd < 0)
 636		return -errno;
 637
 638	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
 639	if (elf == NULL) {
 640		ret = -EINVAL;
 641		goto out_close;
 642	}
 643
 644	if (gelf_getehdr(elf, &ehdr) == NULL)
 645		goto out;
 646
 647	if (!elf_section_by_name(elf, &ehdr, &shdr, ".text", NULL))
 648		goto out;
 649
 650	*address = shdr.sh_addr - shdr.sh_offset;
 651	ret = 0;
 652out:
 653	elf_end(elf);
 654out_close:
 655	close(fd);
 656
 657	return ret;
 658}
 659
 660/*
 661 * Convert trace point to probe point with debuginfo
 662 */
 663static int find_perf_probe_point_from_dwarf(struct probe_trace_point *tp,
 664					    struct perf_probe_point *pp,
 665					    bool is_kprobe)
 666{
 667	struct debuginfo *dinfo = NULL;
 668	u64 stext = 0;
 669	u64 addr = tp->address;
 670	int ret = -ENOENT;
 671
 672	/* convert the address to dwarf address */
 673	if (!is_kprobe) {
 674		if (!addr) {
 675			ret = -EINVAL;
 676			goto error;
 677		}
 678		ret = get_text_start_address(tp->module, &stext, NULL);
 679		if (ret < 0)
 680			goto error;
 681		addr += stext;
 682	} else if (tp->symbol) {
 683		/* If the module is given, this returns relative address */
 684		ret = kernel_get_symbol_address_by_name(tp->symbol, &addr,
 685							false, !!tp->module);
 686		if (ret != 0)
 687			goto error;
 688		addr += tp->offset;
 689	}
 690
 691	pr_debug("try to find information at %" PRIx64 " in %s\n", addr,
 692		 tp->module ? : "kernel");
 693
 694	dinfo = debuginfo_cache__open(tp->module, verbose <= 0);
 695	if (dinfo)
 696		ret = debuginfo__find_probe_point(dinfo, addr, pp);
 697	else
 698		ret = -ENOENT;
 699
 700	if (ret > 0) {
 701		pp->retprobe = tp->retprobe;
 702		return 0;
 703	}
 704error:
 705	pr_debug("Failed to find corresponding probes from debuginfo.\n");
 706	return ret ? : -ENOENT;
 707}
 708
 709/* Adjust symbol name and address */
 710static int post_process_probe_trace_point(struct probe_trace_point *tp,
 711					   struct map *map, u64 offs)
 712{
 713	struct symbol *sym;
 714	u64 addr = tp->address - offs;
 715
 716	sym = map__find_symbol(map, addr);
 717	if (!sym) {
 718		/*
 719		 * If the address is in the inittext section, map can not
 720		 * find it. Ignore it if we are probing offline kernel.
 721		 */
 722		return (symbol_conf.ignore_vmlinux_buildid) ? 0 : -ENOENT;
 723	}
 724
 725	if (strcmp(sym->name, tp->symbol)) {
 726		/* If we have no realname, use symbol for it */
 727		if (!tp->realname)
 728			tp->realname = tp->symbol;
 729		else
 730			free(tp->symbol);
 731		tp->symbol = strdup(sym->name);
 732		if (!tp->symbol)
 733			return -ENOMEM;
 734	}
 735	tp->offset = addr - sym->start;
 736	tp->address -= offs;
 737
 738	return 0;
 739}
 740
 741/*
 742 * Rename DWARF symbols to ELF symbols -- gcc sometimes optimizes functions
 743 * and generate new symbols with suffixes such as .constprop.N or .isra.N
 744 * etc. Since those symbols are not recorded in DWARF, we have to find
 745 * correct generated symbols from offline ELF binary.
 746 * For online kernel or uprobes we don't need this because those are
 747 * rebased on _text, or already a section relative address.
 748 */
 749static int
 750post_process_offline_probe_trace_events(struct probe_trace_event *tevs,
 751					int ntevs, const char *pathname)
 752{
 753	struct map *map;
 754	u64 stext = 0;
 755	int i, ret = 0;
 756
 757	/* Prepare a map for offline binary */
 758	map = dso__new_map(pathname);
 759	if (!map || get_text_start_address(pathname, &stext, NULL) < 0) {
 760		pr_warning("Failed to get ELF symbols for %s\n", pathname);
 761		return -EINVAL;
 762	}
 763
 764	for (i = 0; i < ntevs; i++) {
 765		ret = post_process_probe_trace_point(&tevs[i].point,
 766						     map, stext);
 767		if (ret < 0)
 768			break;
 769	}
 770	map__put(map);
 771
 772	return ret;
 773}
 774
 775static int add_exec_to_probe_trace_events(struct probe_trace_event *tevs,
 776					  int ntevs, const char *exec,
 777					  struct nsinfo *nsi)
 778{
 779	int i, ret = 0;
 780	u64 stext = 0;
 781
 782	if (!exec)
 783		return 0;
 784
 785	ret = get_text_start_address(exec, &stext, nsi);
 786	if (ret < 0)
 787		return ret;
 788
 789	for (i = 0; i < ntevs && ret >= 0; i++) {
 790		/* point.address is the address of point.symbol + point.offset */
 791		tevs[i].point.address -= stext;
 792		tevs[i].point.module = strdup(exec);
 793		if (!tevs[i].point.module) {
 794			ret = -ENOMEM;
 795			break;
 796		}
 797		tevs[i].uprobes = true;
 798	}
 799
 800	return ret;
 801}
 802
 803static int
 804post_process_module_probe_trace_events(struct probe_trace_event *tevs,
 805				       int ntevs, const char *module,
 806				       struct debuginfo *dinfo)
 807{
 808	Dwarf_Addr text_offs = 0;
 809	int i, ret = 0;
 810	char *mod_name = NULL;
 811	struct map *map;
 812
 813	if (!module)
 814		return 0;
 815
 816	map = get_target_map(module, NULL, false);
 817	if (!map || debuginfo__get_text_offset(dinfo, &text_offs, true) < 0) {
 818		pr_warning("Failed to get ELF symbols for %s\n", module);
 819		return -EINVAL;
 820	}
 821
 822	mod_name = find_module_name(module);
 823	for (i = 0; i < ntevs; i++) {
 824		ret = post_process_probe_trace_point(&tevs[i].point,
 825						map, text_offs);
 826		if (ret < 0)
 827			break;
 828		tevs[i].point.module =
 829			strdup(mod_name ? mod_name : module);
 830		if (!tevs[i].point.module) {
 831			ret = -ENOMEM;
 832			break;
 833		}
 834	}
 835
 836	free(mod_name);
 837	map__put(map);
 838
 839	return ret;
 840}
 841
 842static int
 843post_process_kernel_probe_trace_events(struct probe_trace_event *tevs,
 844				       int ntevs)
 845{
 846	struct ref_reloc_sym *reloc_sym;
 847	struct map *map;
 848	char *tmp;
 849	int i, skipped = 0;
 850
 851	/* Skip post process if the target is an offline kernel */
 852	if (symbol_conf.ignore_vmlinux_buildid)
 853		return post_process_offline_probe_trace_events(tevs, ntevs,
 854						symbol_conf.vmlinux_name);
 855
 856	reloc_sym = kernel_get_ref_reloc_sym(&map);
 857	if (!reloc_sym) {
 858		pr_warning("Relocated base symbol is not found! "
 859			   "Check /proc/sys/kernel/kptr_restrict\n"
 860			   "and /proc/sys/kernel/perf_event_paranoid. "
 861			   "Or run as privileged perf user.\n\n");
 862		return -EINVAL;
 863	}
 864
 865	for (i = 0; i < ntevs; i++) {
 866		if (!tevs[i].point.address)
 867			continue;
 868		if (tevs[i].point.retprobe && !kretprobe_offset_is_supported())
 869			continue;
 870		/*
 871		 * If we found a wrong one, mark it by NULL symbol.
 872		 * Since addresses in debuginfo is same as objdump, we need
 873		 * to convert it to addresses on memory.
 874		 */
 875		if (kprobe_warn_out_range(tevs[i].point.symbol,
 876			map__objdump_2mem(map, tevs[i].point.address))) {
 877			tmp = NULL;
 878			skipped++;
 879		} else {
 880			tmp = strdup(reloc_sym->name);
 881			if (!tmp)
 882				return -ENOMEM;
 883		}
 884		/* If we have no realname, use symbol for it */
 885		if (!tevs[i].point.realname)
 886			tevs[i].point.realname = tevs[i].point.symbol;
 887		else
 888			free(tevs[i].point.symbol);
 889		tevs[i].point.symbol = tmp;
 890		tevs[i].point.offset = tevs[i].point.address -
 891			(map__reloc(map) ? reloc_sym->unrelocated_addr :
 892				      reloc_sym->addr);
 893	}
 894	return skipped;
 895}
 896
 897void __weak
 898arch__post_process_probe_trace_events(struct perf_probe_event *pev __maybe_unused,
 899				      int ntevs __maybe_unused)
 900{
 901}
 902
 903/* Post processing the probe events */
 904static int post_process_probe_trace_events(struct perf_probe_event *pev,
 905					   struct probe_trace_event *tevs,
 906					   int ntevs, const char *module,
 907					   bool uprobe, struct debuginfo *dinfo)
 908{
 909	int ret;
 910
 911	if (uprobe)
 912		ret = add_exec_to_probe_trace_events(tevs, ntevs, module,
 913						     pev->nsi);
 914	else if (module)
 915		/* Currently ref_reloc_sym based probe is not for drivers */
 916		ret = post_process_module_probe_trace_events(tevs, ntevs,
 917							     module, dinfo);
 918	else
 919		ret = post_process_kernel_probe_trace_events(tevs, ntevs);
 920
 921	if (ret >= 0)
 922		arch__post_process_probe_trace_events(pev, ntevs);
 923
 924	return ret;
 925}
 926
 927/* Try to find perf_probe_event with debuginfo */
 928static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
 929					  struct probe_trace_event **tevs)
 930{
 931	bool need_dwarf = perf_probe_event_need_dwarf(pev);
 932	struct perf_probe_point tmp;
 933	struct debuginfo *dinfo;
 934	int ntevs, ret = 0;
 935
 936	/* Workaround for gcc #98776 issue.
 937	 * Perf failed to add kretprobe event with debuginfo of vmlinux which is
 938	 * compiled by gcc with -fpatchable-function-entry option enabled. The
 939	 * same issue with kernel module. The retprobe doesn`t need debuginfo.
 940	 * This workaround solution use map to query the probe function address
 941	 * for retprobe event.
 942	 */
 943	if (pev->point.retprobe)
 944		return 0;
 945
 946	dinfo = open_debuginfo(pev->target, pev->nsi, !need_dwarf);
 947	if (!dinfo) {
 948		if (need_dwarf)
 949			return -ENODATA;
 950		pr_debug("Could not open debuginfo. Try to use symbols.\n");
 951		return 0;
 952	}
 953
 954	pr_debug("Try to find probe point from debuginfo.\n");
 955	/* Searching trace events corresponding to a probe event */
 956	ntevs = debuginfo__find_trace_events(dinfo, pev, tevs);
 957
 958	if (ntevs == 0)	{  /* Not found, retry with an alternative */
 959		ret = get_alternative_probe_event(dinfo, pev, &tmp);
 960		if (!ret) {
 961			ntevs = debuginfo__find_trace_events(dinfo, pev, tevs);
 962			/*
 963			 * Write back to the original probe_event for
 964			 * setting appropriate (user given) event name
 965			 */
 966			clear_perf_probe_point(&pev->point);
 967			memcpy(&pev->point, &tmp, sizeof(tmp));
 968		}
 969	}
 970
 971	if (ntevs > 0) {	/* Succeeded to find trace events */
 972		pr_debug("Found %d probe_trace_events.\n", ntevs);
 973		ret = post_process_probe_trace_events(pev, *tevs, ntevs,
 974					pev->target, pev->uprobes, dinfo);
 975		if (ret < 0 || ret == ntevs) {
 976			pr_debug("Post processing failed or all events are skipped. (%d)\n", ret);
 977			clear_probe_trace_events(*tevs, ntevs);
 978			zfree(tevs);
 979			ntevs = 0;
 980		}
 981	}
 982
 983	debuginfo__delete(dinfo);
 984
 985	if (ntevs == 0)	{	/* No error but failed to find probe point. */
 986		char *probe_point = synthesize_perf_probe_point(&pev->point);
 987		pr_warning("Probe point '%s' not found.\n", probe_point);
 988		free(probe_point);
 989		return -ENODEV;
 990	} else if (ntevs < 0) {
 991		/* Error path : ntevs < 0 */
 992		pr_debug("An error occurred in debuginfo analysis (%d).\n", ntevs);
 993		if (ntevs == -EBADF)
 994			pr_warning("Warning: No dwarf info found in the vmlinux - "
 995				"please rebuild kernel with CONFIG_DEBUG_INFO=y.\n");
 996		if (!need_dwarf) {
 997			pr_debug("Trying to use symbols.\n");
 998			return 0;
 999		}
1000	}
1001	return ntevs;
1002}
1003
1004#define LINEBUF_SIZE 256
1005#define NR_ADDITIONAL_LINES 2
1006
1007static int __show_one_line(FILE *fp, int l, bool skip, bool show_num)
1008{
1009	char buf[LINEBUF_SIZE], sbuf[STRERR_BUFSIZE];
1010	const char *color = show_num ? "" : PERF_COLOR_BLUE;
1011	const char *prefix = NULL;
1012
1013	do {
1014		if (fgets(buf, LINEBUF_SIZE, fp) == NULL)
1015			goto error;
1016		if (skip)
1017			continue;
1018		if (!prefix) {
1019			prefix = show_num ? "%7d  " : "         ";
1020			color_fprintf(stdout, color, prefix, l);
1021		}
1022		color_fprintf(stdout, color, "%s", buf);
1023
1024	} while (strchr(buf, '\n') == NULL);
1025
1026	return 1;
1027error:
1028	if (ferror(fp)) {
1029		pr_warning("File read error: %s\n",
1030			   str_error_r(errno, sbuf, sizeof(sbuf)));
1031		return -1;
1032	}
1033	return 0;
1034}
1035
1036static int _show_one_line(FILE *fp, int l, bool skip, bool show_num)
1037{
1038	int rv = __show_one_line(fp, l, skip, show_num);
1039	if (rv == 0) {
1040		pr_warning("Source file is shorter than expected.\n");
1041		rv = -1;
1042	}
1043	return rv;
1044}
1045
1046static int sprint_line_description(char *sbuf, size_t size, struct line_range *lr)
1047{
1048	if (!lr->function)
1049		return snprintf(sbuf, size, "file: %s, line: %d", lr->file, lr->start);
1050
1051	if (lr->file)
1052		return snprintf(sbuf, size, "function: %s, file:%s, line: %d", lr->function, lr->file, lr->start);
1053
1054	return snprintf(sbuf, size, "function: %s, line:%d", lr->function, lr->start);
1055}
1056
1057#define show_one_line_with_num(f,l)	_show_one_line(f,l,false,true)
1058#define show_one_line(f,l)		_show_one_line(f,l,false,false)
1059#define skip_one_line(f,l)		_show_one_line(f,l,true,false)
1060#define show_one_line_or_eof(f,l)	__show_one_line(f,l,false,false)
1061
1062/*
1063 * Show line-range always requires debuginfo to find source file and
1064 * line number.
1065 */
1066static int __show_line_range(struct line_range *lr, const char *module,
1067			     bool user)
1068{
1069	int l = 1;
1070	struct int_node *ln;
1071	struct debuginfo *dinfo;
1072	FILE *fp;
1073	int ret;
1074	char *tmp;
1075	char sbuf[STRERR_BUFSIZE];
1076	char sbuild_id[SBUILD_ID_SIZE] = "";
1077
1078	/* Search a line range */
1079	dinfo = open_debuginfo(module, NULL, false);
1080	if (!dinfo)
1081		return -ENOENT;
1082
1083	ret = debuginfo__find_line_range(dinfo, lr);
1084	if (!ret) {	/* Not found, retry with an alternative */
1085		pr_debug2("Failed to find line range in debuginfo. Fallback to alternative\n");
1086		ret = get_alternative_line_range(dinfo, lr, module, user);
1087		if (!ret)
1088			ret = debuginfo__find_line_range(dinfo, lr);
1089		else /* Ignore error, we just failed to find it. */
1090			ret = -ENOENT;
1091	}
1092	if (dinfo->build_id) {
1093		struct build_id bid;
1094
1095		build_id__init(&bid, dinfo->build_id, BUILD_ID_SIZE);
1096		build_id__snprintf(&bid, sbuild_id, sizeof(sbuild_id));
1097	}
1098	debuginfo__delete(dinfo);
1099	if (ret == 0 || ret == -ENOENT) {
1100		sprint_line_description(sbuf, sizeof(sbuf), lr);
1101		pr_warning("Specified source line(%s) is not found.\n", sbuf);
1102		return -ENOENT;
1103	} else if (ret < 0) {
1104		pr_warning("Debuginfo analysis failed.\n");
1105		return ret;
1106	}
1107
1108	/* Convert source file path */
1109	tmp = lr->path;
1110	ret = find_source_path(tmp, sbuild_id, lr->comp_dir, &lr->path);
1111
1112	/* Free old path when new path is assigned */
1113	if (tmp != lr->path)
1114		free(tmp);
1115
1116	if (ret < 0) {
1117		pr_warning("Failed to find source file path.\n");
1118		return ret;
1119	}
1120
1121	setup_pager();
1122
1123	if (lr->function)
1124		fprintf(stdout, "<%s@%s:%d>\n", lr->function, lr->path,
1125			lr->start - lr->offset);
1126	else
1127		fprintf(stdout, "<%s:%d>\n", lr->path, lr->start);
1128
1129	fp = fopen(lr->path, "r");
1130	if (fp == NULL) {
1131		pr_warning("Failed to open %s: %s\n", lr->path,
1132			   str_error_r(errno, sbuf, sizeof(sbuf)));
1133		return -errno;
1134	}
1135	/* Skip to starting line number */
1136	while (l < lr->start) {
1137		ret = skip_one_line(fp, l++);
1138		if (ret < 0)
1139			goto end;
1140	}
1141
1142	intlist__for_each_entry(ln, lr->line_list) {
1143		for (; ln->i > (unsigned long)l; l++) {
1144			ret = show_one_line(fp, l - lr->offset);
1145			if (ret < 0)
1146				goto end;
1147		}
1148		ret = show_one_line_with_num(fp, l++ - lr->offset);
1149		if (ret < 0)
1150			goto end;
1151	}
1152
1153	if (lr->end == INT_MAX)
1154		lr->end = l + NR_ADDITIONAL_LINES;
1155	while (l <= lr->end) {
1156		ret = show_one_line_or_eof(fp, l++ - lr->offset);
1157		if (ret <= 0)
1158			break;
1159	}
1160end:
1161	fclose(fp);
1162	return ret;
1163}
1164
1165int show_line_range(struct line_range *lr, const char *module,
1166		    struct nsinfo *nsi, bool user)
1167{
1168	int ret;
1169	struct nscookie nsc;
1170
1171	ret = init_probe_symbol_maps(user);
1172	if (ret < 0)
1173		return ret;
1174	nsinfo__mountns_enter(nsi, &nsc);
1175	ret = __show_line_range(lr, module, user);
1176	nsinfo__mountns_exit(&nsc);
1177	exit_probe_symbol_maps();
1178
1179	return ret;
1180}
1181
1182static int show_available_vars_at(struct debuginfo *dinfo,
1183				  struct perf_probe_event *pev,
1184				  struct strfilter *_filter)
1185{
1186	char *buf;
1187	int ret, i, nvars;
1188	struct str_node *node;
1189	struct variable_list *vls = NULL, *vl;
1190	struct perf_probe_point tmp;
1191	const char *var;
1192
1193	buf = synthesize_perf_probe_point(&pev->point);
1194	if (!buf)
1195		return -EINVAL;
1196	pr_debug("Searching variables at %s\n", buf);
1197
1198	ret = debuginfo__find_available_vars_at(dinfo, pev, &vls);
1199	if (!ret) {  /* Not found, retry with an alternative */
1200		ret = get_alternative_probe_event(dinfo, pev, &tmp);
1201		if (!ret) {
1202			ret = debuginfo__find_available_vars_at(dinfo, pev,
1203								&vls);
1204			/* Release the old probe_point */
1205			clear_perf_probe_point(&tmp);
1206		}
1207	}
1208	if (ret <= 0) {
1209		if (ret == 0 || ret == -ENOENT) {
1210			pr_err("Failed to find the address of %s\n", buf);
1211			ret = -ENOENT;
1212		} else
1213			pr_warning("Debuginfo analysis failed.\n");
1214		goto end;
1215	}
1216
1217	/* Some variables are found */
1218	fprintf(stdout, "Available variables at %s\n", buf);
1219	for (i = 0; i < ret; i++) {
1220		vl = &vls[i];
1221		/*
1222		 * A probe point might be converted to
1223		 * several trace points.
1224		 */
1225		fprintf(stdout, "\t@<%s+%lu>\n", vl->point.symbol,
1226			vl->point.offset);
1227		zfree(&vl->point.symbol);
1228		nvars = 0;
1229		if (vl->vars) {
1230			strlist__for_each_entry(node, vl->vars) {
1231				var = strchr(node->s, '\t') + 1;
1232				if (strfilter__compare(_filter, var)) {
1233					fprintf(stdout, "\t\t%s\n", node->s);
1234					nvars++;
1235				}
1236			}
1237			strlist__delete(vl->vars);
1238		}
1239		if (nvars == 0)
1240			fprintf(stdout, "\t\t(No matched variables)\n");
1241	}
1242	free(vls);
1243end:
1244	free(buf);
1245	return ret;
1246}
1247
1248/* Show available variables on given probe point */
1249int show_available_vars(struct perf_probe_event *pevs, int npevs,
1250			struct strfilter *_filter)
1251{
1252	int i, ret = 0;
1253	struct debuginfo *dinfo;
1254
1255	ret = init_probe_symbol_maps(pevs->uprobes);
1256	if (ret < 0)
1257		return ret;
1258
1259	dinfo = open_debuginfo(pevs->target, pevs->nsi, false);
1260	if (!dinfo) {
1261		ret = -ENOENT;
1262		goto out;
1263	}
1264
1265	setup_pager();
1266
1267	for (i = 0; i < npevs && ret >= 0; i++)
1268		ret = show_available_vars_at(dinfo, &pevs[i], _filter);
1269
1270	debuginfo__delete(dinfo);
1271out:
1272	exit_probe_symbol_maps();
1273	return ret;
1274}
1275
1276#else	/* !HAVE_LIBDW_SUPPORT */
1277
1278static void debuginfo_cache__exit(void)
1279{
1280}
1281
1282static int
1283find_perf_probe_point_from_dwarf(struct probe_trace_point *tp __maybe_unused,
1284				 struct perf_probe_point *pp __maybe_unused,
1285				 bool is_kprobe __maybe_unused)
1286{
1287	return -ENOSYS;
1288}
1289
1290static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
1291				struct probe_trace_event **tevs __maybe_unused)
1292{
1293	if (perf_probe_event_need_dwarf(pev)) {
1294		pr_warning("Debuginfo-analysis is not supported.\n");
1295		return -ENOSYS;
1296	}
1297
1298	return 0;
1299}
1300
1301int show_line_range(struct line_range *lr __maybe_unused,
1302		    const char *module __maybe_unused,
1303		    struct nsinfo *nsi __maybe_unused,
1304		    bool user __maybe_unused)
1305{
1306	pr_warning("Debuginfo-analysis is not supported.\n");
1307	return -ENOSYS;
1308}
1309
1310int show_available_vars(struct perf_probe_event *pevs __maybe_unused,
1311			int npevs __maybe_unused,
1312			struct strfilter *filter __maybe_unused)
1313{
1314	pr_warning("Debuginfo-analysis is not supported.\n");
1315	return -ENOSYS;
1316}
1317#endif
1318
1319void line_range__clear(struct line_range *lr)
1320{
1321	zfree(&lr->function);
1322	zfree(&lr->file);
1323	zfree(&lr->path);
1324	zfree(&lr->comp_dir);
1325	intlist__delete(lr->line_list);
1326}
1327
1328int line_range__init(struct line_range *lr)
1329{
1330	memset(lr, 0, sizeof(*lr));
1331	lr->line_list = intlist__new(NULL);
1332	if (!lr->line_list)
1333		return -ENOMEM;
1334	else
1335		return 0;
1336}
1337
1338static int parse_line_num(char **ptr, int *val, const char *what)
1339{
1340	const char *start = *ptr;
1341
1342	errno = 0;
1343	*val = strtol(*ptr, ptr, 0);
1344	if (errno || *ptr == start) {
1345		semantic_error("'%s' is not a valid number.\n", what);
1346		return -EINVAL;
1347	}
1348	return 0;
1349}
1350
1351/* Check the name is good for event, group or function */
1352static bool is_c_func_name(const char *name)
1353{
1354	if (!isalpha(*name) && *name != '_')
1355		return false;
1356	while (*++name != '\0') {
1357		if (!isalpha(*name) && !isdigit(*name) && *name != '_')
1358			return false;
1359	}
1360	return true;
1361}
1362
1363/*
1364 * Stuff 'lr' according to the line range described by 'arg'.
1365 * The line range syntax is described by:
1366 *
1367 *         SRC[:SLN[+NUM|-ELN]]
1368 *         FNC[@SRC][:SLN[+NUM|-ELN]]
1369 *
1370 * FNC@SRC accepts `FNC@*` which forcibly specify FNC as function name.
1371 * SRC and FUNC can be quoted by double/single quotes.
1372 */
1373int parse_line_range_desc(const char *arg, struct line_range *lr)
1374{
1375	char *buf = strdup(arg);
1376	char *p;
1377	int err = 0;
1378
1379	if (!buf)
1380		return -ENOMEM;
1381
1382	lr->start = 0;
1383	lr->end = INT_MAX;
1384
1385	p = strpbrk_esq(buf, ":");
1386	if (p) {
1387		if (p == buf) {
1388			semantic_error("No file/function name in '%s'.\n", p);
1389			err = -EINVAL;
1390			goto out;
1391		}
1392		*(p++) = '\0';
1393
1394		err = parse_line_num(&p, &lr->start, "start line");
1395		if (err)
1396			goto out;
1397
1398		if (*p == '+' || *p == '-') {
1399			const char c = *(p++);
1400
1401			err = parse_line_num(&p, &lr->end, "end line");
1402			if (err)
1403				goto out;
1404
1405			if (c == '+') {
1406				lr->end += lr->start;
1407				/*
1408				 * Adjust the number of lines here.
1409				 * If the number of lines == 1, the
1410				 * end of line should be equal to
1411				 * the start of line.
1412				 */
1413				lr->end--;
1414			}
1415		}
1416
1417		pr_debug("Line range is %d to %d\n", lr->start, lr->end);
1418
1419		err = -EINVAL;
1420		if (lr->start > lr->end) {
1421			semantic_error("Start line must be smaller"
1422				       " than end line.\n");
1423			goto out;
1424		}
1425		if (*p != '\0') {
1426			semantic_error("Tailing with invalid str '%s'.\n", p);
1427			goto out;
1428		}
1429	}
1430
1431	p = strpbrk_esq(buf, "@");
1432	if (p) {
1433		*p++ = '\0';
1434		if (strcmp(p, "*")) {
1435			lr->file = strdup_esq(p);
1436			if (lr->file == NULL) {
1437				err = -ENOMEM;
1438				goto out;
1439			}
1440		}
1441		if (*buf != '\0')
1442			lr->function = strdup_esq(buf);
1443		if (!lr->function && !lr->file) {
1444			semantic_error("Only '@*' is not allowed.\n");
1445			err = -EINVAL;
1446			goto out;
1447		}
1448	} else if (strpbrk_esq(buf, "/."))
1449		lr->file = strdup_esq(buf);
1450	else if (is_c_func_name(buf))/* We reuse it for checking funcname */
1451		lr->function = strdup_esq(buf);
1452	else {	/* Invalid name */
1453		semantic_error("'%s' is not a valid function name.\n", buf);
1454		err = -EINVAL;
1455		goto out;
1456	}
1457
1458out:
1459	free(buf);
1460	return err;
1461}
1462
1463static int parse_perf_probe_event_name(char **arg, struct perf_probe_event *pev)
1464{
1465	char *ptr;
1466
1467	ptr = strpbrk_esq(*arg, ":");
1468	if (ptr) {
1469		*ptr = '\0';
1470		if (!pev->sdt && !is_c_func_name(*arg))
1471			goto ng_name;
1472		pev->group = strdup_esq(*arg);
1473		if (!pev->group)
1474			return -ENOMEM;
1475		*arg = ptr + 1;
1476	} else
1477		pev->group = NULL;
1478
1479	pev->event = strdup_esq(*arg);
1480	if (pev->event == NULL)
1481		return -ENOMEM;
1482
1483	if (!pev->sdt && !is_c_func_name(pev->event)) {
1484		zfree(&pev->event);
1485ng_name:
1486		zfree(&pev->group);
1487		semantic_error("%s is bad for event name -it must "
1488			       "follow C symbol-naming rule.\n", *arg);
1489		return -EINVAL;
1490	}
1491	return 0;
1492}
1493
1494/* Parse probepoint definition. */
1495static int parse_perf_probe_point(char *arg, struct perf_probe_event *pev)
1496{
1497	struct perf_probe_point *pp = &pev->point;
1498	char *ptr, *tmp;
1499	char c, nc = 0;
1500	bool file_spec = false;
1501	int ret;
1502
1503	/*
1504	 * <Syntax>
1505	 * perf probe [GRP:][EVENT=]SRC[:LN|;PTN]
1506	 * perf probe [GRP:][EVENT=]FUNC[@SRC][+OFFS|%return|:LN|;PAT]
1507	 * perf probe %[GRP:]SDT_EVENT
1508	 */
1509	if (!arg)
1510		return -EINVAL;
1511
1512	if (is_sdt_event(arg)) {
1513		pev->sdt = true;
1514		if (arg[0] == '%')
1515			arg++;
1516	}
1517
1518	ptr = strpbrk_esq(arg, ";=@+%");
1519	if (pev->sdt) {
1520		if (ptr) {
1521			if (*ptr != '@') {
1522				semantic_error("%s must be an SDT name.\n",
1523					       arg);
1524				return -EINVAL;
1525			}
1526			/* This must be a target file name or build id */
1527			tmp = build_id_cache__complement(ptr + 1);
1528			if (tmp) {
1529				pev->target = build_id_cache__origname(tmp);
1530				free(tmp);
1531			} else
1532				pev->target = strdup_esq(ptr + 1);
1533			if (!pev->target)
1534				return -ENOMEM;
1535			*ptr = '\0';
1536		}
1537		ret = parse_perf_probe_event_name(&arg, pev);
1538		if (ret == 0) {
1539			if (asprintf(&pev->point.function, "%%%s", pev->event) < 0)
1540				ret = -errno;
1541		}
1542		return ret;
1543	}
1544
1545	if (ptr && *ptr == '=') {	/* Event name */
1546		*ptr = '\0';
1547		tmp = ptr + 1;
1548		ret = parse_perf_probe_event_name(&arg, pev);
1549		if (ret < 0)
1550			return ret;
1551
1552		arg = tmp;
1553	}
1554
1555	/*
1556	 * Check arg is function or file name and copy it.
1557	 *
1558	 * We consider arg to be a file spec if and only if it satisfies
1559	 * all of the below criteria::
1560	 * - it does not include any of "+@%",
1561	 * - it includes one of ":;", and
1562	 * - it has a period '.' in the name.
1563	 *
1564	 * Otherwise, we consider arg to be a function specification.
1565	 */
1566	if (!strpbrk_esc(arg, "+@%")) {
1567		ptr = strpbrk_esc(arg, ";:");
1568		/* This is a file spec if it includes a '.' before ; or : */
1569		if (ptr && memchr(arg, '.', ptr - arg))
1570			file_spec = true;
1571	}
1572
1573	ptr = strpbrk_esq(arg, ";:+@%");
1574	if (ptr) {
1575		nc = *ptr;
1576		*ptr++ = '\0';
1577	}
1578
1579	if (arg[0] == '\0')
1580		tmp = NULL;
1581	else {
1582		tmp = strdup_esq(arg);
1583		if (tmp == NULL)
1584			return -ENOMEM;
1585	}
1586
1587	if (file_spec)
1588		pp->file = tmp;
1589	else {
1590		pp->function = tmp;
1591
1592		/*
1593		 * Keep pp->function even if this is absolute address,
1594		 * so it can mark whether abs_address is valid.
1595		 * Which make 'perf probe lib.bin 0x0' possible.
1596		 *
1597		 * Note that checking length of tmp is not needed
1598		 * because when we access tmp[1] we know tmp[0] is '0',
1599		 * so tmp[1] should always valid (but could be '\0').
1600		 */
1601		if (tmp && !strncmp(tmp, "0x", 2)) {
1602			pp->abs_address = strtoull(pp->function, &tmp, 0);
1603			if (*tmp != '\0') {
1604				semantic_error("Invalid absolute address.\n");
1605				return -EINVAL;
1606			}
1607		}
1608	}
1609
1610	/* Parse other options */
1611	while (ptr) {
1612		arg = ptr;
1613		c = nc;
1614		if (c == ';') {	/* Lazy pattern must be the last part */
1615			pp->lazy_line = strdup(arg); /* let leave escapes */
1616			if (pp->lazy_line == NULL)
1617				return -ENOMEM;
1618			break;
1619		}
1620		ptr = strpbrk_esq(arg, ";:+@%");
1621		if (ptr) {
1622			nc = *ptr;
1623			*ptr++ = '\0';
1624		}
1625		switch (c) {
1626		case ':':	/* Line number */
1627			pp->line = strtoul(arg, &tmp, 0);
1628			if (*tmp != '\0') {
1629				semantic_error("There is non-digit char"
1630					       " in line number.\n");
1631				return -EINVAL;
1632			}
1633			break;
1634		case '+':	/* Byte offset from a symbol */
1635			pp->offset = strtoul(arg, &tmp, 0);
1636			if (*tmp != '\0') {
1637				semantic_error("There is non-digit character"
1638						" in offset.\n");
1639				return -EINVAL;
1640			}
1641			break;
1642		case '@':	/* File name */
1643			if (pp->file) {
1644				semantic_error("SRC@SRC is not allowed.\n");
1645				return -EINVAL;
1646			}
1647			if (!strcmp(arg, "*"))
1648				break;
1649			pp->file = strdup_esq(arg);
1650			if (pp->file == NULL)
1651				return -ENOMEM;
1652			break;
1653		case '%':	/* Probe places */
1654			if (strcmp(arg, "return") == 0) {
1655				pp->retprobe = 1;
1656			} else {	/* Others not supported yet */
1657				semantic_error("%%%s is not supported.\n", arg);
1658				return -ENOTSUP;
1659			}
1660			break;
1661		default:	/* Buggy case */
1662			pr_err("This program has a bug at %s:%d.\n",
1663				__FILE__, __LINE__);
1664			return -ENOTSUP;
1665			break;
1666		}
1667	}
1668
1669	/* Exclusion check */
1670	if (pp->lazy_line && pp->line) {
1671		semantic_error("Lazy pattern can't be used with"
1672			       " line number.\n");
1673		return -EINVAL;
1674	}
1675
1676	if (pp->lazy_line && pp->offset) {
1677		semantic_error("Lazy pattern can't be used with offset.\n");
1678		return -EINVAL;
1679	}
1680
1681	if (pp->line && pp->offset) {
1682		semantic_error("Offset can't be used with line number.\n");
1683		return -EINVAL;
1684	}
1685
1686	if (!pp->line && !pp->lazy_line && pp->file && !pp->function) {
1687		semantic_error("File always requires line number or "
1688			       "lazy pattern.\n");
1689		return -EINVAL;
1690	}
1691
1692	if (pp->offset && !pp->function) {
1693		semantic_error("Offset requires an entry function.\n");
1694		return -EINVAL;
1695	}
1696
1697	if ((pp->offset || pp->line || pp->lazy_line) && pp->retprobe) {
1698		semantic_error("Offset/Line/Lazy pattern can't be used with "
1699			       "return probe.\n");
1700		return -EINVAL;
1701	}
1702
1703	pr_debug("symbol:%s file:%s line:%d offset:%lu return:%d lazy:%s\n",
1704		 pp->function, pp->file, pp->line, pp->offset, pp->retprobe,
1705		 pp->lazy_line);
1706	return 0;
1707}
1708
1709/* Parse perf-probe event argument */
1710static int parse_perf_probe_arg(char *str, struct perf_probe_arg *arg)
1711{
1712	char *tmp, *goodname;
1713	struct perf_probe_arg_field **fieldp;
1714
1715	pr_debug("parsing arg: %s into ", str);
1716
1717	tmp = strchr(str, '=');
1718	if (tmp) {
1719		arg->name = strndup(str, tmp - str);
1720		if (arg->name == NULL)
1721			return -ENOMEM;
1722		pr_debug("name:%s ", arg->name);
1723		str = tmp + 1;
1724	}
1725
1726	tmp = strchr(str, '@');
1727	if (tmp && tmp != str && !strcmp(tmp + 1, "user")) { /* user attr */
1728		if (!user_access_is_supported()) {
1729			semantic_error("ftrace does not support user access\n");
1730			return -EINVAL;
1731		}
1732		*tmp = '\0';
1733		arg->user_access = true;
1734		pr_debug("user_access ");
1735	}
1736
1737	tmp = strchr(str, ':');
1738	if (tmp) {	/* Type setting */
1739		*tmp = '\0';
1740		arg->type = strdup(tmp + 1);
1741		if (arg->type == NULL)
1742			return -ENOMEM;
1743		pr_debug("type:%s ", arg->type);
1744	}
1745
1746	tmp = strpbrk(str, "-.[");
1747	if (!is_c_varname(str) || !tmp) {
1748		/* A variable, register, symbol or special value */
1749		arg->var = strdup(str);
1750		if (arg->var == NULL)
1751			return -ENOMEM;
1752		pr_debug("%s\n", arg->var);
1753		return 0;
1754	}
1755
1756	/* Structure fields or array element */
1757	arg->var = strndup(str, tmp - str);
1758	if (arg->var == NULL)
1759		return -ENOMEM;
1760	goodname = arg->var;
1761	pr_debug("%s, ", arg->var);
1762	fieldp = &arg->field;
1763
1764	do {
1765		*fieldp = zalloc(sizeof(struct perf_probe_arg_field));
1766		if (*fieldp == NULL)
1767			return -ENOMEM;
1768		if (*tmp == '[') {	/* Array */
1769			str = tmp;
1770			(*fieldp)->index = strtol(str + 1, &tmp, 0);
1771			(*fieldp)->ref = true;
1772			if (*tmp != ']' || tmp == str + 1) {
1773				semantic_error("Array index must be a"
1774						" number.\n");
1775				return -EINVAL;
1776			}
1777			tmp++;
1778			if (*tmp == '\0')
1779				tmp = NULL;
1780		} else {		/* Structure */
1781			if (*tmp == '.') {
1782				str = tmp + 1;
1783				(*fieldp)->ref = false;
1784			} else if (tmp[1] == '>') {
1785				str = tmp + 2;
1786				(*fieldp)->ref = true;
1787			} else {
1788				semantic_error("Argument parse error: %s\n",
1789					       str);
1790				return -EINVAL;
1791			}
1792			tmp = strpbrk(str, "-.[");
1793		}
1794		if (tmp) {
1795			(*fieldp)->name = strndup(str, tmp - str);
1796			if ((*fieldp)->name == NULL)
1797				return -ENOMEM;
1798			if (*str != '[')
1799				goodname = (*fieldp)->name;
1800			pr_debug("%s(%d), ", (*fieldp)->name, (*fieldp)->ref);
1801			fieldp = &(*fieldp)->next;
1802		}
1803	} while (tmp);
1804	(*fieldp)->name = strdup(str);
1805	if ((*fieldp)->name == NULL)
1806		return -ENOMEM;
1807	if (*str != '[')
1808		goodname = (*fieldp)->name;
1809	pr_debug("%s(%d)\n", (*fieldp)->name, (*fieldp)->ref);
1810
1811	/* If no name is specified, set the last field name (not array index)*/
1812	if (!arg->name) {
1813		arg->name = strdup(goodname);
1814		if (arg->name == NULL)
1815			return -ENOMEM;
1816	}
1817	return 0;
1818}
1819
1820/* Parse perf-probe event command */
1821int parse_perf_probe_command(const char *cmd, struct perf_probe_event *pev)
1822{
1823	char **argv;
1824	int argc, i, ret = 0;
1825
1826	argv = argv_split(cmd, &argc);
1827	if (!argv) {
1828		pr_debug("Failed to split arguments.\n");
1829		return -ENOMEM;
1830	}
1831	if (argc - 1 > MAX_PROBE_ARGS) {
1832		semantic_error("Too many probe arguments (%d).\n", argc - 1);
1833		ret = -ERANGE;
1834		goto out;
1835	}
1836	/* Parse probe point */
1837	ret = parse_perf_probe_point(argv[0], pev);
1838	if (ret < 0)
1839		goto out;
1840
1841	/* Generate event name if needed */
1842	if (!pev->event && pev->point.function && pev->point.line
1843			&& !pev->point.lazy_line && !pev->point.offset) {
1844		if (asprintf(&pev->event, "%s_L%d", pev->point.function,
1845			pev->point.line) < 0) {
1846			ret = -ENOMEM;
1847			goto out;
1848		}
1849	}
1850
1851	/* Copy arguments and ensure return probe has no C argument */
1852	pev->nargs = argc - 1;
1853	pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
1854	if (pev->args == NULL) {
1855		ret = -ENOMEM;
1856		goto out;
1857	}
1858	for (i = 0; i < pev->nargs && ret >= 0; i++) {
1859		ret = parse_perf_probe_arg(argv[i + 1], &pev->args[i]);
1860		if (ret >= 0 &&
1861		    is_c_varname(pev->args[i].var) && pev->point.retprobe) {
1862			semantic_error("You can't specify local variable for"
1863				       " kretprobe.\n");
1864			ret = -EINVAL;
1865		}
1866	}
1867out:
1868	argv_free(argv);
1869
1870	return ret;
1871}
1872
1873/* Returns true if *any* ARG is either C variable, $params or $vars. */
1874bool perf_probe_with_var(struct perf_probe_event *pev)
1875{
1876	int i = 0;
1877
1878	for (i = 0; i < pev->nargs; i++)
1879		if (is_c_varname(pev->args[i].var)              ||
1880		    !strcmp(pev->args[i].var, PROBE_ARG_PARAMS) ||
1881		    !strcmp(pev->args[i].var, PROBE_ARG_VARS))
1882			return true;
1883	return false;
1884}
1885
1886/* Return true if this perf_probe_event requires debuginfo */
1887bool perf_probe_event_need_dwarf(struct perf_probe_event *pev)
1888{
1889	if (pev->point.file || pev->point.line || pev->point.lazy_line)
1890		return true;
1891
1892	if (perf_probe_with_var(pev))
1893		return true;
1894
1895	return false;
1896}
1897
1898/* Parse probe_events event into struct probe_point */
1899int parse_probe_trace_command(const char *cmd, struct probe_trace_event *tev)
1900{
1901	struct probe_trace_point *tp = &tev->point;
1902	char pr;
1903	char *p;
1904	char *argv0_str = NULL, *fmt, *fmt1_str, *fmt2_str, *fmt3_str;
1905	int ret, i, argc;
1906	char **argv;
1907
1908	pr_debug("Parsing probe_events: %s\n", cmd);
1909	argv = argv_split(cmd, &argc);
1910	if (!argv) {
1911		pr_debug("Failed to split arguments.\n");
1912		return -ENOMEM;
1913	}
1914	if (argc < 2) {
1915		semantic_error("Too few probe arguments.\n");
1916		ret = -ERANGE;
1917		goto out;
1918	}
1919
1920	/* Scan event and group name. */
1921	argv0_str = strdup(argv[0]);
1922	if (argv0_str == NULL) {
1923		ret = -ENOMEM;
1924		goto out;
1925	}
1926	fmt1_str = strtok_r(argv0_str, ":", &fmt);
1927	fmt2_str = strtok_r(NULL, "/", &fmt);
1928	fmt3_str = strtok_r(NULL, " \t", &fmt);
1929	if (fmt1_str == NULL || fmt2_str == NULL || fmt3_str == NULL) {
1930		semantic_error("Failed to parse event name: %s\n", argv[0]);
1931		ret = -EINVAL;
1932		goto out;
1933	}
1934	pr = fmt1_str[0];
1935	tev->group = strdup(fmt2_str);
1936	tev->event = strdup(fmt3_str);
1937	if (tev->group == NULL || tev->event == NULL) {
1938		ret = -ENOMEM;
1939		goto out;
1940	}
1941	pr_debug("Group:%s Event:%s probe:%c\n", tev->group, tev->event, pr);
1942
1943	tp->retprobe = (pr == 'r');
1944
1945	/* Scan module name(if there), function name and offset */
1946	p = strchr(argv[1], ':');
1947	if (p) {
1948		tp->module = strndup(argv[1], p - argv[1]);
1949		if (!tp->module) {
1950			ret = -ENOMEM;
1951			goto out;
1952		}
1953		tev->uprobes = (tp->module[0] == '/');
1954		p++;
1955	} else
1956		p = argv[1];
1957	fmt1_str = strtok_r(p, "+", &fmt);
1958	/* only the address started with 0x */
1959	if (fmt1_str[0] == '0')	{
1960		/*
1961		 * Fix a special case:
1962		 * if address == 0, kernel reports something like:
1963		 * p:probe_libc/abs_0 /lib/libc-2.18.so:0x          (null) arg1=%ax
1964		 * Newer kernel may fix that, but we want to
1965		 * support old kernel also.
1966		 */
1967		if (strcmp(fmt1_str, "0x") == 0) {
1968			if (!argv[2] || strcmp(argv[2], "(null)")) {
1969				ret = -EINVAL;
1970				goto out;
1971			}
1972			tp->address = 0;
1973
1974			free(argv[2]);
1975			for (i = 2; argv[i + 1] != NULL; i++)
1976				argv[i] = argv[i + 1];
1977
1978			argv[i] = NULL;
1979			argc -= 1;
1980		} else
1981			tp->address = strtoull(fmt1_str, NULL, 0);
1982	} else {
1983		/* Only the symbol-based probe has offset */
1984		tp->symbol = strdup(fmt1_str);
1985		if (tp->symbol == NULL) {
1986			ret = -ENOMEM;
1987			goto out;
1988		}
1989		fmt2_str = strtok_r(NULL, "", &fmt);
1990		if (fmt2_str == NULL)
1991			tp->offset = 0;
1992		else
1993			tp->offset = strtoul(fmt2_str, NULL, 10);
1994	}
1995
1996	if (tev->uprobes) {
1997		fmt2_str = strchr(p, '(');
1998		if (fmt2_str)
1999			tp->ref_ctr_offset = strtoul(fmt2_str + 1, NULL, 0);
2000	}
2001
2002	tev->nargs = argc - 2;
2003	tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
2004	if (tev->args == NULL) {
2005		ret = -ENOMEM;
2006		goto out;
2007	}
2008	for (i = 0; i < tev->nargs; i++) {
2009		p = strchr(argv[i + 2], '=');
2010		if (p)	/* We don't need which register is assigned. */
2011			*p++ = '\0';
2012		else
2013			p = argv[i + 2];
2014		tev->args[i].name = strdup(argv[i + 2]);
2015		/* TODO: parse regs and offset */
2016		tev->args[i].value = strdup(p);
2017		if (tev->args[i].name == NULL || tev->args[i].value == NULL) {
2018			ret = -ENOMEM;
2019			goto out;
2020		}
2021	}
2022	ret = 0;
2023out:
2024	free(argv0_str);
2025	argv_free(argv);
2026	return ret;
2027}
2028
2029/* Compose only probe arg */
2030char *synthesize_perf_probe_arg(struct perf_probe_arg *pa)
2031{
2032	struct perf_probe_arg_field *field = pa->field;
2033	struct strbuf buf;
2034	char *ret = NULL;
2035	int err;
2036
2037	if (strbuf_init(&buf, 64) < 0)
2038		return NULL;
2039
2040	if (pa->name && pa->var)
2041		err = strbuf_addf(&buf, "%s=%s", pa->name, pa->var);
2042	else
2043		err = strbuf_addstr(&buf, pa->name ?: pa->var);
2044	if (err)
2045		goto out;
2046
2047	while (field) {
2048		if (field->name[0] == '[')
2049			err = strbuf_addstr(&buf, field->name);
2050		else
2051			err = strbuf_addf(&buf, "%s%s", field->ref ? "->" : ".",
2052					  field->name);
2053		field = field->next;
2054		if (err)
2055			goto out;
2056	}
2057
2058	if (pa->type)
2059		if (strbuf_addf(&buf, ":%s", pa->type) < 0)
2060			goto out;
2061
2062	ret = strbuf_detach(&buf, NULL);
2063out:
2064	strbuf_release(&buf);
2065	return ret;
2066}
2067
2068/* Compose only probe point (not argument) */
2069static char *synthesize_perf_probe_point(struct perf_probe_point *pp)
2070{
2071	struct strbuf buf;
2072	char *tmp, *ret = NULL;
2073	int len, err = 0;
2074
2075	if (strbuf_init(&buf, 64) < 0)
2076		return NULL;
2077
2078	if (pp->function) {
2079		if (strbuf_addstr(&buf, pp->function) < 0)
2080			goto out;
2081		if (pp->offset)
2082			err = strbuf_addf(&buf, "+%lu", pp->offset);
2083		else if (pp->line)
2084			err = strbuf_addf(&buf, ":%d", pp->line);
2085		else if (pp->retprobe)
2086			err = strbuf_addstr(&buf, "%return");
2087		if (err)
2088			goto out;
2089	}
2090	if (pp->file) {
2091		tmp = pp->file;
2092		len = strlen(tmp);
2093		if (len > 30) {
2094			tmp = strchr(pp->file + len - 30, '/');
2095			tmp = tmp ? tmp + 1 : pp->file + len - 30;
2096		}
2097		err = strbuf_addf(&buf, "@%s", tmp);
2098		if (!err && !pp->function && pp->line)
2099			err = strbuf_addf(&buf, ":%d", pp->line);
2100	}
2101	if (!err)
2102		ret = strbuf_detach(&buf, NULL);
2103out:
2104	strbuf_release(&buf);
2105	return ret;
2106}
2107
2108char *synthesize_perf_probe_command(struct perf_probe_event *pev)
2109{
2110	struct strbuf buf;
2111	char *tmp, *ret = NULL;
2112	int i;
2113
2114	if (strbuf_init(&buf, 64))
2115		return NULL;
2116	if (pev->event)
2117		if (strbuf_addf(&buf, "%s:%s=", pev->group ?: PERFPROBE_GROUP,
2118				pev->event) < 0)
2119			goto out;
2120
2121	tmp = synthesize_perf_probe_point(&pev->point);
2122	if (!tmp || strbuf_addstr(&buf, tmp) < 0) {
2123		free(tmp);
2124		goto out;
2125	}
2126	free(tmp);
2127
2128	for (i = 0; i < pev->nargs; i++) {
2129		tmp = synthesize_perf_probe_arg(pev->args + i);
2130		if (!tmp || strbuf_addf(&buf, " %s", tmp) < 0) {
2131			free(tmp);
2132			goto out;
2133		}
2134		free(tmp);
2135	}
2136
2137	ret = strbuf_detach(&buf, NULL);
2138out:
2139	strbuf_release(&buf);
2140	return ret;
2141}
2142
2143static int __synthesize_probe_trace_arg_ref(struct probe_trace_arg_ref *ref,
2144					    struct strbuf *buf, int depth)
2145{
2146	int err;
2147	if (ref->next) {
2148		depth = __synthesize_probe_trace_arg_ref(ref->next, buf,
2149							 depth + 1);
2150		if (depth < 0)
2151			return depth;
2152	}
2153	if (ref->user_access)
2154		err = strbuf_addf(buf, "%s%ld(", "+u", ref->offset);
2155	else
2156		err = strbuf_addf(buf, "%+ld(", ref->offset);
2157	return (err < 0) ? err : depth;
2158}
2159
2160static int synthesize_probe_trace_arg(struct probe_trace_arg *arg,
2161				      struct strbuf *buf)
2162{
2163	struct probe_trace_arg_ref *ref = arg->ref;
2164	int depth = 0, err;
2165
2166	/* Argument name or separator */
2167	if (arg->name)
2168		err = strbuf_addf(buf, " %s=", arg->name);
2169	else
2170		err = strbuf_addch(buf, ' ');
2171	if (err)
2172		return err;
2173
2174	/* Special case: @XXX */
2175	if (arg->value[0] == '@' && arg->ref)
2176			ref = ref->next;
2177
2178	/* Dereferencing arguments */
2179	if (ref) {
2180		depth = __synthesize_probe_trace_arg_ref(ref, buf, 1);
2181		if (depth < 0)
2182			return depth;
2183	}
2184
2185	/* Print argument value */
2186	if (arg->value[0] == '@' && arg->ref)
2187		err = strbuf_addf(buf, "%s%+ld", arg->value, arg->ref->offset);
2188	else
2189		err = strbuf_addstr(buf, arg->value);
2190
2191	/* Closing */
2192	while (!err && depth--)
2193		err = strbuf_addch(buf, ')');
2194
2195	/* Print argument type */
2196	if (!err && arg->type)
2197		err = strbuf_addf(buf, ":%s", arg->type);
2198
2199	return err;
2200}
2201
2202static int
2203synthesize_probe_trace_args(struct probe_trace_event *tev, struct strbuf *buf)
2204{
2205	int i, ret = 0;
2206
2207	for (i = 0; i < tev->nargs && ret >= 0; i++)
2208		ret = synthesize_probe_trace_arg(&tev->args[i], buf);
2209
2210	return ret;
2211}
2212
2213static int
2214synthesize_uprobe_trace_def(struct probe_trace_point *tp, struct strbuf *buf)
2215{
2216	int err;
2217
2218	/* Uprobes must have tp->module */
2219	if (!tp->module)
2220		return -EINVAL;
2221	/*
2222	 * If tp->address == 0, then this point must be a
2223	 * absolute address uprobe.
2224	 * try_to_find_absolute_address() should have made
2225	 * tp->symbol to "0x0".
2226	 */
2227	if (!tp->address && (!tp->symbol || strcmp(tp->symbol, "0x0")))
2228		return -EINVAL;
2229
2230	/* Use the tp->address for uprobes */
2231	err = strbuf_addf(buf, "%s:0x%" PRIx64, tp->module, tp->address);
2232
2233	if (err >= 0 && tp->ref_ctr_offset) {
2234		if (!uprobe_ref_ctr_is_supported())
2235			return -EINVAL;
2236		err = strbuf_addf(buf, "(0x%lx)", tp->ref_ctr_offset);
2237	}
2238	return err >= 0 ? 0 : err;
2239}
2240
2241static int
2242synthesize_kprobe_trace_def(struct probe_trace_point *tp, struct strbuf *buf)
2243{
2244	if (!strncmp(tp->symbol, "0x", 2)) {
2245		/* Absolute address. See try_to_find_absolute_address() */
2246		return strbuf_addf(buf, "%s%s0x%" PRIx64, tp->module ?: "",
2247				  tp->module ? ":" : "", tp->address);
2248	} else {
2249		return strbuf_addf(buf, "%s%s%s+%lu", tp->module ?: "",
2250				tp->module ? ":" : "", tp->symbol, tp->offset);
2251	}
2252}
2253
2254char *synthesize_probe_trace_command(struct probe_trace_event *tev)
2255{
2256	struct probe_trace_point *tp = &tev->point;
2257	struct strbuf buf;
2258	char *ret = NULL;
2259	int err;
2260
2261	if (strbuf_init(&buf, 32) < 0)
2262		return NULL;
2263
2264	if (strbuf_addf(&buf, "%c:%s/%s ", tp->retprobe ? 'r' : 'p',
2265			tev->group, tev->event) < 0)
2266		goto error;
2267
2268	if (tev->uprobes)
2269		err = synthesize_uprobe_trace_def(tp, &buf);
2270	else
2271		err = synthesize_kprobe_trace_def(tp, &buf);
2272
2273	if (err >= 0)
2274		err = synthesize_probe_trace_args(tev, &buf);
2275
2276	if (err >= 0)
2277		ret = strbuf_detach(&buf, NULL);
2278error:
2279	strbuf_release(&buf);
2280	return ret;
2281}
2282
2283static int find_perf_probe_point_from_map(struct probe_trace_point *tp,
2284					  struct perf_probe_point *pp,
2285					  bool is_kprobe)
2286{
2287	struct symbol *sym = NULL;
2288	struct map *map = NULL;
2289	u64 addr = tp->address;
2290	int ret = -ENOENT;
2291
2292	if (!is_kprobe) {
2293		map = dso__new_map(tp->module);
2294		if (!map)
2295			goto out;
2296		sym = map__find_symbol(map, addr);
2297	} else {
2298		if (tp->symbol && !addr) {
2299			if (kernel_get_symbol_address_by_name(tp->symbol,
2300						&addr, true, false) < 0)
2301				goto out;
2302		}
2303		if (addr) {
2304			addr += tp->offset;
2305			sym = machine__find_kernel_symbol(host_machine, addr, &map);
2306		}
2307	}
2308
2309	if (!sym)
2310		goto out;
2311
2312	pp->retprobe = tp->retprobe;
2313	pp->offset = addr - map__unmap_ip(map, sym->start);
2314	pp->function = strdup(sym->name);
2315	ret = pp->function ? 0 : -ENOMEM;
2316
2317out:
2318	map__put(map);
2319
2320	return ret;
2321}
2322
2323static int convert_to_perf_probe_point(struct probe_trace_point *tp,
2324				       struct perf_probe_point *pp,
2325				       bool is_kprobe)
2326{
2327	char buf[128];
2328	int ret;
2329
2330	ret = find_perf_probe_point_from_dwarf(tp, pp, is_kprobe);
2331	if (!ret)
2332		return 0;
2333	ret = find_perf_probe_point_from_map(tp, pp, is_kprobe);
2334	if (!ret)
2335		return 0;
2336
2337	pr_debug("Failed to find probe point from both of dwarf and map.\n");
2338
2339	if (tp->symbol) {
2340		pp->function = strdup(tp->symbol);
2341		pp->offset = tp->offset;
2342	} else {
2343		ret = e_snprintf(buf, 128, "0x%" PRIx64, tp->address);
2344		if (ret < 0)
2345			return ret;
2346		pp->function = strdup(buf);
2347		pp->offset = 0;
2348	}
2349	if (pp->function == NULL)
2350		return -ENOMEM;
2351
2352	pp->retprobe = tp->retprobe;
2353
2354	return 0;
2355}
2356
2357static int convert_to_perf_probe_event(struct probe_trace_event *tev,
2358			       struct perf_probe_event *pev, bool is_kprobe)
2359{
2360	struct strbuf buf = STRBUF_INIT;
2361	int i, ret;
2362
2363	/* Convert event/group name */
2364	pev->event = strdup(tev->event);
2365	pev->group = strdup(tev->group);
2366	if (pev->event == NULL || pev->group == NULL)
2367		return -ENOMEM;
2368
2369	/* Convert trace_point to probe_point */
2370	ret = convert_to_perf_probe_point(&tev->point, &pev->point, is_kprobe);
2371	if (ret < 0)
2372		return ret;
2373
2374	/* Convert trace_arg to probe_arg */
2375	pev->nargs = tev->nargs;
2376	pev->args = zalloc(sizeof(struct perf_probe_arg) * pev->nargs);
2377	if (pev->args == NULL)
2378		return -ENOMEM;
2379	for (i = 0; i < tev->nargs && ret >= 0; i++) {
2380		if (tev->args[i].name)
2381			pev->args[i].name = strdup(tev->args[i].name);
2382		else {
2383			if ((ret = strbuf_init(&buf, 32)) < 0)
2384				goto error;
2385			ret = synthesize_probe_trace_arg(&tev->args[i], &buf);
2386			pev->args[i].name = strbuf_detach(&buf, NULL);
2387		}
2388		if (pev->args[i].name == NULL && ret >= 0)
2389			ret = -ENOMEM;
2390	}
2391error:
2392	if (ret < 0)
2393		clear_perf_probe_event(pev);
2394
2395	return ret;
2396}
2397
2398void clear_perf_probe_event(struct perf_probe_event *pev)
2399{
2400	struct perf_probe_arg_field *field, *next;
2401	int i;
2402
2403	zfree(&pev->event);
2404	zfree(&pev->group);
2405	zfree(&pev->target);
2406	clear_perf_probe_point(&pev->point);
2407
2408	for (i = 0; i < pev->nargs; i++) {
2409		zfree(&pev->args[i].name);
2410		zfree(&pev->args[i].var);
2411		zfree(&pev->args[i].type);
2412		field = pev->args[i].field;
2413		while (field) {
2414			next = field->next;
2415			zfree(&field->name);
2416			free(field);
2417			field = next;
2418		}
2419	}
2420	pev->nargs = 0;
2421	zfree(&pev->args);
2422	nsinfo__zput(pev->nsi);
2423}
2424
2425#define strdup_or_goto(str, label)	\
2426({ char *__p = NULL; if (str && !(__p = strdup(str))) goto label; __p; })
2427
2428static int perf_probe_point__copy(struct perf_probe_point *dst,
2429				  struct perf_probe_point *src)
2430{
2431	dst->file = strdup_or_goto(src->file, out_err);
2432	dst->function = strdup_or_goto(src->function, out_err);
2433	dst->lazy_line = strdup_or_goto(src->lazy_line, out_err);
2434	dst->line = src->line;
2435	dst->retprobe = src->retprobe;
2436	dst->offset = src->offset;
2437	return 0;
2438
2439out_err:
2440	clear_perf_probe_point(dst);
2441	return -ENOMEM;
2442}
2443
2444static int perf_probe_arg__copy(struct perf_probe_arg *dst,
2445				struct perf_probe_arg *src)
2446{
2447	struct perf_probe_arg_field *field, **ppfield;
2448
2449	dst->name = strdup_or_goto(src->name, out_err);
2450	dst->var = strdup_or_goto(src->var, out_err);
2451	dst->type = strdup_or_goto(src->type, out_err);
2452
2453	field = src->field;
2454	ppfield = &(dst->field);
2455	while (field) {
2456		*ppfield = zalloc(sizeof(*field));
2457		if (!*ppfield)
2458			goto out_err;
2459		(*ppfield)->name = strdup_or_goto(field->name, out_err);
2460		(*ppfield)->index = field->index;
2461		(*ppfield)->ref = field->ref;
2462		field = field->next;
2463		ppfield = &((*ppfield)->next);
2464	}
2465	return 0;
2466out_err:
2467	return -ENOMEM;
2468}
2469
2470int perf_probe_event__copy(struct perf_probe_event *dst,
2471			   struct perf_probe_event *src)
2472{
2473	int i;
2474
2475	dst->event = strdup_or_goto(src->event, out_err);
2476	dst->group = strdup_or_goto(src->group, out_err);
2477	dst->target = strdup_or_goto(src->target, out_err);
2478	dst->uprobes = src->uprobes;
2479
2480	if (perf_probe_point__copy(&dst->point, &src->point) < 0)
2481		goto out_err;
2482
2483	dst->args = zalloc(sizeof(struct perf_probe_arg) * src->nargs);
2484	if (!dst->args)
2485		goto out_err;
2486	dst->nargs = src->nargs;
2487
2488	for (i = 0; i < src->nargs; i++)
2489		if (perf_probe_arg__copy(&dst->args[i], &src->args[i]) < 0)
2490			goto out_err;
2491	return 0;
2492
2493out_err:
2494	clear_perf_probe_event(dst);
2495	return -ENOMEM;
2496}
2497
2498void clear_probe_trace_event(struct probe_trace_event *tev)
2499{
2500	struct probe_trace_arg_ref *ref, *next;
2501	int i;
2502
2503	zfree(&tev->event);
2504	zfree(&tev->group);
2505	zfree(&tev->point.symbol);
2506	zfree(&tev->point.realname);
2507	zfree(&tev->point.module);
2508	for (i = 0; i < tev->nargs; i++) {
2509		zfree(&tev->args[i].name);
2510		zfree(&tev->args[i].value);
2511		zfree(&tev->args[i].type);
2512		ref = tev->args[i].ref;
2513		while (ref) {
2514			next = ref->next;
2515			free(ref);
2516			ref = next;
2517		}
2518	}
2519	zfree(&tev->args);
2520	tev->nargs = 0;
2521}
2522
2523struct kprobe_blacklist_node {
2524	struct list_head list;
2525	u64 start;
2526	u64 end;
2527	char *symbol;
2528};
2529
2530static void kprobe_blacklist__delete(struct list_head *blacklist)
2531{
2532	struct kprobe_blacklist_node *node;
2533
2534	while (!list_empty(blacklist)) {
2535		node = list_first_entry(blacklist,
2536					struct kprobe_blacklist_node, list);
2537		list_del_init(&node->list);
2538		zfree(&node->symbol);
2539		free(node);
2540	}
2541}
2542
2543static int kprobe_blacklist__load(struct list_head *blacklist)
2544{
2545	struct kprobe_blacklist_node *node;
2546	const char *__debugfs = debugfs__mountpoint();
2547	char buf[PATH_MAX], *p;
2548	FILE *fp;
2549	int ret;
2550
2551	if (__debugfs == NULL)
2552		return -ENOTSUP;
2553
2554	ret = e_snprintf(buf, PATH_MAX, "%s/kprobes/blacklist", __debugfs);
2555	if (ret < 0)
2556		return ret;
2557
2558	fp = fopen(buf, "r");
2559	if (!fp)
2560		return -errno;
2561
2562	ret = 0;
2563	while (fgets(buf, PATH_MAX, fp)) {
2564		node = zalloc(sizeof(*node));
2565		if (!node) {
2566			ret = -ENOMEM;
2567			break;
2568		}
2569		INIT_LIST_HEAD(&node->list);
2570		list_add_tail(&node->list, blacklist);
2571		if (sscanf(buf, "0x%" PRIx64 "-0x%" PRIx64, &node->start, &node->end) != 2) {
2572			ret = -EINVAL;
2573			break;
2574		}
2575		p = strchr(buf, '\t');
2576		if (p) {
2577			p++;
2578			if (p[strlen(p) - 1] == '\n')
2579				p[strlen(p) - 1] = '\0';
2580		} else
2581			p = (char *)"unknown";
2582		node->symbol = strdup(p);
2583		if (!node->symbol) {
2584			ret = -ENOMEM;
2585			break;
2586		}
2587		pr_debug2("Blacklist: 0x%" PRIx64 "-0x%" PRIx64 ", %s\n",
2588			  node->start, node->end, node->symbol);
2589		ret++;
2590	}
2591	if (ret < 0)
2592		kprobe_blacklist__delete(blacklist);
2593	fclose(fp);
2594
2595	return ret;
2596}
2597
2598static struct kprobe_blacklist_node *
2599kprobe_blacklist__find_by_address(struct list_head *blacklist, u64 address)
2600{
2601	struct kprobe_blacklist_node *node;
2602
2603	list_for_each_entry(node, blacklist, list) {
2604		if (node->start <= address && address < node->end)
2605			return node;
2606	}
2607
2608	return NULL;
2609}
2610
2611static LIST_HEAD(kprobe_blacklist);
2612
2613static void kprobe_blacklist__init(void)
2614{
2615	if (!list_empty(&kprobe_blacklist))
2616		return;
2617
2618	if (kprobe_blacklist__load(&kprobe_blacklist) < 0)
2619		pr_debug("No kprobe blacklist support, ignored\n");
2620}
2621
2622static void kprobe_blacklist__release(void)
2623{
2624	kprobe_blacklist__delete(&kprobe_blacklist);
2625}
2626
2627static bool kprobe_blacklist__listed(u64 address)
2628{
2629	return !!kprobe_blacklist__find_by_address(&kprobe_blacklist, address);
2630}
2631
2632static int perf_probe_event__sprintf(const char *group, const char *event,
2633				     struct perf_probe_event *pev,
2634				     const char *module,
2635				     struct strbuf *result)
2636{
2637	int i, ret;
2638	char *buf;
2639
2640	if (asprintf(&buf, "%s:%s", group, event) < 0)
2641		return -errno;
2642	ret = strbuf_addf(result, "  %-20s (on ", buf);
2643	free(buf);
2644	if (ret)
2645		return ret;
2646
2647	/* Synthesize only event probe point */
2648	buf = synthesize_perf_probe_point(&pev->point);
2649	if (!buf)
2650		return -ENOMEM;
2651	ret = strbuf_addstr(result, buf);
2652	free(buf);
2653
2654	if (!ret && module)
2655		ret = strbuf_addf(result, " in %s", module);
2656
2657	if (!ret && pev->nargs > 0) {
2658		ret = strbuf_add(result, " with", 5);
2659		for (i = 0; !ret && i < pev->nargs; i++) {
2660			buf = synthesize_perf_probe_arg(&pev->args[i]);
2661			if (!buf)
2662				return -ENOMEM;
2663			ret = strbuf_addf(result, " %s", buf);
2664			free(buf);
2665		}
2666	}
2667	if (!ret)
2668		ret = strbuf_addch(result, ')');
2669
2670	return ret;
2671}
2672
2673/* Show an event */
2674int show_perf_probe_event(const char *group, const char *event,
2675			  struct perf_probe_event *pev,
2676			  const char *module, bool use_stdout)
2677{
2678	struct strbuf buf = STRBUF_INIT;
2679	int ret;
2680
2681	ret = perf_probe_event__sprintf(group, event, pev, module, &buf);
2682	if (ret >= 0) {
2683		if (use_stdout)
2684			printf("%s\n", buf.buf);
2685		else
2686			pr_info("%s\n", buf.buf);
2687	}
2688	strbuf_release(&buf);
2689
2690	return ret;
2691}
2692
2693static bool filter_probe_trace_event(struct probe_trace_event *tev,
2694				     struct strfilter *filter)
2695{
2696	char tmp[128];
2697
2698	/* At first, check the event name itself */
2699	if (strfilter__compare(filter, tev->event))
2700		return true;
2701
2702	/* Next, check the combination of name and group */
2703	if (e_snprintf(tmp, 128, "%s:%s", tev->group, tev->event) < 0)
2704		return false;
2705	return strfilter__compare(filter, tmp);
2706}
2707
2708static int __show_perf_probe_events(int fd, bool is_kprobe,
2709				    struct strfilter *filter)
2710{
2711	int ret = 0;
2712	struct probe_trace_event tev;
2713	struct perf_probe_event pev;
2714	struct strlist *rawlist;
2715	struct str_node *ent;
2716
2717	memset(&tev, 0, sizeof(tev));
2718	memset(&pev, 0, sizeof(pev));
2719
2720	rawlist = probe_file__get_rawlist(fd);
2721	if (!rawlist)
2722		return -ENOMEM;
2723
2724	strlist__for_each_entry(ent, rawlist) {
2725		ret = parse_probe_trace_command(ent->s, &tev);
2726		if (ret >= 0) {
2727			if (!filter_probe_trace_event(&tev, filter))
2728				goto next;
2729			ret = convert_to_perf_probe_event(&tev, &pev,
2730								is_kprobe);
2731			if (ret < 0)
2732				goto next;
2733			ret = show_perf_probe_event(pev.group, pev.event,
2734						    &pev, tev.point.module,
2735						    true);
2736		}
2737next:
2738		clear_perf_probe_event(&pev);
2739		clear_probe_trace_event(&tev);
2740		if (ret < 0)
2741			break;
2742	}
2743	strlist__delete(rawlist);
2744	/* Cleanup cached debuginfo if needed */
2745	debuginfo_cache__exit();
2746
2747	return ret;
2748}
2749
2750/* List up current perf-probe events */
2751int show_perf_probe_events(struct strfilter *filter)
2752{
2753	int kp_fd, up_fd, ret;
2754
2755	setup_pager();
2756
2757	if (probe_conf.cache)
2758		return probe_cache__show_all_caches(filter);
2759
2760	ret = init_probe_symbol_maps(false);
2761	if (ret < 0)
2762		return ret;
2763
2764	ret = probe_file__open_both(&kp_fd, &up_fd, 0);
2765	if (ret < 0)
2766		return ret;
2767
2768	if (kp_fd >= 0)
2769		ret = __show_perf_probe_events(kp_fd, true, filter);
2770	if (up_fd >= 0 && ret >= 0)
2771		ret = __show_perf_probe_events(up_fd, false, filter);
2772	if (kp_fd > 0)
2773		close(kp_fd);
2774	if (up_fd > 0)
2775		close(up_fd);
2776	exit_probe_symbol_maps();
2777
2778	return ret;
2779}
2780
2781static int get_new_event_name(char *buf, size_t len, const char *base,
2782			      struct strlist *namelist, bool ret_event,
2783			      bool allow_suffix, bool not_C_symname)
2784{
2785	int i, ret;
2786	char *p, *nbase;
2787
2788	if (*base == '.')
2789		base++;
2790	nbase = strdup(base);
2791	if (!nbase)
2792		return -ENOMEM;
2793
2794	if (not_C_symname) {
2795		/* Replace non-alnum with '_' */
2796		char *s, *d;
2797
2798		s = d = nbase;
2799		do {
2800			if (*s && !isalnum(*s)) {
2801				if (d != nbase && *(d - 1) != '_')
2802					*d++ = '_';
2803			} else
2804				*d++ = *s;
2805		} while (*s++);
2806	} else {
2807		/* Cut off the dot suffixes (e.g. .const, .isra) and version suffixes */
2808		p = strpbrk(nbase, ".@");
2809		if (p && p != nbase)
2810			*p = '\0';
2811	}
2812
2813	/* Try no suffix number */
2814	ret = e_snprintf(buf, len, "%s%s", nbase, ret_event ? "__return" : "");
2815	if (ret < 0) {
2816		pr_warning("snprintf() failed: %d; the event name '%s' is too long\n"
2817			   "  Hint: Set a shorter event with syntax \"EVENT=PROBEDEF\"\n"
2818			   "        EVENT: Event name (max length: %d bytes).\n",
2819			   ret, nbase, MAX_EVENT_NAME_LEN);
2820		goto out;
2821	}
2822	if (!strlist__has_entry(namelist, buf))
2823		goto out;
2824
2825	if (!allow_suffix) {
2826		pr_warning("Error: event \"%s\" already exists.\n"
2827			   " Hint: Remove existing event by 'perf probe -d'\n"
2828			   "       or force duplicates by 'perf probe -f'\n"
2829			   "       or set 'force=yes' in BPF source.\n",
2830			   buf);
2831		ret = -EEXIST;
2832		goto out;
2833	}
2834
2835	/* Try to add suffix */
2836	for (i = 1; i < MAX_EVENT_INDEX; i++) {
2837		ret = e_snprintf(buf, len, "%s_%d", nbase, i);
2838		if (ret < 0) {
2839			pr_warning("Add suffix failed: %d; the event name '%s' is too long\n"
2840				   "  Hint: Set a shorter event with syntax \"EVENT=PROBEDEF\"\n"
2841				   "        EVENT: Event name (max length: %d bytes).\n",
2842				   ret, nbase, MAX_EVENT_NAME_LEN);
2843			goto out;
2844		}
2845		if (!strlist__has_entry(namelist, buf))
2846			break;
2847	}
2848	if (i == MAX_EVENT_INDEX) {
2849		pr_warning("Too many events are on the same function.\n");
2850		ret = -ERANGE;
2851	}
2852
2853out:
2854	free(nbase);
2855
2856	/* Final validation */
2857	if (ret >= 0 && !is_c_func_name(buf)) {
2858		pr_warning("Internal error: \"%s\" is an invalid event name.\n",
2859			   buf);
2860		ret = -EINVAL;
2861	}
2862
2863	return ret;
2864}
2865
2866/* Warn if the current kernel's uprobe implementation is old */
2867static void warn_uprobe_event_compat(struct probe_trace_event *tev)
2868{
2869	int i;
2870	char *buf = synthesize_probe_trace_command(tev);
2871	struct probe_trace_point *tp = &tev->point;
2872
2873	if (tp->ref_ctr_offset && !uprobe_ref_ctr_is_supported()) {
2874		pr_warning("A semaphore is associated with %s:%s and "
2875			   "seems your kernel doesn't support it.\n",
2876			   tev->group, tev->event);
2877	}
2878
2879	/* Old uprobe event doesn't support memory dereference */
2880	if (!tev->uprobes || tev->nargs == 0 || !buf)
2881		goto out;
2882
2883	for (i = 0; i < tev->nargs; i++) {
2884		if (strchr(tev->args[i].value, '@')) {
2885			pr_warning("%s accesses a variable by symbol name, but that is not supported for user application probe.\n",
2886				   tev->args[i].value);
2887			break;
2888		}
2889		if (strglobmatch(tev->args[i].value, "[$+-]*")) {
2890			pr_warning("Please upgrade your kernel to at least 3.14 to have access to feature %s\n",
2891				   tev->args[i].value);
2892			break;
2893		}
2894	}
2895out:
2896	free(buf);
2897}
2898
2899/* Set new name from original perf_probe_event and namelist */
2900static int probe_trace_event__set_name(struct probe_trace_event *tev,
2901				       struct perf_probe_event *pev,
2902				       struct strlist *namelist,
2903				       bool allow_suffix)
2904{
2905	const char *event, *group;
2906	bool not_C_symname = true;
2907	char buf[MAX_EVENT_NAME_LEN];
2908	int ret;
2909
2910	/* If probe_event or trace_event already have the name, reuse it */
2911	if (pev->event && !pev->sdt)
2912		event = pev->event;
2913	else if (tev->event)
2914		event = tev->event;
2915	else {
2916		/* Or generate new one from probe point */
2917		if (pev->point.function &&
2918			(strncmp(pev->point.function, "0x", 2) != 0) &&
2919			!strisglob(pev->point.function))
2920			event = pev->point.function;
2921		else {
2922			event = tev->point.realname;
2923			not_C_symname = !is_known_C_lang(tev->lang);
2924		}
2925	}
2926	if (pev->group && !pev->sdt)
2927		group = pev->group;
2928	else if (tev->group)
2929		group = tev->group;
2930	else
2931		group = PERFPROBE_GROUP;
2932
2933	if (strlen(group) >= MAX_EVENT_NAME_LEN) {
2934		pr_err("Probe group string='%s' is too long (>= %d bytes)\n",
2935			group, MAX_EVENT_NAME_LEN);
2936		return -ENOMEM;
2937	}
2938
2939	/* Get an unused new event name */
2940	ret = get_new_event_name(buf, sizeof(buf), event, namelist,
2941				 tev->point.retprobe, allow_suffix,
2942				 not_C_symname);
2943	if (ret < 0)
2944		return ret;
2945
2946	event = buf;
2947
2948	tev->event = strdup(event);
2949	tev->group = strdup(group);
2950	if (tev->event == NULL || tev->group == NULL)
2951		return -ENOMEM;
2952
2953	/*
2954	 * Add new event name to namelist if multiprobe event is NOT
2955	 * supported, since we have to use new event name for following
2956	 * probes in that case.
2957	 */
2958	if (!multiprobe_event_is_supported())
2959		strlist__add(namelist, event);
2960	return 0;
2961}
2962
2963static int __open_probe_file_and_namelist(bool uprobe,
2964					  struct strlist **namelist)
2965{
2966	int fd;
2967
2968	fd = probe_file__open(PF_FL_RW | (uprobe ? PF_FL_UPROBE : 0));
2969	if (fd < 0)
2970		return fd;
2971
2972	/* Get current event names */
2973	*namelist = probe_file__get_namelist(fd);
2974	if (!(*namelist)) {
2975		pr_debug("Failed to get current event list.\n");
2976		close(fd);
2977		return -ENOMEM;
2978	}
2979	return fd;
2980}
2981
2982static int __add_probe_trace_events(struct perf_probe_event *pev,
2983				     struct probe_trace_event *tevs,
2984				     int ntevs, bool allow_suffix)
2985{
2986	int i, fd[2] = {-1, -1}, up, ret;
2987	struct probe_trace_event *tev = NULL;
2988	struct probe_cache *cache = NULL;
2989	struct strlist *namelist[2] = {NULL, NULL};
2990	struct nscookie nsc;
2991
2992	up = pev->uprobes ? 1 : 0;
2993	fd[up] = __open_probe_file_and_namelist(up, &namelist[up]);
2994	if (fd[up] < 0)
2995		return fd[up];
2996
2997	ret = 0;
2998	for (i = 0; i < ntevs; i++) {
2999		tev = &tevs[i];
3000		up = tev->uprobes ? 1 : 0;
3001		if (fd[up] == -1) {	/* Open the kprobe/uprobe_events */
3002			fd[up] = __open_probe_file_and_namelist(up,
3003								&namelist[up]);
3004			if (fd[up] < 0)
3005				goto close_out;
3006		}
3007		/* Skip if the symbol is out of .text or blacklisted */
3008		if (!tev->point.symbol && !pev->uprobes)
3009			continue;
3010
3011		/* Set new name for tev (and update namelist) */
3012		ret = probe_trace_event__set_name(tev, pev, namelist[up],
3013						  allow_suffix);
3014		if (ret < 0)
3015			break;
3016
3017		nsinfo__mountns_enter(pev->nsi, &nsc);
3018		ret = probe_file__add_event(fd[up], tev);
3019		nsinfo__mountns_exit(&nsc);
3020		if (ret < 0)
3021			break;
3022
3023		/*
3024		 * Probes after the first probe which comes from same
3025		 * user input are always allowed to add suffix, because
3026		 * there might be several addresses corresponding to
3027		 * one code line.
3028		 */
3029		allow_suffix = true;
3030	}
3031	if (ret == -EINVAL && pev->uprobes)
3032		warn_uprobe_event_compat(tev);
3033	if (ret == 0 && probe_conf.cache) {
3034		cache = probe_cache__new(pev->target, pev->nsi);
3035		if (!cache ||
3036		    probe_cache__add_entry(cache, pev, tevs, ntevs) < 0 ||
3037		    probe_cache__commit(cache) < 0)
3038			pr_warning("Failed to add event to probe cache\n");
3039		probe_cache__delete(cache);
3040	}
3041
3042close_out:
3043	for (up = 0; up < 2; up++) {
3044		strlist__delete(namelist[up]);
3045		if (fd[up] >= 0)
3046			close(fd[up]);
3047	}
3048	return ret;
3049}
3050
3051static int find_probe_functions(struct map *map, char *name,
3052				struct symbol **syms)
3053{
3054	int found = 0;
3055	struct symbol *sym;
3056	struct rb_node *tmp;
3057	const char *norm, *ver;
3058	char *buf = NULL;
3059	bool cut_version = true;
3060
3061	if (map__load(map) < 0)
3062		return -EACCES;	/* Possible permission error to load symbols */
3063
3064	/* If user gives a version, don't cut off the version from symbols */
3065	if (strchr(name, '@'))
3066		cut_version = false;
3067
3068	map__for_each_symbol(map, sym, tmp) {
3069		norm = arch__normalize_symbol_name(sym->name);
3070		if (!norm)
3071			continue;
3072
3073		if (cut_version) {
3074			/* We don't care about default symbol or not */
3075			ver = strchr(norm, '@');
3076			if (ver) {
3077				buf = strndup(norm, ver - norm);
3078				if (!buf)
3079					return -ENOMEM;
3080				norm = buf;
3081			}
3082		}
3083
3084		if (strglobmatch(norm, name)) {
3085			found++;
3086			if (syms && found < probe_conf.max_probes)
3087				syms[found - 1] = sym;
3088		}
3089		if (buf)
3090			zfree(&buf);
3091	}
3092
3093	return found;
3094}
3095
3096void __weak arch__fix_tev_from_maps(struct perf_probe_event *pev __maybe_unused,
3097				struct probe_trace_event *tev __maybe_unused,
3098				struct map *map __maybe_unused,
3099				struct symbol *sym __maybe_unused) { }
3100
3101
3102static void pr_kallsyms_access_error(void)
3103{
3104	pr_err("Please ensure you can read the /proc/kallsyms symbol addresses.\n"
3105	       "If /proc/sys/kernel/kptr_restrict is '2', you can not read\n"
3106	       "kernel symbol addresses even if you are a superuser. Please change\n"
3107	       "it to '1'. If kptr_restrict is '1', the superuser can read the\n"
3108	       "symbol addresses.\n"
3109	       "In that case, please run this command again with sudo.\n");
3110}
3111
3112/*
3113 * Find probe function addresses from map.
3114 * Return an error or the number of found probe_trace_event
3115 */
3116static int find_probe_trace_events_from_map(struct perf_probe_event *pev,
3117					    struct probe_trace_event **tevs)
3118{
3119	struct map *map = NULL;
3120	struct ref_reloc_sym *reloc_sym = NULL;
3121	struct symbol *sym;
3122	struct symbol **syms = NULL;
3123	struct probe_trace_event *tev;
3124	struct perf_probe_point *pp = &pev->point;
3125	struct probe_trace_point *tp;
3126	int num_matched_functions;
3127	int ret, i, j, skipped = 0;
3128	char *mod_name;
3129
3130	map = get_target_map(pev->target, pev->nsi, pev->uprobes);
3131	if (!map) {
3132		ret = -EINVAL;
3133		goto out;
3134	}
3135
3136	syms = malloc(sizeof(struct symbol *) * probe_conf.max_probes);
3137	if (!syms) {
3138		ret = -ENOMEM;
3139		goto out;
3140	}
3141
3142	/*
3143	 * Load matched symbols: Since the different local symbols may have
3144	 * same name but different addresses, this lists all the symbols.
3145	 */
3146	num_matched_functions = find_probe_functions(map, pp->function, syms);
3147	if (num_matched_functions <= 0) {
3148		if (num_matched_functions == -EACCES) {
3149			pr_err("Failed to load symbols from %s\n",
3150			       pev->target ?: "/proc/kallsyms");
3151			if (pev->target)
3152				pr_err("Please ensure the file is not stripped.\n");
3153			else
3154				pr_kallsyms_access_error();
3155		} else
3156			pr_err("Failed to find symbol %s in %s\n", pp->function,
3157				pev->target ? : "kernel");
3158		ret = -ENOENT;
3159		goto out;
3160	} else if (num_matched_functions > probe_conf.max_probes) {
3161		pr_err("Too many functions matched in %s\n",
3162			pev->target ? : "kernel");
3163		ret = -E2BIG;
3164		goto out;
3165	}
3166
3167	/* Note that the symbols in the kmodule are not relocated */
3168	if (!pev->uprobes && !pev->target &&
3169			(!pp->retprobe || kretprobe_offset_is_supported())) {
3170		reloc_sym = kernel_get_ref_reloc_sym(NULL);
3171		if (!reloc_sym) {
3172			pr_warning("Relocated base symbol is not found! "
3173				   "Check /proc/sys/kernel/kptr_restrict\n"
3174				   "and /proc/sys/kernel/perf_event_paranoid. "
3175				   "Or run as privileged perf user.\n\n");
3176			ret = -EINVAL;
3177			goto out;
3178		}
3179	}
3180
3181	/* Setup result trace-probe-events */
3182	*tevs = zalloc(sizeof(*tev) * num_matched_functions);
3183	if (!*tevs) {
3184		ret = -ENOMEM;
3185		goto out;
3186	}
3187
3188	ret = 0;
3189
3190	for (j = 0; j < num_matched_functions; j++) {
3191		sym = syms[j];
3192
3193		if (sym->type != STT_FUNC)
3194			continue;
3195
3196		/* There can be duplicated symbols in the map */
3197		for (i = 0; i < j; i++)
3198			if (sym->start == syms[i]->start) {
3199				pr_debug("Found duplicated symbol %s @ %" PRIx64 "\n",
3200					 sym->name, sym->start);
3201				break;
3202			}
3203		if (i != j)
3204			continue;
3205
3206		tev = (*tevs) + ret;
3207		tp = &tev->point;
3208		if (ret == num_matched_functions) {
3209			pr_warning("Too many symbols are listed. Skip it.\n");
3210			break;
3211		}
3212		ret++;
3213
3214		if (pp->offset > sym->end - sym->start) {
3215			pr_warning("Offset %ld is bigger than the size of %s\n",
3216				   pp->offset, sym->name);
3217			ret = -ENOENT;
3218			goto err_out;
3219		}
3220		/* Add one probe point */
3221		tp->address = map__unmap_ip(map, sym->start) + pp->offset;
3222
3223		/* Check the kprobe (not in module) is within .text  */
3224		if (!pev->uprobes && !pev->target &&
3225		    kprobe_warn_out_range(sym->name, tp->address)) {
3226			tp->symbol = NULL;	/* Skip it */
3227			skipped++;
3228		} else if (reloc_sym) {
3229			tp->symbol = strdup_or_goto(reloc_sym->name, nomem_out);
3230			tp->offset = tp->address - reloc_sym->addr;
3231		} else {
3232			tp->symbol = strdup_or_goto(sym->name, nomem_out);
3233			tp->offset = pp->offset;
3234		}
3235		tp->realname = strdup_or_goto(sym->name, nomem_out);
3236
3237		tp->retprobe = pp->retprobe;
3238		if (pev->target) {
3239			if (pev->uprobes) {
3240				tev->point.module = strdup_or_goto(pev->target,
3241								   nomem_out);
3242			} else {
3243				mod_name = find_module_name(pev->target);
3244				tev->point.module =
3245					strdup(mod_name ? mod_name : pev->target);
3246				free(mod_name);
3247				if (!tev->point.module)
3248					goto nomem_out;
3249			}
3250		}
3251		tev->uprobes = pev->uprobes;
3252		tev->nargs = pev->nargs;
3253		if (tev->nargs) {
3254			tev->args = zalloc(sizeof(struct probe_trace_arg) *
3255					   tev->nargs);
3256			if (tev->args == NULL)
3257				goto nomem_out;
3258		}
3259		for (i = 0; i < tev->nargs; i++) {
3260			if (pev->args[i].name)
3261				tev->args[i].name =
3262					strdup_or_goto(pev->args[i].name,
3263							nomem_out);
3264
3265			tev->args[i].value = strdup_or_goto(pev->args[i].var,
3266							    nomem_out);
3267			if (pev->args[i].type)
3268				tev->args[i].type =
3269					strdup_or_goto(pev->args[i].type,
3270							nomem_out);
3271		}
3272		arch__fix_tev_from_maps(pev, tev, map, sym);
3273	}
3274	if (ret == skipped) {
3275		ret = -ENOENT;
3276		goto err_out;
3277	}
3278
3279out:
3280	map__put(map);
3281	free(syms);
3282	return ret;
3283
3284nomem_out:
3285	ret = -ENOMEM;
3286err_out:
3287	clear_probe_trace_events(*tevs, num_matched_functions);
3288	zfree(tevs);
3289	goto out;
3290}
3291
3292static int try_to_find_absolute_address(struct perf_probe_event *pev,
3293					struct probe_trace_event **tevs)
3294{
3295	struct perf_probe_point *pp = &pev->point;
3296	struct probe_trace_event *tev;
3297	struct probe_trace_point *tp;
3298	int i, err;
3299
3300	if (!(pev->point.function && !strncmp(pev->point.function, "0x", 2)))
3301		return -EINVAL;
3302	if (perf_probe_event_need_dwarf(pev))
3303		return -EINVAL;
3304
3305	/*
3306	 * This is 'perf probe /lib/libc.so 0xabcd'. Try to probe at
3307	 * absolute address.
3308	 *
3309	 * Only one tev can be generated by this.
3310	 */
3311	*tevs = zalloc(sizeof(*tev));
3312	if (!*tevs)
3313		return -ENOMEM;
3314
3315	tev = *tevs;
3316	tp = &tev->point;
3317
3318	/*
3319	 * Don't use tp->offset, use address directly, because
3320	 * in synthesize_probe_trace_command() address cannot be
3321	 * zero.
3322	 */
3323	tp->address = pev->point.abs_address;
3324	tp->retprobe = pp->retprobe;
3325	tev->uprobes = pev->uprobes;
3326
3327	err = -ENOMEM;
3328	/*
3329	 * Give it a '0x' leading symbol name.
3330	 * In __add_probe_trace_events, a NULL symbol is interpreted as
3331	 * invalid.
3332	 */
3333	if (asprintf(&tp->symbol, "0x%" PRIx64, tp->address) < 0)
3334		goto errout;
3335
3336	/* For kprobe, check range */
3337	if ((!tev->uprobes) &&
3338	    (kprobe_warn_out_range(tev->point.symbol,
3339				   tev->point.address))) {
3340		err = -EACCES;
3341		goto errout;
3342	}
3343
3344	if (asprintf(&tp->realname, "abs_%" PRIx64, tp->address) < 0)
3345		goto errout;
3346
3347	if (pev->target) {
3348		tp->module = strdup(pev->target);
3349		if (!tp->module)
3350			goto errout;
3351	}
3352
3353	if (tev->group) {
3354		tev->group = strdup(pev->group);
3355		if (!tev->group)
3356			goto errout;
3357	}
3358
3359	if (pev->event) {
3360		tev->event = strdup(pev->event);
3361		if (!tev->event)
3362			goto errout;
3363	}
3364
3365	tev->nargs = pev->nargs;
3366	tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
3367	if (!tev->args)
3368		goto errout;
3369
3370	for (i = 0; i < tev->nargs; i++)
3371		copy_to_probe_trace_arg(&tev->args[i], &pev->args[i]);
3372
3373	return 1;
3374
3375errout:
3376	clear_probe_trace_events(*tevs, 1);
3377	*tevs = NULL;
3378	return err;
3379}
3380
3381/* Concatenate two arrays */
3382static void *memcat(void *a, size_t sz_a, void *b, size_t sz_b)
3383{
3384	void *ret;
3385
3386	ret = malloc(sz_a + sz_b);
3387	if (ret) {
3388		memcpy(ret, a, sz_a);
3389		memcpy(ret + sz_a, b, sz_b);
3390	}
3391	return ret;
3392}
3393
3394static int
3395concat_probe_trace_events(struct probe_trace_event **tevs, int *ntevs,
3396			  struct probe_trace_event **tevs2, int ntevs2)
3397{
3398	struct probe_trace_event *new_tevs;
3399	int ret = 0;
3400
3401	if (*ntevs == 0) {
3402		*tevs = *tevs2;
3403		*ntevs = ntevs2;
3404		*tevs2 = NULL;
3405		return 0;
3406	}
3407
3408	if (*ntevs + ntevs2 > probe_conf.max_probes)
3409		ret = -E2BIG;
3410	else {
3411		/* Concatenate the array of probe_trace_event */
3412		new_tevs = memcat(*tevs, (*ntevs) * sizeof(**tevs),
3413				  *tevs2, ntevs2 * sizeof(**tevs2));
3414		if (!new_tevs)
3415			ret = -ENOMEM;
3416		else {
3417			free(*tevs);
3418			*tevs = new_tevs;
3419			*ntevs += ntevs2;
3420		}
3421	}
3422	if (ret < 0)
3423		clear_probe_trace_events(*tevs2, ntevs2);
3424	zfree(tevs2);
3425
3426	return ret;
3427}
3428
3429/*
3430 * Try to find probe_trace_event from given probe caches. Return the number
3431 * of cached events found, if an error occurs return the error.
3432 */
3433static int find_cached_events(struct perf_probe_event *pev,
3434			      struct probe_trace_event **tevs,
3435			      const char *target)
3436{
3437	struct probe_cache *cache;
3438	struct probe_cache_entry *entry;
3439	struct probe_trace_event *tmp_tevs = NULL;
3440	int ntevs = 0;
3441	int ret = 0;
3442
3443	cache = probe_cache__new(target, pev->nsi);
3444	/* Return 0 ("not found") if the target has no probe cache. */
3445	if (!cache)
3446		return 0;
3447
3448	for_each_probe_cache_entry(entry, cache) {
3449		/* Skip the cache entry which has no name */
3450		if (!entry->pev.event || !entry->pev.group)
3451			continue;
3452		if ((!pev->group || strglobmatch(entry->pev.group, pev->group)) &&
3453		    strglobmatch(entry->pev.event, pev->event)) {
3454			ret = probe_cache_entry__get_event(entry, &tmp_tevs);
3455			if (ret > 0)
3456				ret = concat_probe_trace_events(tevs, &ntevs,
3457								&tmp_tevs, ret);
3458			if (ret < 0)
3459				break;
3460		}
3461	}
3462	probe_cache__delete(cache);
3463	if (ret < 0) {
3464		clear_probe_trace_events(*tevs, ntevs);
3465		zfree(tevs);
3466	} else {
3467		ret = ntevs;
3468		if (ntevs > 0 && target && target[0] == '/')
3469			pev->uprobes = true;
3470	}
3471
3472	return ret;
3473}
3474
3475/* Try to find probe_trace_event from all probe caches */
3476static int find_cached_events_all(struct perf_probe_event *pev,
3477				   struct probe_trace_event **tevs)
3478{
3479	struct probe_trace_event *tmp_tevs = NULL;
3480	struct strlist *bidlist;
3481	struct str_node *nd;
3482	char *pathname;
3483	int ntevs = 0;
3484	int ret;
3485
3486	/* Get the buildid list of all valid caches */
3487	bidlist = build_id_cache__list_all(true);
3488	if (!bidlist) {
3489		ret = -errno;
3490		pr_debug("Failed to get buildids: %d\n", ret);
3491		return ret;
3492	}
3493
3494	ret = 0;
3495	strlist__for_each_entry(nd, bidlist) {
3496		pathname = build_id_cache__origname(nd->s);
3497		ret = find_cached_events(pev, &tmp_tevs, pathname);
3498		/* In the case of cnt == 0, we just skip it */
3499		if (ret > 0)
3500			ret = concat_probe_trace_events(tevs, &ntevs,
3501							&tmp_tevs, ret);
3502		free(pathname);
3503		if (ret < 0)
3504			break;
3505	}
3506	strlist__delete(bidlist);
3507
3508	if (ret < 0) {
3509		clear_probe_trace_events(*tevs, ntevs);
3510		zfree(tevs);
3511	} else
3512		ret = ntevs;
3513
3514	return ret;
3515}
3516
3517static int find_probe_trace_events_from_cache(struct perf_probe_event *pev,
3518					      struct probe_trace_event **tevs)
3519{
3520	struct probe_cache *cache;
3521	struct probe_cache_entry *entry;
3522	struct probe_trace_event *tev;
3523	struct str_node *node;
3524	int ret, i;
3525
3526	if (pev->sdt) {
3527		/* For SDT/cached events, we use special search functions */
3528		if (!pev->target)
3529			return find_cached_events_all(pev, tevs);
3530		else
3531			return find_cached_events(pev, tevs, pev->target);
3532	}
3533	cache = probe_cache__new(pev->target, pev->nsi);
3534	if (!cache)
3535		return 0;
3536
3537	entry = probe_cache__find(cache, pev);
3538	if (!entry) {
3539		/* SDT must be in the cache */
3540		ret = pev->sdt ? -ENOENT : 0;
3541		goto out;
3542	}
3543
3544	ret = strlist__nr_entries(entry->tevlist);
3545	if (ret > probe_conf.max_probes) {
3546		pr_debug("Too many entries matched in the cache of %s\n",
3547			 pev->target ? : "kernel");
3548		ret = -E2BIG;
3549		goto out;
3550	}
3551
3552	*tevs = zalloc(ret * sizeof(*tev));
3553	if (!*tevs) {
3554		ret = -ENOMEM;
3555		goto out;
3556	}
3557
3558	i = 0;
3559	strlist__for_each_entry(node, entry->tevlist) {
3560		tev = &(*tevs)[i++];
3561		ret = parse_probe_trace_command(node->s, tev);
3562		if (ret < 0)
3563			goto out;
3564		/* Set the uprobes attribute as same as original */
3565		tev->uprobes = pev->uprobes;
3566	}
3567	ret = i;
3568
3569out:
3570	probe_cache__delete(cache);
3571	return ret;
3572}
3573
3574static int convert_to_probe_trace_events(struct perf_probe_event *pev,
3575					 struct probe_trace_event **tevs)
3576{
3577	int ret;
3578
3579	if (!pev->group && !pev->sdt) {
3580		/* Set group name if not given */
3581		if (!pev->uprobes) {
3582			pev->group = strdup(PERFPROBE_GROUP);
3583			ret = pev->group ? 0 : -ENOMEM;
3584		} else
3585			ret = convert_exec_to_group(pev->target, &pev->group);
3586		if (ret != 0) {
3587			pr_warning("Failed to make a group name.\n");
3588			return ret;
3589		}
3590	}
3591
3592	ret = try_to_find_absolute_address(pev, tevs);
3593	if (ret > 0)
3594		return ret;
3595
3596	/* At first, we need to lookup cache entry */
3597	ret = find_probe_trace_events_from_cache(pev, tevs);
3598	if (ret > 0 || pev->sdt)	/* SDT can be found only in the cache */
3599		return ret == 0 ? -ENOENT : ret; /* Found in probe cache */
3600
3601	/* Convert perf_probe_event with debuginfo */
3602	ret = try_to_find_probe_trace_events(pev, tevs);
3603	if (ret != 0)
3604		return ret;	/* Found in debuginfo or got an error */
3605
3606	return find_probe_trace_events_from_map(pev, tevs);
3607}
3608
3609int convert_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3610{
3611	int i, ret;
3612
3613	/* Loop 1: convert all events */
3614	for (i = 0; i < npevs; i++) {
3615		/* Init kprobe blacklist if needed */
3616		if (!pevs[i].uprobes)
3617			kprobe_blacklist__init();
3618		/* Convert with or without debuginfo */
3619		ret  = convert_to_probe_trace_events(&pevs[i], &pevs[i].tevs);
3620		if (ret < 0)
3621			return ret;
3622		pevs[i].ntevs = ret;
3623	}
3624	/* This just release blacklist only if allocated */
3625	kprobe_blacklist__release();
3626
3627	return 0;
3628}
3629
3630static int show_probe_trace_event(struct probe_trace_event *tev)
3631{
3632	char *buf = synthesize_probe_trace_command(tev);
3633
3634	if (!buf) {
3635		pr_debug("Failed to synthesize probe trace event.\n");
3636		return -EINVAL;
3637	}
3638
3639	/* Showing definition always go stdout */
3640	printf("%s\n", buf);
3641	free(buf);
3642
3643	return 0;
3644}
3645
3646int show_probe_trace_events(struct perf_probe_event *pevs, int npevs)
3647{
3648	struct strlist *namelist = strlist__new(NULL, NULL);
3649	struct probe_trace_event *tev;
3650	struct perf_probe_event *pev;
3651	int i, j, ret = 0;
3652
3653	if (!namelist)
3654		return -ENOMEM;
3655
3656	for (j = 0; j < npevs && !ret; j++) {
3657		pev = &pevs[j];
3658		for (i = 0; i < pev->ntevs && !ret; i++) {
3659			tev = &pev->tevs[i];
3660			/* Skip if the symbol is out of .text or blacklisted */
3661			if (!tev->point.symbol && !pev->uprobes)
3662				continue;
3663
3664			/* Set new name for tev (and update namelist) */
3665			ret = probe_trace_event__set_name(tev, pev,
3666							  namelist, true);
3667			if (!ret)
3668				ret = show_probe_trace_event(tev);
3669		}
3670	}
3671	strlist__delete(namelist);
3672
3673	return ret;
3674}
3675
3676static int show_bootconfig_event(struct probe_trace_event *tev)
3677{
3678	struct probe_trace_point *tp = &tev->point;
3679	struct strbuf buf;
3680	char *ret = NULL;
3681	int err;
3682
3683	if (strbuf_init(&buf, 32) < 0)
3684		return -ENOMEM;
3685
3686	err = synthesize_kprobe_trace_def(tp, &buf);
3687	if (err >= 0)
3688		err = synthesize_probe_trace_args(tev, &buf);
3689	if (err >= 0)
3690		ret = strbuf_detach(&buf, NULL);
3691	strbuf_release(&buf);
3692
3693	if (ret) {
3694		printf("'%s'", ret);
3695		free(ret);
3696	}
3697
3698	return err;
3699}
3700
3701int show_bootconfig_events(struct perf_probe_event *pevs, int npevs)
3702{
3703	struct strlist *namelist = strlist__new(NULL, NULL);
3704	struct probe_trace_event *tev;
3705	struct perf_probe_event *pev;
3706	char *cur_name = NULL;
3707	int i, j, ret = 0;
3708
3709	if (!namelist)
3710		return -ENOMEM;
3711
3712	for (j = 0; j < npevs && !ret; j++) {
3713		pev = &pevs[j];
3714		if (pev->group && strcmp(pev->group, "probe"))
3715			pr_warning("WARN: Group name %s is ignored\n", pev->group);
3716		if (pev->uprobes) {
3717			pr_warning("ERROR: Bootconfig doesn't support uprobes\n");
3718			ret = -EINVAL;
3719			break;
3720		}
3721		for (i = 0; i < pev->ntevs && !ret; i++) {
3722			tev = &pev->tevs[i];
3723			/* Skip if the symbol is out of .text or blacklisted */
3724			if (!tev->point.symbol && !pev->uprobes)
3725				continue;
3726
3727			/* Set new name for tev (and update namelist) */
3728			ret = probe_trace_event__set_name(tev, pev,
3729							  namelist, true);
3730			if (ret)
3731				break;
3732
3733			if (!cur_name || strcmp(cur_name, tev->event)) {
3734				printf("%sftrace.event.kprobes.%s.probe = ",
3735					cur_name ? "\n" : "", tev->event);
3736				cur_name = tev->event;
3737			} else
3738				printf(", ");
3739			ret = show_bootconfig_event(tev);
3740		}
3741	}
3742	printf("\n");
3743	strlist__delete(namelist);
3744
3745	return ret;
3746}
3747
3748int apply_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3749{
3750	int i, ret = 0;
3751
3752	/* Loop 2: add all events */
3753	for (i = 0; i < npevs; i++) {
3754		ret = __add_probe_trace_events(&pevs[i], pevs[i].tevs,
3755					       pevs[i].ntevs,
3756					       probe_conf.force_add);
3757		if (ret < 0)
3758			break;
3759	}
3760	return ret;
3761}
3762
3763void cleanup_perf_probe_events(struct perf_probe_event *pevs, int npevs)
3764{
3765	int i, j;
3766	struct perf_probe_event *pev;
3767
3768	/* Loop 3: cleanup and free trace events  */
3769	for (i = 0; i < npevs; i++) {
3770		pev = &pevs[i];
3771		for (j = 0; j < pev->ntevs; j++)
3772			clear_probe_trace_event(&pev->tevs[j]);
3773		zfree(&pev->tevs);
3774		pev->ntevs = 0;
3775		clear_perf_probe_event(pev);
3776	}
3777}
3778
3779int show_available_funcs(const char *target, struct nsinfo *nsi,
3780			 struct strfilter *_filter, bool user)
3781{
3782	struct map *map;
3783	struct dso *dso;
3784	int ret;
3785
3786	ret = init_probe_symbol_maps(user);
3787	if (ret < 0)
3788		return ret;
3789
3790	/* Get a symbol map */
3791	map = get_target_map(target, nsi, user);
3792	if (!map) {
3793		pr_err("Failed to get a map for %s\n", (target) ? : "kernel");
3794		return -EINVAL;
3795	}
3796
3797	ret = map__load(map);
3798	if (ret) {
3799		if (ret == -2) {
3800			char *str = strfilter__string(_filter);
3801			pr_err("Failed to find symbols matched to \"%s\"\n",
3802			       str);
3803			free(str);
3804		} else
3805			pr_err("Failed to load symbols in %s\n",
3806			       (target) ? : "kernel");
3807		goto end;
3808	}
3809	dso = map__dso(map);
3810	dso__sort_by_name(dso);
3811
3812	/* Show all (filtered) symbols */
3813	setup_pager();
3814
3815	for (size_t i = 0; i < dso__symbol_names_len(dso); i++) {
3816		struct symbol *pos = dso__symbol_names(dso)[i];
3817
3818		if (strfilter__compare(_filter, pos->name))
3819			printf("%s\n", pos->name);
3820	}
3821end:
3822	map__put(map);
3823	exit_probe_symbol_maps();
3824
3825	return ret;
3826}
3827
3828int copy_to_probe_trace_arg(struct probe_trace_arg *tvar,
3829			    struct perf_probe_arg *pvar)
3830{
3831	tvar->value = strdup(pvar->var);
3832	if (tvar->value == NULL)
3833		return -ENOMEM;
3834	if (pvar->type) {
3835		tvar->type = strdup(pvar->type);
3836		if (tvar->type == NULL)
3837			return -ENOMEM;
3838	}
3839	if (pvar->name) {
3840		tvar->name = strdup(pvar->name);
3841		if (tvar->name == NULL)
3842			return -ENOMEM;
3843	} else
3844		tvar->name = NULL;
3845	return 0;
3846}
~/ Read-only file preview.