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