xref: /linux/tools/perf/util/build-id.c (revision 7e27239d2230394a797e2791bccf7ad24fc45c43)
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 pathbuf[PATH_MAX];
590 	char *debugfile;
591 	struct nscookie nsc;
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 	/* See the build id note in dso__read_binary_type_filename(). */
603 	if (symbol_conf.symfs_layout_flat)
604 		scnprintf(pathbuf, PATH_MAX, "/%s.debug", sbuild_id);
605 	else
606 		scnprintf(pathbuf, PATH_MAX, "%s%.2s/%s.debug", dirname,
607 			  sbuild_id, sbuild_id + 2);
608 	__symbol__join_symfs(debugfile, PATH_MAX, pathbuf);
609 
610 	nsinfo__mountns_enter(nsi, &nsc);
611 	realname = realpath(debugfile, NULL);
612 	if (realname && access(realname, R_OK))
613 		zfree(&realname);
614 	nsinfo__mountns_exit(&nsc);
615 
616 #ifdef HAVE_DEBUGINFOD_SUPPORT
617 	if (realname == NULL) {
618 		debuginfod_client* c;
619 
620 		pr_debug("Downloading debug info with build id %s\n", sbuild_id);
621 
622 		c = debuginfod_begin();
623 		if (c != NULL) {
624 			int fd = debuginfod_find_debuginfo(c,
625 					(const unsigned char*)sbuild_id, 0,
626 					&realname);
627 			if (fd >= 0)
628 				close(fd); /* retaining reference by realname */
629 			debuginfod_end(c);
630 		}
631 	}
632 #endif
633 
634 out:
635 	free(debugfile);
636 	return realname;
637 }
638 
639 int
640 build_id_cache__add(const char *sbuild_id, const char *name, const char *realname,
641 		    struct nsinfo *nsi, bool is_kallsyms, bool is_vdso,
642 		    const char *proper_name, const char *root_dir)
643 {
644 	const size_t size = PATH_MAX;
645 	char *filename = NULL, *dir_name = NULL, *linkname = zalloc(size), *tmp;
646 	char *debugfile = NULL;
647 	int err = -1;
648 
649 	if (!proper_name)
650 		proper_name = name;
651 
652 	dir_name = build_id_cache__cachedir(sbuild_id, proper_name, nsi, is_kallsyms,
653 					    is_vdso);
654 	if (!dir_name)
655 		goto out_free;
656 
657 	/* Remove old style build-id cache */
658 	if (is_regular_file(dir_name))
659 		if (unlink(dir_name))
660 			goto out_free;
661 
662 	if (mkdir_p(dir_name, 0755))
663 		goto out_free;
664 
665 	/* Save the allocated buildid dirname */
666 	if (asprintf(&filename, "%s/%s", dir_name,
667 		     build_id_cache__basename(is_kallsyms, is_vdso,
668 		     false)) < 0) {
669 		filename = NULL;
670 		goto out_free;
671 	}
672 
673 	if (access(filename, F_OK)) {
674 		if (is_kallsyms) {
675 			if (copyfile("/proc/kallsyms", filename))
676 				goto out_free;
677 		} else if (nsi && nsinfo__need_setns(nsi)) {
678 			if (copyfile_ns(name, filename, nsi))
679 				goto out_free;
680 		} else if (link(realname, filename) && errno != EEXIST) {
681 			struct stat f_stat;
682 
683 			if (!(stat(name, &f_stat) < 0) &&
684 					copyfile_mode(name, filename, f_stat.st_mode))
685 				goto out_free;
686 		}
687 	}
688 
689 	/* Some binaries are stripped, but have .debug files with their symbol
690 	 * table.  Check to see if we can locate one of those, since the elf
691 	 * file itself may not be very useful to users of our tools without a
692 	 * symtab.
693 	 */
694 	if (!is_kallsyms && !is_vdso &&
695 	    strncmp(".ko", name + strlen(name) - 3, 3)) {
696 		debugfile = build_id_cache__find_debug(sbuild_id, nsi, root_dir);
697 		if (debugfile) {
698 			zfree(&filename);
699 			if (asprintf(&filename, "%s/%s", dir_name,
700 			    build_id_cache__basename(false, false, true)) < 0) {
701 				filename = NULL;
702 				goto out_free;
703 			}
704 			if (access(filename, F_OK)) {
705 				if (nsi && nsinfo__need_setns(nsi)) {
706 					if (copyfile_ns(debugfile, filename,
707 							nsi))
708 						goto out_free;
709 				} else if (link(debugfile, filename) &&
710 						errno != EEXIST &&
711 						copyfile(debugfile, filename))
712 					goto out_free;
713 			}
714 		}
715 	}
716 
717 	if (!build_id_cache__linkname(sbuild_id, linkname, size))
718 		goto out_free;
719 	tmp = strrchr(linkname, '/');
720 	*tmp = '\0';
721 
722 	if (access(linkname, X_OK) && mkdir_p(linkname, 0755))
723 		goto out_free;
724 
725 	*tmp = '/';
726 	tmp = dir_name + strlen(buildid_dir) - 5;
727 	memcpy(tmp, "../..", 5);
728 
729 	if (symlink(tmp, linkname) == 0) {
730 		err = 0;
731 	} else if (errno == EEXIST) {
732 		char path[PATH_MAX];
733 		ssize_t len;
734 
735 		len = readlink(linkname, path, sizeof(path) - 1);
736 		if (len <= 0) {
737 			pr_err("Can't read link: %s\n", linkname);
738 			goto out_free;
739 		}
740 		path[len] = '\0';
741 
742 		if (strcmp(tmp, path)) {
743 			pr_debug("build <%s> already linked to %s\n",
744 				 sbuild_id, linkname);
745 		}
746 		err = 0;
747 	}
748 
749 	/* Update SDT cache : error is just warned */
750 	if (realname &&
751 	    build_id_cache__add_sdt_cache(sbuild_id, realname, nsi) < 0)
752 		pr_debug4("Failed to update/scan SDT cache for %s\n", realname);
753 
754 out_free:
755 	free(filename);
756 	free(debugfile);
757 	free(dir_name);
758 	free(linkname);
759 	return err;
760 }
761 
762 int __build_id_cache__add_s(const char *sbuild_id, const char *name,
763 			    struct nsinfo *nsi, bool is_kallsyms, bool is_vdso,
764 			    const char *proper_name, const char *root_dir)
765 {
766 	char *realname = NULL;
767 	int err = -1;
768 
769 	if (!is_kallsyms) {
770 		if (!is_vdso)
771 			realname = nsinfo__realpath(name, nsi);
772 		else
773 			realname = realpath(name, NULL);
774 		if (!realname)
775 			goto out_free;
776 	}
777 
778 	err = build_id_cache__add(sbuild_id, name, realname, nsi,
779 				  is_kallsyms, is_vdso, proper_name, root_dir);
780 out_free:
781 	if (!is_kallsyms)
782 		free(realname);
783 	return err;
784 }
785 
786 static int build_id_cache__add_b(const struct build_id *bid,
787 				 const char *name, struct nsinfo *nsi,
788 				 bool is_kallsyms, bool is_vdso,
789 				 const char *proper_name,
790 				 const char *root_dir)
791 {
792 	char sbuild_id[SBUILD_ID_SIZE];
793 
794 	build_id__snprintf(bid, sbuild_id, sizeof(sbuild_id));
795 
796 	return __build_id_cache__add_s(sbuild_id, name, nsi, is_kallsyms,
797 				       is_vdso, proper_name, root_dir);
798 }
799 
800 bool build_id_cache__cached(const char *sbuild_id)
801 {
802 	bool ret = false;
803 	char *filename = build_id_cache__linkname(sbuild_id, NULL, 0);
804 
805 	if (filename && !access(filename, F_OK))
806 		ret = true;
807 	free(filename);
808 
809 	return ret;
810 }
811 
812 int build_id_cache__remove_s(const char *sbuild_id)
813 {
814 	const size_t size = PATH_MAX;
815 	char *filename = zalloc(size),
816 	     *linkname = zalloc(size), *tmp;
817 	int err = -1;
818 
819 	if (filename == NULL || linkname == NULL)
820 		goto out_free;
821 
822 	if (!build_id_cache__linkname(sbuild_id, linkname, size))
823 		goto out_free;
824 
825 	if (access(linkname, F_OK))
826 		goto out_free;
827 
828 	if (readlink(linkname, filename, size - 1) < 0)
829 		goto out_free;
830 
831 	if (unlink(linkname))
832 		goto out_free;
833 
834 	/*
835 	 * Since the link is relative, we must make it absolute:
836 	 */
837 	tmp = strrchr(linkname, '/') + 1;
838 	snprintf(tmp, size - (tmp - linkname), "%s", filename);
839 
840 	if (rm_rf(linkname))
841 		goto out_free;
842 
843 	err = 0;
844 out_free:
845 	free(filename);
846 	free(linkname);
847 	return err;
848 }
849 
850 static int filename__read_build_id_ns(const char *filename,
851 				      struct build_id *bid,
852 				      struct nsinfo *nsi)
853 {
854 	struct nscookie nsc;
855 	int ret;
856 
857 	nsinfo__mountns_enter(nsi, &nsc);
858 	ret = filename__read_build_id(filename, bid);
859 	nsinfo__mountns_exit(&nsc);
860 
861 	return ret;
862 }
863 
864 static bool dso__build_id_mismatch(struct dso *dso, const char *name)
865 {
866 	struct build_id bid = { .size = 0, };
867 	bool ret = false;
868 
869 	mutex_lock(dso__lock(dso));
870 	if (filename__read_build_id_ns(name, &bid, dso__nsinfo(dso)) >= 0)
871 		ret = !dso__build_id_equal(dso, &bid);
872 
873 	mutex_unlock(dso__lock(dso));
874 
875 	return ret;
876 }
877 
878 static int dso__cache_build_id(struct dso *dso, struct machine *machine,
879 			       void *priv __maybe_unused)
880 {
881 	bool is_kallsyms = dso__is_kallsyms(dso);
882 	bool is_vdso = dso__is_vdso(dso);
883 	const char *name = dso__long_name(dso);
884 	const char *proper_name = NULL;
885 	const char *root_dir = NULL;
886 	char *allocated_name = NULL;
887 	int ret = 0;
888 
889 	if (!dso__has_build_id(dso) || !dso__hit(dso))
890 		return 0;
891 
892 	if (dso__is_kcore(dso)) {
893 		is_kallsyms = true;
894 		name = machine->mmap_name;
895 	}
896 
897 	if (!machine__is_host(machine)) {
898 		if (*machine->root_dir) {
899 			root_dir = machine->root_dir;
900 			ret = asprintf(&allocated_name, "%s/%s", root_dir, name);
901 			if (ret < 0)
902 				return ret;
903 			proper_name = name;
904 			name = allocated_name;
905 		} else if (is_kallsyms) {
906 			/* Cannot get guest kallsyms */
907 			return 0;
908 		}
909 	}
910 
911 	if (!is_kallsyms && dso__build_id_mismatch(dso, name))
912 		goto out_free;
913 
914 	mutex_lock(dso__lock(dso));
915 	ret = build_id_cache__add_b(dso__bid(dso), name, dso__nsinfo(dso),
916 				    is_kallsyms, is_vdso, proper_name, root_dir);
917 	mutex_unlock(dso__lock(dso));
918 out_free:
919 	free(allocated_name);
920 	return ret;
921 }
922 
923 static int
924 machines__for_each_dso(struct machines *machines, machine__dso_t fn, void *priv)
925 {
926 	int ret = machine__for_each_dso(&machines->host, fn, priv);
927 	struct rb_node *nd;
928 
929 	for (nd = rb_first_cached(&machines->guests); nd;
930 	     nd = rb_next(nd)) {
931 		struct machine *pos = rb_entry(nd, struct machine, rb_node);
932 
933 		ret |= machine__for_each_dso(pos, fn, priv);
934 	}
935 	return ret ? -1 : 0;
936 }
937 
938 int __perf_session__cache_build_ids(struct perf_session *session,
939 				    machine__dso_t fn, void *priv)
940 {
941 	if (no_buildid_cache)
942 		return 0;
943 
944 	if (mkdir(buildid_dir, 0755) != 0 && errno != EEXIST)
945 		return -1;
946 
947 	return machines__for_each_dso(&session->machines, fn, priv) ?  -1 : 0;
948 }
949 
950 int perf_session__cache_build_ids(struct perf_session *session)
951 {
952 	return __perf_session__cache_build_ids(session, dso__cache_build_id, NULL);
953 }
954 
955 static bool machine__read_build_ids(struct machine *machine, bool with_hits)
956 {
957 	return dsos__read_build_ids(&machine->dsos, with_hits);
958 }
959 
960 bool perf_session__read_build_ids(struct perf_session *session, bool with_hits)
961 {
962 	struct rb_node *nd;
963 	bool ret = machine__read_build_ids(&session->machines.host, with_hits);
964 
965 	for (nd = rb_first_cached(&session->machines.guests); nd;
966 	     nd = rb_next(nd)) {
967 		struct machine *pos = rb_entry(nd, struct machine, rb_node);
968 		ret |= machine__read_build_ids(pos, with_hits);
969 	}
970 
971 	return ret;
972 }
973 
974 void build_id__init(struct build_id *bid, const u8 *data, size_t size)
975 {
976 	if (size > BUILD_ID_SIZE) {
977 		pr_debug("Truncating build_id size from %zd\n", size);
978 		size = BUILD_ID_SIZE;
979 	}
980 	memcpy(bid->data, data, size);
981 	bid->size = size;
982 }
983 
984 bool build_id__is_defined(const struct build_id *bid)
985 {
986 	return bid && bid->size ? !!memchr_inv(bid->data, 0, bid->size) : false;
987 }
988