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