build-id.c 21.3 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
2 3 4 5 6 7 8 9
/*
 * build-id.c
 *
 * build-id support
 *
 * Copyright (C) 2009, 2010 Red Hat Inc.
 * Copyright (C) 2009, 2010 Arnaldo Carvalho de Melo <acme@redhat.com>
 */
10
#include "util.h" // lsdir(), mkdir_p(), rm_rf()
11
#include <dirent.h>
12
#include <errno.h>
13
#include <stdio.h>
14 15
#include <sys/stat.h>
#include <sys/types.h>
16
#include "util/copyfile.h"
17
#include "dso.h"
18 19
#include "build-id.h"
#include "event.h"
20
#include "namespaces.h"
21
#include "map.h"
22
#include "symbol.h"
23
#include "thread.h"
24
#include <linux/kernel.h>
25
#include "debug.h"
26
#include "session.h"
27
#include "tool.h"
28 29
#include "header.h"
#include "vdso.h"
30
#include "path.h"
31
#include "probe-file.h"
32
#include "strlist.h"
33

34 35 36 37
#ifdef HAVE_DEBUGINFOD_SUPPORT
#include <elfutils/debuginfod.h>
#endif

38
#include <linux/ctype.h>
39
#include <linux/zalloc.h>
40
#include <linux/string.h>
41
#include <asm/bug.h>
42 43 44

static bool no_buildid_cache;

45 46
int build_id__mark_dso_hit(struct perf_tool *tool __maybe_unused,
			   union perf_event *event,
47
			   struct perf_sample *sample,
48
			   struct evsel *evsel __maybe_unused,
49
			   struct machine *machine)
50 51
{
	struct addr_location al;
52
	struct thread *thread = machine__findnew_thread(machine, sample->pid,
53
							sample->tid);
54 55 56 57 58 59 60

	if (thread == NULL) {
		pr_err("problem processing %d event, skipping it.\n",
			event->header.type);
		return -1;
	}

61
	if (thread__find_map(thread, sample->cpumode, sample->ip, &al))
62 63
		al.map->dso->hit = 1;

64
	thread__put(thread);
65 66 67
	return 0;
}

68
static int perf_event__exit_del_thread(struct perf_tool *tool __maybe_unused,
69
				       union perf_event *event,
70 71
				       struct perf_sample *sample
				       __maybe_unused,
72
				       struct machine *machine)
73
{
74 75 76
	struct thread *thread = machine__findnew_thread(machine,
							event->fork.pid,
							event->fork.tid);
77

78 79
	dump_printf("(%d:%d):(%d:%d)\n", event->fork.pid, event->fork.tid,
		    event->fork.ppid, event->fork.ptid);
80

81
	if (thread) {
82
		machine__remove_thread(machine, thread);
83 84
		thread__put(thread);
	}
85 86 87 88

	return 0;
}

89
struct perf_tool build_id__mark_dso_hit_ops = {
90
	.sample	= build_id__mark_dso_hit,
91
	.mmap	= perf_event__process_mmap,
92
	.mmap2	= perf_event__process_mmap2,
93
	.fork	= perf_event__process_fork,
94
	.exit	= perf_event__exit_del_thread,
95 96
	.attr		 = perf_event__process_attr,
	.build_id	 = perf_event__process_build_id,
97
	.ordered_events	 = true,
98
};
99

100
int build_id__sprintf(const struct build_id *build_id, char *bf)
101 102
{
	char *bid = bf;
103 104
	const u8 *raw = build_id->data;
	size_t i;
105

106 107
	bf[0] = 0x0;

108
	for (i = 0; i < build_id->size; ++i) {
109 110 111 112 113
		sprintf(bid, "%02x", *raw);
		++raw;
		bid += 2;
	}

114
	return (bid - bf) + 1;
115 116
}

