xref: /linux/tools/perf/util/build-id.c (revision 46e6acfe3501fa938af9c5bd730f0020235b08a2)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * build-id.c
4  *
5  * build-id support
6  *
7  * Copyright (C) 2009, 2010 Red Hat Inc.
8  * Copyright (C) 2009, 2010 Arnaldo Carvalho de Melo <acme@redhat.com>
9  */
10 #include "util.h" // lsdir(), mkdir_p(), rm_rf()
11 #include <dirent.h>
12 #include <errno.h>
13 #include <stdio.h>
14 #include <sys/stat.h>
15 #include <sys/types.h>
16 #include "util/copyfile.h"
17 #include "dso.h"
18 #include "build-id.h"
19 #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 #include "header.h"
29 #include "vdso.h"
30 #include "path.h"
31 #include "probe-file.h"
32 #include "strlist.h"
33 
34 #ifdef HAVE_DEBUGINFOD_SUPPORT
35 #include <elfutils/debuginfod.h>
36 #endif
37 
38 #include <linux/ctype.h>
39 #include <linux/zalloc.h>
40 #include <linux/string.h>
41 #include <asm/bug.h>
42 
43 static bool no_buildid_cache;
44 
45 int build_id__mark_dso_hit(struct perf_tool *tool __maybe_unused,
46 			   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 	if (thread == NULL) {
56 		pr_err("problem processing %d event, skipping it.\n",
57 			event->header.type);
58 		return -1;
59 	}
60 
61 	addr_location__init(&al);
62 	if (thread__find_map(thread, sample->cpumode, sample->ip, &al))
63 		dso__set_hit(map__dso(al.map));
64 
65 	addr_location__exit(&al);
66 	thread__put(thread);
67 	return 0;
68 }
69 
70 static int perf_event__exit_del_thread(struct perf_tool *tool __maybe_unused,
71 				       union perf_event *event,
72 				       struct perf_sample *sample
73 				       __maybe_unused,
74 				       struct machine *machine)
75 {
76 	struct thread *thread = machine__findnew_thread(machine,
77 							event->fork.pid,
78 							event->fork.tid);
79 
80 	dump_printf("(%d:%d):(%d:%d)\n", event->fork.pid, event->fork.tid,
81 		    event->fork.ppid, event->fork.ptid);
82 
83 	if (thread) {
84 		machine__remove_thread(machine, thread);
85 		thread__put(thread);
86 	}
87 
88 	return 0;
89 }
90 
91 struct perf_tool build_id__mark_dso_hit_ops = {
92 	.sample	= build_id__mark_dso_hit,
93 	.mmap	= perf_event__process_mmap,
94 	.mmap2	= perf_event__process_mmap2,
95 	.fork	= perf_event__process_fork,
96 	.exit	= perf_event__exit_del_thread,
97 	.attr		 = perf_event__process_attr,
98 	.build_id	 = perf_event__process_build_id,
99 	.ordered_events	 = true,
100 };
101 
102 int build_id__sprintf(const struct build_id *build_id, char *bf)
103 {
104 	char *bid = bf;
105 	const u8 *raw = build_id->data;
106 	size_t i;
107 
108 	bf[0] = 0x0;
109 
110 	for (i = 0; i < build_id->size; ++i) {
111 		sprintf(bid, "%02x", *raw);
112 		++raw;
113 		bid += 2;
114 	}
115 
116 	return (bid - bf) + 1;
117 }
118 
119 int sysfs__sprintf_build_id(const char *root_dir, char *sbuild_id)
120 {
121 	char notes[PATH_MAX];
122 	struct build_id bid;
123 	int ret;
124 
125 	if (!root_dir)
126 		root_dir = "";
127 
128 	scnprintf(notes, sizeof(notes), "%s/sys/kernel/notes", root_dir);
129 
130 	ret = sysfs__read_build_id(notes, &bid);
131 	if (ret < 0)
132 		return ret;
133 
134 	return build_id__sprintf(&bid, sbuild_id);
135 }
136 
137 int filename__sprintf_build_id(const char *pathname, char *sbuild_id)
138 {
139 	struct build_id bid;
140 	int ret;
141 
142 	ret = filename__read_build_id(pathname, &bid);
143 	if (ret < 0)
144 		return ret;
145 
146 	return build_id__sprintf(&bid, sbuild_id);
147 }
148 
149 /* asnprintf consolidates asprintf and snprintf */
150 static int asnprintf(char **strp, size_t size, const char *fmt, ...)
151 {
152 	va_list ap;
153 	int ret;
154 
155 	if (!strp)
156 		return -EINVAL;
157 
158 	va_start(ap, fmt);
159 	if (*strp)
160 		ret = vsnprintf(*strp, size, fmt, ap);
161 	else
162 		ret = vasprintf(strp, fmt, ap);
163 	va_end(ap);
164 
165 	return ret;
166 }
167 
168 char *build_id_cache__kallsyms_path(const char *sbuild_id, char *bf,
169 				    size_t size)
170 {
171 	bool retry_old = true;
172 
173 	snprintf(bf, size, "%s/%s/%s/kallsyms",
174 		 buildid_dir, DSO__NAME_KALLSYMS, sbuild_id);
175 retry:
176 	if (!access(bf, F_OK))
177 		return bf;
178 	if (retry_old) {
179 		/* Try old style kallsyms cache */
180 		snprintf(bf, size, "%s/%s/%s",
181 			 buildid_dir, DSO__NAME_KALLSYMS, sbuild_id);
182 		retry_old = false;
183 		goto retry;
184 	}
185 
186 	return NULL;
187 }
188 
189 char *build_id_cache__linkname(const char *sbuild_id, char *bf, size_t size)
190 {
191 	char *tmp = bf;
192 	int ret = asnprintf(&bf, size, "%s/.build-id/%.2s/%s", buildid_dir,
193 			    sbuild_id, sbuild_id + 2);
194 	if (ret < 0 || (tmp && size < (unsigned int)ret))
195 		return NULL;
196 	return bf;
197 }
198 
199 /* The caller is responsible to free the returned buffer. */
200 char *build_id_cache__origname(const char *sbuild_id)
201 {
202 	char *linkname;
203 	char buf[PATH_MAX];
204 	char *ret = NULL, *p;
205 	size_t offs = 5;	/* == strlen("../..") */
206 	ssize_t len;
207 
208 	linkname = build_id_cache__linkname(sbuild_id, NULL, 0);
209 	if (!linkname)
210 		return NULL;
211 
212 	len = readlink(linkname, buf, sizeof(buf) - 1);
213 	if (len <= 0)
214 		goto out;
215 	buf[len] = '\0';
216 
217 	/* The link should be "../..<origpath>/<sbuild_id>" */
218 	p = strrchr(buf, '/');	/* Cut off the "/<sbuild_id>" */
219 	if (p && (p > buf + offs)) {
220 		*p = '\0';
221 		if (buf[offs + 1] == '[')
222 			offs++;	/*
223 				 * This is a DSO name, like [kernel.kallsyms].
224 				 * Skip the first '/', since this is not the
225 				 * cache of a regular file.
226 				 */
227 		ret = strdup(buf + offs);	/* Skip "../..[/]" */
228 	}
229 out:
230 	free(linkname);
231 	return ret;
232 }
233 
234 /* Check if the given build_id cache is valid on current running system */
235 static bool build_id_cache__valid_id(char *sbuild_id)
236 {
237 	char real_sbuild_id[SBUILD_ID_SIZE] = "";
238 	char *pathname;
239 	int ret = 0;
240 	bool result = false;
241 
242 	pathname = build_id_cache__origname(sbuild_id);
243 	if (!pathname)
244 		return false;
245 
246 	if (!strcmp(pathname, DSO__NAME_KALLSYMS))
247 		ret = sysfs__sprintf_build_id("/", real_sbuild_id);
248 	else if (pathname[0] == '/')
249 		ret = filename__sprintf_build_id(pathname, real_sbuild_id);
250 	else
251 		ret = -EINVAL;	/* Should we support other special DSO cache? */
252 	if (ret >= 0)
253 		result = (strcmp(sbuild_id, real_sbuild_id) == 0);
254 	free(pathname);
255 
256 	return result;
257 }
258 
259 static const char *build_id_cache__basename(bool is_kallsyms, bool is_vdso,
260 					    bool is_debug)
261 {
262 	return is_kallsyms ? "kallsyms" : (is_vdso ? "vdso" : (is_debug ?
263 	    "debug" : "elf"));
264 }
265 
266 char *__dso__build_id_filename(const struct dso *dso, char *bf, size_t size,
267 			       bool is_debug, bool is_kallsyms)
268 {
269 	bool is_vdso = dso__is_vdso((struct dso *)dso);
270 	char sbuild_id[SBUILD_ID_SIZE];
271 	char *linkname;
272 	bool alloc = (bf == NULL);
273 	int ret;
274 
275 	if (!dso__has_build_id(dso))
276 		return NULL;
277 
278 	build_id__sprintf(dso__bid_const(dso), sbuild_id);
279 	linkname = build_id_cache__linkname(sbuild_id, NULL, 0);
280 	if (!linkname)
281 		return NULL;
282 
283 	/* Check if old style build_id cache */
284 	if (is_regular_file(linkname))
285 		ret = asnprintf(&bf, size, "%s", linkname);
286 	else
287 		ret = asnprintf(&bf, size, "%s/%s", linkname,
288 			 build_id_cache__basename(is_kallsyms, is_vdso,
289 						  is_debug));
290 	if (ret < 0 || (!alloc && size < (unsigned int)ret))
291 		bf = NULL;
292 	free(linkname);
293 
294 	return bf;
295 }
296 
297 char *dso__build_id_filename(const struct dso *dso, char *bf, size_t size,
298 			     bool is_debug)
299 {
300 	bool is_kallsyms = dso__is_kallsyms((struct dso *)dso);
301 
302 	return __dso__build_id_filename(dso, bf, size, is_debug, is_kallsyms);
303 }
304 
305 static int write_buildid(const char *name, size_t name_len, struct build_id *bid,
306 			 pid_t pid, u16 misc, struct feat_fd *fd)
307 {
308 	int err;
309 	struct perf_record_header_build_id b;
310 	size_t len;
311 
312 	len = name_len + 1;
313 	len = PERF_ALIGN(len, NAME_ALIGN);
314 
315 	memset(&b, 0, sizeof(b));
316 	memcpy(&b.data, bid->data, bid->size);
317 	b.size = (u8) bid->size;
318 	misc |= PERF_RECORD_MISC_BUILD_ID_SIZE;
319 	b.pid = pid;
320 	b.header.misc = misc;
321 	b.header.size = sizeof(b) + len;
322 
323 	err = do_write(fd, &b, sizeof(b));
324 	if (err < 0)
325 		return err;
326 
327 	return write_padded(fd, name, name_len + 1, len);
328 }
329 
330 struct machine__write_buildid_table_cb_args {
331 	struct machine *machine;
332 	struct feat_fd *fd;
333 	u16 kmisc, umisc;
334 };
335 
336 static int machine__write_buildid_table_cb(struct dso *dso, void *data)
337 {
338 	struct machine__write_buildid_table_cb_args *args = data;
339 	const char *name;
340 	size_t name_len;
341 	bool in_kernel = false;
342 
343 	if (!dso__has_build_id(dso))
344 		return 0;
345 
346 	if (!dso__hit(dso) && !dso__is_vdso(dso))
347 		return 0;
348 
349 	if (dso__is_vdso(dso)) {
350 		name = dso__short_name(dso);
351 		name_len = dso__short_name_len(dso);
352 	} else if (dso__is_kcore(dso)) {
353 		name = args->machine->mmap_name;
354 		name_len = strlen(name);
355 	} else {
356 		name = dso__long_name(dso);
357 		name_len = dso__long_name_len(dso);
358 	}
359 
360 	in_kernel = dso__kernel(dso) || is_kernel_module(name, PERF_RECORD_MISC_CPUMODE_UNKNOWN);
361 	return write_buildid(name, name_len, dso__bid(dso), args->machine->pid,
362 			     in_kernel ? args->kmisc : args->umisc, args->fd);
363 }
364 
365 static int machine__write_buildid_table(struct machine *machine, struct feat_fd *fd)
366 {
367 	struct machine__write_buildid_table_cb_args args = {
368 		.machine = machine,
369 		.fd = fd,
370 		.kmisc = PERF_RECORD_MISC_KERNEL,
371 		.umisc = PERF_RECORD_MISC_USER,
372 	};
373 
374 	if (!machine__is_host(machine)) {
375 		args.kmisc = PERF_RECORD_MISC_GUEST_KERNEL;
376 		args.umisc = PERF_RECORD_MISC_GUEST_USER;
377 	}
378 
379 	return dsos__for_each_dso(&machine->dsos, machine__write_buildid_table_cb, &args);
380 }
381 
382 int perf_session__write_buildid_table(struct perf_session *session,
383 				      struct feat_fd *fd)
384 {
385 	struct rb_node *nd;
386 	int err = machine__write_buildid_table(&session->machines.host, fd);
387 
388 	if (err)
389 		return err;
390 
391 	for (nd = rb_first_cached(&session->machines.guests); nd;
392 	     nd = rb_next(nd)) {
393 		struct machine *pos = rb_entry(nd, struct machine, rb_node);
394 		err = machine__write_buildid_table(pos, fd);
395 		if (err)
396 			break;
397 	}
398 	return err;
399 }
400 
401 void disable_buildid_cache(void)
402 {
403 	no_buildid_cache = true;
404 }
405 
406 static bool lsdir_bid_head_filter(const char *name __maybe_unused,
407 				  struct dirent *d)
408 {
409 	return (strlen(d->d_name) == 2) &&
410 		isxdigit(d->d_name[0]) && isxdigit(d->d_name[1]);
411 }
412 
413 static bool lsdir_bid_tail_filter(const char *name __maybe_unused,
414 				  struct dirent *d)
415 {
416 	int i = 0;
417 	while (isxdigit(d->d_name[i]) && i < SBUILD_ID_SIZE - 3)
418 		i++;
419 	return (i >= SBUILD_ID_MIN_SIZE - 3) && (i <= SBUILD_ID_SIZE - 3) &&
420 		(d->d_name[i] == '\0');
421 }
422 
423 struct strlist *build_id_cache__list_all(bool validonly)
424 {
425 	struct strlist *toplist, *linklist = NULL, *bidlist;
426 	struct str_node *nd, *nd2;
427 	char *topdir, *linkdir = NULL;
428 	char sbuild_id[SBUILD_ID_SIZE];
429 
430 	/* for filename__ functions */
431 	if (validonly)
432 		symbol__init(NULL);
433 
434 	/* Open the top-level directory */
435 	if (asprintf(&topdir, "%s/.build-id/", buildid_dir) < 0)
436 		return NULL;
437 
438 	bidlist = strlist__new(NULL, NULL);
439 	if (!bidlist)
440 		goto out;
441 
442 	toplist = lsdir(topdir, lsdir_bid_head_filter);
443 	if (!toplist) {
444 		pr_debug("Error in lsdir(%s): %d\n", topdir, errno);
445 		/* If there is no buildid cache, return an empty list */
446 		if (errno == ENOENT)
447 			goto out;
448 		goto err_out;
449 	}
450 
451 	strlist__for_each_entry(nd, toplist) {
452 		if (asprintf(&linkdir, "%s/%s", topdir, nd->s) < 0)
453 			goto err_out;
454 		/* Open the lower-level directory */
455 		linklist = lsdir(linkdir, lsdir_bid_tail_filter);
456 		if (!linklist) {
457 			pr_debug("Error in lsdir(%s): %d\n", linkdir, errno);
458 			goto err_out;
459 		}
460 		strlist__for_each_entry(nd2, linklist) {
461 			if (snprintf(sbuild_id, SBUILD_ID_SIZE, "%s%s",
462 				     nd->s, nd2->s) > SBUILD_ID_SIZE - 1)
463 				goto err_out;
464 			if (validonly && !build_id_cache__valid_id(sbuild_id))
465 				continue;
466 			if (strlist__add(bidlist, sbuild_id) < 0)
467 				goto err_out;
468 		}
469 		strlist__delete(linklist);
470 		zfree(&linkdir);
471 	}
472 
473 out_free:
474 	strlist__delete(toplist);
475 out:
476 	free(topdir);
477 
478 	return bidlist;
479 
480 err_out:
481 	strlist__delete(linklist);
482 	zfree(&linkdir);
483 	strlist__delete(bidlist);
484 	bidlist = NULL;
485 	goto out_free;
486 }
487 
488 static bool str_is_build_id(const char *maybe_sbuild_id, size_t len)
489 {
490 	size_t i;
491 
492 	for (i = 0; i < len; i++) {
493 		if (!isxdigit(maybe_sbuild_id[i]))
494 			return false;
495 	}
496 	return true;
497 }
498 
499 /* Return the valid complete build-id */
500 char *build_id_cache__complement(const char *incomplete_sbuild_id)
501 {
502 	struct strlist *bidlist;
503 	struct str_node *nd, *cand = NULL;
504 	char *sbuild_id = NULL;
505 	size_t len = strlen(incomplete_sbuild_id);
506 
507 	if (len >= SBUILD_ID_SIZE ||
508 	    !str_is_build_id(incomplete_sbuild_id, len))
509 		return NULL;
510 
511 	bidlist = build_id_cache__list_all(true);
512 	if (!bidlist)
513 		return NULL;
514 
515 	strlist__for_each_entry(nd, bidlist) {
516 		if (strncmp(nd->s, incomplete_sbuild_id, len) != 0)
517 			continue;
518 		if (cand) {	/* Error: There are more than 2 candidates. */
519 			cand = NULL;
520 			break;
521 		}
522 		cand = nd;
523 	}
524 	if (cand)
525 		sbuild_id = strdup(cand->s);
526 	strlist__delete(bidlist);
527 
528 	return sbuild_id;
529 }
530 
531 char *build_id_cache__cachedir(const char *sbuild_id, const char *name,
532 			       struct nsinfo *nsi, bool is_kallsyms,
533 			       bool is_vdso)
534 {
535 	char *realname = NULL, *filename;
536 	bool slash = is_kallsyms || is_vdso;
537 
538 	if (!slash)
539 		realname = nsinfo__realpath(name, nsi);
540 
541 	if (asprintf(&filename, "%s%s%s%s%s", buildid_dir, slash ? "/" : "",
542 		     is_vdso ? DSO__NAME_VDSO : (realname ? realname : name),
543 		     sbuild_id ? "/" : "", sbuild_id ?: "") < 0)
544 		filename = NULL;
545 
546 	free(realname);
547 	return filename;
548 }
549 
550 int build_id_cache__list_build_ids(const char *pathname, struct nsinfo *nsi,
551 				   struct strlist **result)
552 {
553 	char *dir_name;
554 	int ret = 0;
555 
556 	dir_name = build_id_cache__cachedir(NULL, pathname, nsi, false, false);
557 	if (!dir_name)
558 		return -ENOMEM;
559 
560 	*result = lsdir(dir_name, lsdir_no_dot_filter);
561 	if (!*result)
562 		ret = -errno;
563 	free(dir_name);
564 
565 	return ret;
566 }
567 
568 #if defined(HAVE_LIBELF_SUPPORT) && defined(HAVE_GELF_GETNOTE_SUPPORT)
569 static int build_id_cache__add_sdt_cache(const char *sbuild_id,
570 					  const char *realname,
571 					  struct nsinfo *nsi)
572 {
573 	struct probe_cache *cache;
574 	int ret;
575 	struct nscookie nsc;
576 
577 	cache = probe_cache__new(sbuild_id, nsi);
578 	if (!cache)
579 		return -1;
580 
581 	nsinfo__mountns_enter(nsi, &nsc);
582 	ret = probe_cache__scan_sdt(cache, realname);
583 	nsinfo__mountns_exit(&nsc);
584 	if (ret >= 0) {
585 		pr_debug4("Found %d SDTs in %s\n", ret, realname);
586 		if (probe_cache__commit(cache) < 0)
587 			ret = -1;
588 	}
589 	probe_cache__delete(cache);
590 	return ret;
591 }
592 #else
593 #define build_id_cache__add_sdt_cache(sbuild_id, realname, nsi) (0)
594 #endif
595 
596 static char *build_id_cache__find_debug(const char *sbuild_id,
597 					struct nsinfo *nsi,
598 					const char *root_dir)
599 {
600 	const char *dirname = "/usr/lib/debug/.build-id/";
601 	char *realname = NULL;
602 	char dirbuf[PATH_MAX];
603 	char *debugfile;
604 	struct nscookie nsc;
605 	size_t len = 0;
606 
607 	debugfile = calloc(1, PATH_MAX);
608 	if (!debugfile)
609 		goto out;
610 
611 	if (root_dir) {
612 		path__join(dirbuf, PATH_MAX, root_dir, dirname);
613 		dirname = dirbuf;
614 	}
615 
616 	len = __symbol__join_symfs(debugfile, PATH_MAX, dirname);
617 	snprintf(debugfile + len, PATH_MAX - len, "%.2s/%s.debug", sbuild_id,
618 		 sbuild_id + 2);
619 
620 	nsinfo__mountns_enter(nsi, &nsc);
621 	realname = realpath(debugfile, NULL);
622 	if (realname && access(realname, R_OK))
623 		zfree(&realname);
624 	nsinfo__mountns_exit(&nsc);
625 
626 #ifdef HAVE_DEBUGINFOD_SUPPORT
627 	if (realname == NULL) {
628 		debuginfod_client* c;
629 
630 		pr_debug("Downloading debug info with build id %s\n", sbuild_id);
631 
632 		c = debuginfod_begin();
633 		if (c != NULL) {
634 			int fd = debuginfod_find_debuginfo(c,
635 					(const unsigned char*)sbuild_id, 0,
636 					&realname);
637 			if (fd >= 0)
638 				close(fd); /* retaining reference by realname */
639 			debuginfod_end(c);
640 		}
641 	}
642 #endif
643 
644 out:
645 	free(debugfile);
646 	return realname;
647 }
648 
649 int
650 build_id_cache__add(const char *sbuild_id, const char *name, const char *realname,
651 		    struct nsinfo *nsi, bool is_kallsyms, bool is_vdso,
652 		    const char *proper_name, const char *root_dir)
653 {
654 	const size_t size = PATH_MAX;
655 	char *filename = NULL, *dir_name = NULL, *linkname = zalloc(size), *tmp;
656 	char *debugfile = NULL;
657 	int err = -1;
658 
659 	if (!proper_name)
660 		proper_name = name;
661 
662 	dir_name = build_id_cache__cachedir(sbuild_id, proper_name, nsi, is_kallsyms,
663 					    is_vdso);
664 	if (!dir_name)
665 		goto out_free;
666 
667 	/* Remove old style build-id cache */
668 	if (is_regular_file(dir_name))
669 		if (unlink(dir_name))
670 			goto out_free;
671 
672 	if (mkdir_p(dir_name, 0755))
673 		goto out_free;
674 
675 	/* Save the allocated buildid dirname */
676 	if (asprintf(&filename, "%s/%s", dir_name,
677 		     build_id_cache__basename(is_kallsyms, is_vdso,
678 		     false)) < 0) {
679 		filename = NULL;
680 		goto out_free;
681 	}
682 
683 	if (access(filename, F_OK)) {
684 		if (is_kallsyms) {
685 			if (copyfile("/proc/kallsyms", filename))
686 				goto out_free;
687 		} else if (nsi && nsinfo__need_setns(nsi)) {
688 			if (copyfile_ns(name, filename, nsi))
689 				goto out_free;
690 		} else if (link(realname, filename) && errno != EEXIST) {
691 			struct stat f_stat;
692 
693 			if (!(stat(name, &f_stat) < 0) &&
694 					copyfile_mode(name, filename, f_stat.st_mode))
695 				goto out_free;
696 		}
697 	}
698 
699 	/* Some binaries are stripped, but have .debug files with their symbol
700 	 * table.  Check to see if we can locate one of those, since the elf
701 	 * file itself may not be very useful to users of our tools without a
702 	 * symtab.
703 	 */
704 	if (!is_kallsyms && !is_vdso &&
705 	    strncmp(".ko", name + strlen(name) - 3, 3)) {
706 		debugfile = build_id_cache__find_debug(sbuild_id, nsi, root_dir);
707 		if (debugfile) {
708 			zfree(&filename);
709 			if (asprintf(&filename, "%s/%s", dir_name,
710 			    build_id_cache__basename(false, false, true)) < 0) {
711 				filename = NULL;
712 				goto out_free;
713 			}
714 			if (access(filename, F_OK)) {
715 				if (nsi && nsinfo__need_setns(nsi)) {
716 					if (copyfile_ns(debugfile, filename,
717 							nsi))
718 						goto out_free;
719 				} else if (link(debugfile, filename) &&
720 						errno != EEXIST &&
721 						copyfile(debugfile, filename))
722 					goto out_free;
723 			}
724 		}
725 	}
726 
727 	if (!build_id_cache__linkname(sbuild_id, linkname, size))
728 		goto out_free;
729 	tmp = strrchr(linkname, '/');
730 	*tmp = '\0';
731 
732 	if (access(linkname, X_OK) && mkdir_p(linkname, 0755))
733 		goto out_free;
734 
735 	*tmp = '/';
736 	tmp = dir_name + strlen(buildid_dir) - 5;
737 	memcpy(tmp, "../..", 5);
738 
739 	if (symlink(tmp, linkname) == 0) {
740 		err = 0;
741 	} else if (errno == EEXIST) {
742 		char path[PATH_MAX];
743 		ssize_t len;
744 
745 		len = readlink(linkname, path, sizeof(path) - 1);
746 		if (len <= 0) {
747 			pr_err("Can't read link: %s\n", linkname);
748 			goto out_free;
749 		}
750 		path[len] = '\0';
751 
752 		if (strcmp(tmp, path)) {
753 			pr_debug("build <%s> already linked to %s\n",
754 				 sbuild_id, linkname);
755 		}
756 		err = 0;
757 	}
758 
759 	/* Update SDT cache : error is just warned */
760 	if (realname &&
761 	    build_id_cache__add_sdt_cache(sbuild_id, realname, nsi) < 0)
762 		pr_debug4("Failed to update/scan SDT cache for %s\n", realname);
763 
764 out_free:
765 	free(filename);
766 	free(debugfile);
767 	free(dir_name);
768 	free(linkname);
769 	return err;
770 }
771 
772 int __build_id_cache__add_s(const char *sbuild_id, const char *name,
773 			    struct nsinfo *nsi, bool is_kallsyms, bool is_vdso,
774 			    const char *proper_name, const char *root_dir)
775 {
776 	char *realname = NULL;
777 	int err = -1;
778 
779 	if (!is_kallsyms) {
780 		if (!is_vdso)
781 			realname = nsinfo__realpath(name, nsi);
782 		else
783 			realname = realpath(name, NULL);
784 		if (!realname)
785 			goto out_free;
786 	}
787 
788 	err = build_id_cache__add(sbuild_id, name, realname, nsi,
789 				  is_kallsyms, is_vdso, proper_name, root_dir);
790 out_free:
791 	if (!is_kallsyms)
792 		free(realname);
793 	return err;
794 }
795 
796 static int build_id_cache__add_b(const struct build_id *bid,
797 				 const char *name, struct nsinfo *nsi,
798 				 bool is_kallsyms, bool is_vdso,
799 				 const char *proper_name,
800 				 const char *root_dir)
801 {
802 	char sbuild_id[SBUILD_ID_SIZE];
803 
804 	build_id__sprintf(bid, sbuild_id);
805 
806 	return __build_id_cache__add_s(sbuild_id, name, nsi, is_kallsyms,
807 				       is_vdso, proper_name, root_dir);
808 }
809 
810 bool build_id_cache__cached(const char *sbuild_id)
811 {
812 	bool ret = false;
813 	char *filename = build_id_cache__linkname(sbuild_id, NULL, 0);
814 
815 	if (filename && !access(filename, F_OK))
816 		ret = true;
817 	free(filename);
818 
819 	return ret;
820 }
821 
822 int build_id_cache__remove_s(const char *sbuild_id)
823 {
824 	const size_t size = PATH_MAX;
825 	char *filename = zalloc(size),
826 	     *linkname = zalloc(size), *tmp;
827 	int err = -1;
828 
829 	if (filename == NULL || linkname == NULL)
830 		goto out_free;
831 
832 	if (!build_id_cache__linkname(sbuild_id, linkname, size))
833 		goto out_free;
834 
835 	if (access(linkname, F_OK))
836 		goto out_free;
837 
838 	if (readlink(linkname, filename, size - 1) < 0)
839 		goto out_free;
840 
841 	if (unlink(linkname))
842 		goto out_free;
843 
844 	/*
845 	 * Since the link is relative, we must make it absolute:
846 	 */
847 	tmp = strrchr(linkname, '/') + 1;
848 	snprintf(tmp, size - (tmp - linkname), "%s", filename);
849 
850 	if (rm_rf(linkname))
851 		goto out_free;
852 
853 	err = 0;
854 out_free:
855 	free(filename);
856 	free(linkname);
857 	return err;
858 }
859 
860 static int filename__read_build_id_ns(const char *filename,
861 				      struct build_id *bid,
862 				      struct nsinfo *nsi)
863 {
864 	struct nscookie nsc;
865 	int ret;
866 
867 	nsinfo__mountns_enter(nsi, &nsc);
868 	ret = filename__read_build_id(filename, bid);
869 	nsinfo__mountns_exit(&nsc);
870 
871 	return ret;
872 }
873 
874 static bool dso__build_id_mismatch(struct dso *dso, const char *name)
875 {
876 	struct build_id bid;
877 	bool ret = false;
878 
879 	mutex_lock(dso__lock(dso));
880 	if (filename__read_build_id_ns(name, &bid, dso__nsinfo(dso)) >= 0)
881 		ret = !dso__build_id_equal(dso, &bid);
882 
883 	mutex_unlock(dso__lock(dso));
884 
885 	return ret;
886 }
887 
888 static int dso__cache_build_id(struct dso *dso, struct machine *machine,
889 			       void *priv __maybe_unused)
890 {
891 	bool is_kallsyms = dso__is_kallsyms(dso);
892 	bool is_vdso = dso__is_vdso(dso);
893 	const char *name = dso__long_name(dso);
894 	const char *proper_name = NULL;
895 	const char *root_dir = NULL;
896 	char *allocated_name = NULL;
897 	int ret = 0;
898 
899 	if (!dso__has_build_id(dso))
900 		return 0;
901 
902 	if (dso__is_kcore(dso)) {
903 		is_kallsyms = true;
904 		name = machine->mmap_name;
905 	}
906 
907 	if (!machine__is_host(machine)) {
908 		if (*machine->root_dir) {
909 			root_dir = machine->root_dir;
910 			ret = asprintf(&allocated_name, "%s/%s", root_dir, name);
911 			if (ret < 0)
912 				return ret;
913 			proper_name = name;
914 			name = allocated_name;
915 		} else if (is_kallsyms) {
916 			/* Cannot get guest kallsyms */
917 			return 0;
918 		}
919 	}
920 
921 	if (!is_kallsyms && dso__build_id_mismatch(dso, name))
922 		goto out_free;
923 
924 	mutex_lock(dso__lock(dso));
925 	ret = build_id_cache__add_b(dso__bid(dso), name, dso__nsinfo(dso),
926 				    is_kallsyms, is_vdso, proper_name, root_dir);
927 	mutex_unlock(dso__lock(dso));
928 out_free:
929 	free(allocated_name);
930 	return ret;
931 }
932 
933 static int
934 machines__for_each_dso(struct machines *machines, machine__dso_t fn, void *priv)
935 {
936 	int ret = machine__for_each_dso(&machines->host, fn, priv);
937 	struct rb_node *nd;
938 
939 	for (nd = rb_first_cached(&machines->guests); nd;
940 	     nd = rb_next(nd)) {
941 		struct machine *pos = rb_entry(nd, struct machine, rb_node);
942 
943 		ret |= machine__for_each_dso(pos, fn, priv);
944 	}
945 	return ret ? -1 : 0;
946 }
947 
948 int __perf_session__cache_build_ids(struct perf_session *session,
949 				    machine__dso_t fn, void *priv)
950 {
951 	if (no_buildid_cache)
952 		return 0;
953 
954 	if (mkdir(buildid_dir, 0755) != 0 && errno != EEXIST)
955 		return -1;
956 
957 	return machines__for_each_dso(&session->machines, fn, priv) ?  -1 : 0;
958 }
959 
960 int perf_session__cache_build_ids(struct perf_session *session)
961 {
962 	return __perf_session__cache_build_ids(session, dso__cache_build_id, NULL);
963 }
964 
965 static bool machine__read_build_ids(struct machine *machine, bool with_hits)
966 {
967 	return dsos__read_build_ids(&machine->dsos, with_hits);
968 }
969 
970 bool perf_session__read_build_ids(struct perf_session *session, bool with_hits)
971 {
972 	struct rb_node *nd;
973 	bool ret = machine__read_build_ids(&session->machines.host, with_hits);
974 
975 	for (nd = rb_first_cached(&session->machines.guests); nd;
976 	     nd = rb_next(nd)) {
977 		struct machine *pos = rb_entry(nd, struct machine, rb_node);
978 		ret |= machine__read_build_ids(pos, with_hits);
979 	}
980 
981 	return ret;
982 }
983 
984 void build_id__init(struct build_id *bid, const u8 *data, size_t size)
985 {
986 	WARN_ON(size > BUILD_ID_SIZE);
987 	memcpy(bid->data, data, size);
988 	bid->size = size;
989 }
990 
991 bool build_id__is_defined(const struct build_id *bid)
992 {
993 	return bid && bid->size ? !!memchr_inv(bid->data, 0, bid->size) : false;
994 }
995