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