117 118 119
int sysfs__sprintf_build_id(const char *root_dir, char *sbuild_id)
{
	char notes[PATH_MAX];
120
	struct build_id bid;
121 122 123 124 125 126 127
	int ret;

	if (!root_dir)
		root_dir = "";

	scnprintf(notes, sizeof(notes), "%s/sys/kernel/notes", root_dir);

128
	ret = sysfs__read_build_id(notes, &bid);
129 130 131
	if (ret < 0)
		return ret;

132
	return build_id__sprintf(&bid, sbuild_id);
133 134 135 136
}

int filename__sprintf_build_id(const char *pathname, char *sbuild_id)
{
137
	struct build_id bid;
138 139
	int ret;

140
	ret = filename__read_build_id(pathname, &bid);
141 142 143
	if (ret < 0)
		return ret;

144
	return build_id__sprintf(&bid, sbuild_id);
145 146
}

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
/* asnprintf consolidates asprintf and snprintf */
static int asnprintf(char **strp, size_t size, const char *fmt, ...)
{
	va_list ap;
	int ret;

	if (!strp)
		return -EINVAL;

	va_start(ap, fmt);
	if (*strp)
		ret = vsnprintf(*strp, size, fmt, ap);
	else
		ret = vasprintf(strp, fmt, ap);
	va_end(ap);

	return ret;
}

166 167 168 169 170
char *build_id_cache__kallsyms_path(const char *sbuild_id, char *bf,
				    size_t size)
{
	bool retry_old = true;

171 172
	snprintf(bf, size, "%s/%s/%s/kallsyms",
		 buildid_dir, DSO__NAME_KALLSYMS, sbuild_id);
173 174 175 176 177
retry:
	if (!access(bf, F_OK))
		return bf;
	if (retry_old) {
		/* Try old style kallsyms cache */
178 179
		snprintf(bf, size, "%s/%s/%s",
			 buildid_dir, DSO__NAME_KALLSYMS, sbuild_id);
180 181 182 183 184 185 186
		retry_old = false;
		goto retry;
	}

	return NULL;
}

187
char *build_id_cache__linkname(const char *sbuild_id, char *bf, size_t size)
188 189 190 191 192 193 194 195 196
{
	char *tmp = bf;
	int ret = asnprintf(&bf, size, "%s/.build-id/%.2s/%s", buildid_dir,
			    sbuild_id, sbuild_id + 2);
	if (ret < 0 || (tmp && size < (unsigned int)ret))
		return NULL;
	return bf;
}

197
/* The caller is responsible to free the returned buffer. */
198 199 200 201 202 203
char *build_id_cache__origname(const char *sbuild_id)
{
	char *linkname;
	char buf[PATH_MAX];
	char *ret = NULL, *p;
	size_t offs = 5;	/* == strlen("../..") */
204
	ssize_t len;
205 206 207 208 209

	linkname = build_id_cache__linkname(sbuild_id, NULL, 0);
	if (!linkname)
		return NULL;

210 211
	len = readlink(linkname, buf, sizeof(buf) - 1);
	if (len <= 0)
212
		goto out;
213 214
	buf[len] = '\0';

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
	/* The link should be "../..<origpath>/<sbuild_id>" */
	p = strrchr(buf, '/');	/* Cut off the "/<sbuild_id>" */
	if (p && (p > buf + offs)) {
		*p = '\0';
		if (buf[offs + 1] == '[')
			offs++;	/*
				 * This is a DSO name, like [kernel.kallsyms].
				 * Skip the first '/', since this is not the
				 * cache of a regular file.
				 */
		ret = strdup(buf + offs);	/* Skip "../..[/]" */
	}
out:
	free(linkname);
	return ret;
}

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
/* Check if the given build_id cache is valid on current running system */
static bool build_id_cache__valid_id(char *sbuild_id)
{
	char real_sbuild_id[SBUILD_ID_SIZE] = "";
	char *pathname;
	int ret = 0;
	bool result = false;

	pathname = build_id_cache__origname(sbuild_id);
	if (!pathname)
		return false;

	if (!strcmp(pathname, DSO__NAME_KALLSYMS))
		ret = sysfs__sprintf_build_id("/", real_sbuild_id);
	else if (pathname[0] == '/')
		ret = filename__sprintf_build_id(pathname, real_sbuild_id);
	else
		ret = -EINVAL;	/* Should we support other special DSO cache? */
	if (ret >= 0)
		result = (strcmp(sbuild_id, real_sbuild_id) == 0);
	free(pathname);

	return result;
}

257 258
static const char *build_id_cache__basename(bool is_kallsyms, bool is_vdso,
					    bool is_debug)
259
{
260 261
	return is_kallsyms ? "kallsyms" : (is_vdso ? "vdso" : (is_debug ?
	    "debug" : "elf"));
262 263
}

264 265
char *__dso__build_id_filename(const struct dso *dso, char *bf, size_t size,
			       bool is_debug, bool is_kallsyms)
266
{
267 268 269 270 271
	bool is_vdso = dso__is_vdso((struct dso *)dso);
	char sbuild_id[SBUILD_ID_SIZE];
	char *linkname;
	bool alloc = (bf == NULL);
	int ret;
272

273
	if (!dso->has_build_id)
274 275
		return NULL;

276
	build_id__sprintf(&dso->bid, sbuild_id);
277 278 279 280 281 282 283 284 285
	linkname = build_id_cache__linkname(sbuild_id, NULL, 0);
	if (!linkname)
		return NULL;

	/* Check if old style build_id cache */
	if (is_regular_file(linkname))
		ret = asnprintf(&bf, size, "%s", linkname);
	else
		ret = asnprintf(&bf, size, "%s/%s", linkname,
286 287
			 build_id_cache__basename(is_kallsyms, is_vdso,
						  is_debug));
288 289 290 291 292
	if (ret < 0 || (!alloc && size < (unsigned int)ret))
		bf = NULL;
	free(linkname);

	return bf;
293
}
294

295 296 297 298 299 300 301 302
char *dso__build_id_filename(const struct dso *dso, char *bf, size_t size,
			     bool is_debug)
{
	bool is_kallsyms = dso__is_kallsyms((struct dso *)dso);

	return __dso__build_id_filename(dso, bf, size, is_debug, is_kallsyms);
}

303 304 305 306 307 308
#define dsos__for_each_with_build_id(pos, head)	\
	list_for_each_entry(pos, head, node)	\
		if (!pos->has_build_id)		\
			continue;		\
		else

309
static int write_buildid(const char *name, size_t name_len, struct build_id *bid,
310
			 pid_t pid, u16 misc, struct feat_fd *fd)
311 312
{
	int err;
313
	struct perf_record_header_build_id b;
314 315 316 317 318 319
	size_t len;

	len = name_len + 1;
	len = PERF_ALIGN(len, NAME_ALIGN);

	memset(&b, 0, sizeof(b));
320 321 322
	memcpy(&b.data, bid->data, bid->size);
	b.size = (u8) bid->size;
	misc |= PERF_RECORD_MISC_BUILD_ID_SIZE;
323 324 325 326
	b.pid = pid;
	b.header.misc = misc;
	b.header.size = sizeof(b) + len;

327
	err = do_write(fd, &b, sizeof(b));
328 329 330 331 332 333
	if (err < 0)
		return err;

	return write_padded(fd, name, name_len + 1, len);
}

334 335
static int machine__write_buildid_table(struct machine *machine,
					struct feat_fd *fd)
336
{
337
	int err = 0;
338
	struct dso *pos;
339 340 341 342 343 344 345
	u16 kmisc = PERF_RECORD_MISC_KERNEL,
	    umisc = PERF_RECORD_MISC_USER;

	if (!machine__is_host(machine)) {
		kmisc = PERF_RECORD_MISC_GUEST_KERNEL;
		umisc = PERF_RECORD_MISC_GUEST_USER;
	}
346

347
	dsos__for_each_with_build_id(pos, &machine->dsos.head) {
348 349
		const char *name;
		size_t name_len;
350
		bool in_kernel = false;
351

352
		if (!pos->hit && !dso__is_vdso(pos))
353 354 355 356
			continue;

		if (dso__is_vdso(pos)) {
			name = pos->short_name;
357
			name_len = pos->short_name_len;
358
		} else if (dso__is_kcore(pos)) {
359 360
			name = machine->mmap_name;
			name_len = strlen(name);
361 362
		} else {
			name = pos->long_name;
363
			name_len = pos->long_name_len;
364 365
		}

366 367 368
		in_kernel = pos->kernel ||
				is_kernel_module(name,
					PERF_RECORD_MISC_CPUMODE_UNKNOWN);
369
		err = write_buildid(name, name_len, &pos->bid, machine->pid,
370
				    in_kernel ? kmisc : umisc, fd);
371
		if (err)
372
			break;
373 374 375 376 377
	}

	return err;
}

378 379
int perf_session__write_buildid_table(struct perf_session *session,
				      struct feat_fd *fd)
380 381 382 383 384 385 386
{
	struct rb_node *nd;
	int err = machine__write_buildid_table(&session->machines.host, fd);

	if (err)
		return err;

387 388
	for (nd = rb_first_cached(&session->machines.guests); nd;
	     nd = rb_next(nd)) {
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
		struct machine *pos = rb_entry(nd, struct machine, rb_node);
		err = machine__write_buildid_table(pos, fd);
		if (err)
			break;
	}
	return err;
}

static int __dsos__hit_all(struct list_head *head)
{
	struct dso *pos;

	list_for_each_entry(pos, head, node)
		pos->hit = true;

	return 0;
}

static int machine__hit_all_dsos(struct machine *machine)
{
409
	return __dsos__hit_all(&machine->dsos.head);
410 411 412 413 414 415 416 417 418 419 420
}

int dsos__hit_all(struct perf_session *session)
{
	struct rb_node *nd;
	int err;

	err = machine__hit_all_dsos(&session->machines.host);
	if (err)
		return err;

421 422
	for (nd = rb_first_cached(&session->machines.guests); nd;
	     nd = rb_next(nd)) {
423 424 425 426 427 428 429 430 431 432
		struct machine *pos = rb_entry(nd, struct machine, rb_node);

		err = machine__hit_all_dsos(pos);
		if (err)
			return err;
	}

	return 0;
}

433 434 435 436 437
void disable_buildid_cache(void)
{
	no_buildid_cache = true;
}

438
static bool lsdir_bid_head_filter(const char *name __maybe_unused,
439
				  struct dirent *d)
440 441 442 443 444 445
{
	return (strlen(d->d_name) == 2) &&
		isxdigit(d->d_name[0]) && isxdigit(d->d_name[1]);
}

static bool lsdir_bid_tail_filter(const char *name __maybe_unused,
446
				  struct dirent *d)
447 448 449 450 451 452 453
{
	int i = 0;
	while (isxdigit(d->d_name[i]) && i < SBUILD_ID_SIZE - 3)
		i++;
	return (i == SBUILD_ID_SIZE - 3) && (d->d_name[i] == '\0');
}

454
struct strlist *build_id_cache__list_all(bool validonly)
455 456 457 458 459 460
{
	struct strlist *toplist, *linklist = NULL, *bidlist;
	struct str_node *nd, *nd2;
	char *topdir, *linkdir = NULL;
	char sbuild_id[SBUILD_ID_SIZE];

461 462 463 464
	/* for filename__ functions */
	if (validonly)
		symbol__init(NULL);

465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
	/* Open the top-level directory */
	if (asprintf(&topdir, "%s/.build-id/", buildid_dir) < 0)
		return NULL;

	bidlist = strlist__new(NULL, NULL);
	if (!bidlist)
		goto out;

	toplist = lsdir(topdir, lsdir_bid_head_filter);
	if (!toplist) {
		pr_debug("Error in lsdir(%s): %d\n", topdir, errno);
		/* If there is no buildid cache, return an empty list */
		if (errno == ENOENT)
			goto out;
		goto err_out;
	}

	strlist__for_each_entry(nd, toplist) {
		if (asprintf(&linkdir, "%s/%s", topdir, nd->s) < 0)
			goto err_out;
		/* Open the lower-level directory */
		linklist = lsdir(linkdir, lsdir_bid_tail_filter);
		if (!linklist) {
			pr_debug("Error in lsdir(%s): %d\n", linkdir, errno);
			goto err_out;
		}
		strlist__for_each_entry(nd2, linklist) {
			if (snprintf(sbuild_id, SBUILD_ID_SIZE, "%s%s",
				     nd->s, nd2->s) != SBUILD_ID_SIZE - 1)
				goto err_out;
495 496
			if (validonly && !build_id_cache__valid_id(sbuild_id))
				continue;
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
			if (strlist__add(bidlist, sbuild_id) < 0)
				goto err_out;
		}
		strlist__delete(linklist);
		zfree(&linkdir);
	}

out_free:
	strlist__delete(toplist);
out:
	free(topdir);

	return bidlist;

err_out:
	strlist__delete(linklist);
	zfree(&linkdir);
	strlist__delete(bidlist);
	bidlist = NULL;
	goto out_free;
}

519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
static bool str_is_build_id(const char *maybe_sbuild_id, size_t len)
{
	size_t i;

	for (i = 0; i < len; i++) {
		if (!isxdigit(maybe_sbuild_id[i]))
			return false;
	}
	return true;
}

/* Return the valid complete build-id */
char *build_id_cache__complement(const char *incomplete_sbuild_id)
{
	struct strlist *bidlist;
	struct str_node *nd, *cand = NULL;
	char *sbuild_id = NULL;
	size_t len = strlen(incomplete_sbuild_id);

	if (len >= SBUILD_ID_SIZE ||
	    !str_is_build_id(incomplete_sbuild_id, len))
		return NULL;

	bidlist = build_id_cache__list_all(true);
	if (!bidlist)
		return NULL;

	strlist__for_each_entry(nd, bidlist) {
		if (strncmp(nd->s, incomplete_sbuild_id, len) != 0)
			continue;
		if (cand) {	/* Error: There are more than 2 candidates. */
			cand = NULL;
			break;
		}
		cand = nd;
	}
	if (cand)
		sbuild_id = strdup(cand->s);
	strlist__delete(bidlist);

	return sbuild_id;
}

562
char *build_id_cache__cachedir(const char *sbuild_id, const char *name,
563 564
			       struct nsinfo *nsi, bool is_kallsyms,
			       bool is_vdso)
565 566 567 568 569
{
	char *realname = (char *)name, *filename;
	bool slash = is_kallsyms || is_vdso;

	if (!slash) {
570
		realname = nsinfo__realpath(name, nsi);
571 572 573 574
		if (!realname)
			return NULL;
	}

575 576 577
	if (asprintf(&filename, "%s%s%s%s%s", buildid_dir, slash ? "/" : "",
		     is_vdso ? DSO__NAME_VDSO : realname,
		     sbuild_id ? "/" : "", sbuild_id ?: "") < 0)
578 579 580 581 582 583 584 585
		filename = NULL;

	if (!slash)
		free(realname);

	return filename;
}

586
int build_id_cache__list_build_ids(const char *pathname, struct nsinfo *nsi,
587 588 589 590 591
				   struct strlist **result)
{
	char *dir_name;
	int ret = 0;

592
	dir_name = build_id_cache__cachedir(NULL, pathname, nsi, false, false);
593 594
	if (!dir_name)
		return -ENOMEM;
595

596 597
	*result = lsdir(dir_name, lsdir_no_dot_filter);
	if (!*result)
598 599 600 601 602 603
		ret = -errno;
	free(dir_name);

	return ret;
}

604
#if defined(HAVE_LIBELF_SUPPORT) && defined(HAVE_GELF_GETNOTE_SUPPORT)
605
static int build_id_cache__add_sdt_cache(const char *sbuild_id,
606 607
					  const char *realname,
					  struct nsinfo *nsi)
608 609 610
{
	struct probe_cache *cache;
	int ret;
611
	struct nscookie nsc;
612

613
	cache = probe_cache__new(sbuild_id, nsi);
614 615 616
	if (!cache)
		return -1;

617
	nsinfo__mountns_enter(nsi, &nsc);
618
	ret = probe_cache__scan_sdt(cache, realname);
619
	nsinfo__mountns_exit(&nsc);
620
	if (ret >= 0) {
621
		pr_debug4("Found %d SDTs in %s\n", ret, realname);
622 623 624 625 626 627 628
		if (probe_cache__commit(cache) < 0)
			ret = -1;
	}
	probe_cache__delete(cache);
	return ret;
}
#else
629
#define build_id_cache__add_sdt_cache(sbuild_id, realname, nsi) (0)
630 631
#endif

632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
static char *build_id_cache__find_debug(const char *sbuild_id,
					struct nsinfo *nsi)
{
	char *realname = NULL;
	char *debugfile;
	struct nscookie nsc;
	size_t len = 0;

	debugfile = calloc(1, PATH_MAX);
	if (!debugfile)
		goto out;

	len = __symbol__join_symfs(debugfile, PATH_MAX,
				   "/usr/lib/debug/.build-id/");
	snprintf(debugfile + len, PATH_MAX - len, "%.2s/%s.debug", sbuild_id,
		 sbuild_id + 2);

	nsinfo__mountns_enter(nsi, &nsc);
	realname = realpath(debugfile, NULL);
	if (realname && access(realname, R_OK))
		zfree(&realname);
	nsinfo__mountns_exit(&nsc);
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668

#ifdef HAVE_DEBUGINFOD_SUPPORT
        if (realname == NULL) {
                debuginfod_client* c = debuginfod_begin();
                if (c != NULL) {
                        int fd = debuginfod_find_debuginfo(c,
                                                           (const unsigned char*)sbuild_id, 0,
                                                           &realname);
                        if (fd >= 0)
                                close(fd); /* retaining reference by realname */
                        debuginfod_end(c);
                }
        }
#endif

669 670 671 672 673
out:
	free(debugfile);
	return realname;
}

674
int build_id_cache__add_s(const char *sbuild_id, const char *name,
675
			  struct nsinfo *nsi, bool is_kallsyms, bool is_vdso)
676 677
{
	const size_t size = PATH_MAX;
678
	char *realname = NULL, *filename = NULL, *dir_name = NULL,
679
	     *linkname = zalloc(size), *tmp;
680
	char *debugfile = NULL;
681
	int err = -1;
682

683
	if (!is_kallsyms) {
684 685 686 687
		if (!is_vdso)
			realname = nsinfo__realpath(name, nsi);
		else
			realname = realpath(name, NULL);
688 689 690
		if (!realname)
			goto out_free;
	}
691

692 693
	dir_name = build_id_cache__cachedir(sbuild_id, name, nsi, is_kallsyms,
					    is_vdso);
694
	if (!dir_name)
695 696
		goto out_free;

697 698 699 700 701
	/* Remove old style build-id cache */
	if (is_regular_file(dir_name))
		if (unlink(dir_name))
			goto out_free;

702
	if (mkdir_p(dir_name, 0755))
703 704
		goto out_free;

705 706
	/* Save the allocated buildid dirname */
	if (asprintf(&filename, "%s/%s", dir_name,
707 708
		     build_id_cache__basename(is_kallsyms, is_vdso,
		     false)) < 0) {
709 710 711
		filename = NULL;
		goto out_free;
	}
712 713 714

	if (access(filename, F_OK)) {
		if (is_kallsyms) {
715 716 717 718
			if (copyfile("/proc/kallsyms", filename))
				goto out_free;
		} else if (nsi && nsi->need_setns) {
			if (copyfile_ns(name, filename, nsi))
719
				goto out_free;
720 721
		} else if (link(realname, filename) && errno != EEXIST &&
				copyfile(name, filename))
722 723 724
			goto out_free;
	}

725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
	/* Some binaries are stripped, but have .debug files with their symbol
	 * table.  Check to see if we can locate one of those, since the elf
	 * file itself may not be very useful to users of our tools without a
	 * symtab.
	 */
	if (!is_kallsyms && !is_vdso &&
	    strncmp(".ko", name + strlen(name) - 3, 3)) {
		debugfile = build_id_cache__find_debug(sbuild_id, nsi);
		if (debugfile) {
			zfree(&filename);
			if (asprintf(&filename, "%s/%s", dir_name,
			    build_id_cache__basename(false, false, true)) < 0) {
				filename = NULL;
				goto out_free;
			}
			if (access(filename, F_OK)) {
				if (nsi && nsi->need_setns) {
					if (copyfile_ns(debugfile, filename,
							nsi))
						goto out_free;
				} else if (link(debugfile, filename) &&
						errno != EEXIST &&
						copyfile(debugfile, filename))
					goto out_free;
			}
		}
	}

753
	if (!build_id_cache__linkname(sbuild_id, linkname, size))
754 755 756
		goto out_free;
	tmp = strrchr(linkname, '/');
	*tmp = '\0';
757 758 759 760

	if (access(linkname, X_OK) && mkdir_p(linkname, 0755))
		goto out_free;

761
	*tmp = '/';
762 763
	tmp = dir_name + strlen(buildid_dir) - 5;
	memcpy(tmp, "../..", 5);
764

765
	if (symlink(tmp, linkname) == 0) {
766
		err = 0;
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
	} else if (errno == EEXIST) {
		char path[PATH_MAX];
		ssize_t len;

		len = readlink(linkname, path, sizeof(path) - 1);
		if (len <= 0) {
			pr_err("Cant read link: %s\n", linkname);
			goto out_free;
		}
		path[len] = '\0';

		if (strcmp(tmp, path)) {
			pr_debug("build <%s> already linked to %s\n",
				 sbuild_id, linkname);
		}
		err = 0;
	}
784 785

	/* Update SDT cache : error is just warned */
786 787
	if (realname &&
	    build_id_cache__add_sdt_cache(sbuild_id, realname, nsi) < 0)
788
		pr_debug4("Failed to update/scan SDT cache for %s\n", realname);
789

790 791 792 793
out_free:
	if (!is_kallsyms)
		free(realname);
	free(filename);
794
	free(debugfile);
795
	free(dir_name);
796 797 798 799
	free(linkname);
	return err;
}

800
static int build_id_cache__add_b(const struct build_id *bid,
801 802
				 const char *name, struct nsinfo *nsi,
				 bool is_kallsyms, bool is_vdso)
803
{
804
	char sbuild_id[SBUILD_ID_SIZE];
805

806
	build_id__sprintf(bid, sbuild_id);
807

808 809
	return build_id_cache__add_s(sbuild_id, name, nsi, is_kallsyms,
				     is_vdso);
810 811
}

812 813 814
bool build_id_cache__cached(const char *sbuild_id)
{
	bool ret = false;
815
	char *filename = build_id_cache__linkname(sbuild_id, NULL, 0);
816 817 818 819 820 821 822 823

	if (filename && !access(filename, F_OK))
		ret = true;
	free(filename);

	return ret;
}

824
int build_id_cache__remove_s(const char *sbuild_id)
825 826 827
{
	const size_t size = PATH_MAX;
	char *filename = zalloc(size),
828
	     *linkname = zalloc(size), *tmp;
829 830 831 832 833
	int err = -1;

	if (filename == NULL || linkname == NULL)
		goto out_free;

834
	if (!build_id_cache__linkname(sbuild_id, linkname, size))
835
		goto out_free;
836 837 838 839 840 841 842 843 844 845 846 847 848

	if (access(linkname, F_OK))
		goto out_free;

	if (readlink(linkname, filename, size - 1) < 0)
		goto out_free;

	if (unlink(linkname))
		goto out_free;

	/*
	 * Since the link is relative, we must make it absolute:
	 */
849 850
	tmp = strrchr(linkname, '/') + 1;
	snprintf(tmp, size - (tmp - linkname), "%s", filename);
851

852
	if (rm_rf(linkname))
853 854 855 856 857 858 859 860 861
		goto out_free;

	err = 0;
out_free:
	free(filename);
	free(linkname);
	return err;
}

862 863
static int dso__cache_build_id(struct dso *dso, struct machine *machine,
			       void *priv __maybe_unused)
864
{
865
	bool is_kallsyms = dso__is_kallsyms(dso);
866 867 868
	bool is_vdso = dso__is_vdso(dso);
	const char *name = dso->long_name;

869 870 871
	if (!dso->has_build_id)
		return 0;

872 873
	if (dso__is_kcore(dso)) {
		is_kallsyms = true;
874
		name = machine->mmap_name;
875
	}
876 877
	return build_id_cache__add_b(&dso->bid, name, dso->nsinfo,
				     is_kallsyms, is_vdso);
878 879
}

880 881
static int
machines__for_each_dso(struct machines *machines, machine__dso_t fn, void *priv)
882
{
883 884
	int ret = machine__for_each_dso(&machines->host, fn, priv);
	struct rb_node *nd;
885

886 887 888
	for (nd = rb_first_cached(&machines->guests); nd;
	     nd = rb_next(nd)) {
		struct machine *pos = rb_entry(nd, struct machine, rb_node);
889

890 891 892
		ret |= machine__for_each_dso(pos, fn, priv);
	}
	return ret ? -1 : 0;
893 894 895 896
}

int perf_session__cache_build_ids(struct perf_session *session)
{
897 898 899
	if (no_buildid_cache)
		return 0;

900
	if (mkdir(buildid_dir, 0755) != 0 && errno != EEXIST)
901 902
		return -1;

903
	return machines__for_each_dso(&session->machines, dso__cache_build_id, NULL) ?  -1 : 0;
904 905 906 907
}

static bool machine__read_build_ids(struct machine *machine, bool with_hits)
{
908
	return __dsos__read_build_ids(&machine->dsos.head, with_hits);
909 910 911 912 913 914 915
}

bool perf_session__read_build_ids(struct perf_session *session, bool with_hits)
{
	struct rb_node *nd;
	bool ret = machine__read_build_ids(&session->machines.host, with_hits);

916 917
	for (nd = rb_first_cached(&session->machines.guests); nd;
	     nd = rb_next(nd)) {
918 919 920 921 922 923
		struct machine *pos = rb_entry(nd, struct machine, rb_node);
		ret |= machine__read_build_ids(pos, with_hits);
	}

	return ret;
}
924 925 926 927 928 929 930

void build_id__init(struct build_id *bid, const u8 *data, size_t size)
{
	WARN_ON(size > BUILD_ID_SIZE);
	memcpy(bid->data, data, size);
	bid->size = size;
}
931 932 933 934 935

bool build_id__is_defined(const struct build_id *bid)
{
	return bid && bid->size ? !!memchr_inv(bid->data, 0, bid->size) : false;
}