1 // SPDX-License-Identifier: GPL-2.0
2 #include <asm/bug.h>
3 #include <linux/kernel.h>
4 #include <sys/time.h>
5 #include <sys/resource.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <unistd.h>
9 #include <errno.h>
10 #include <fcntl.h>
11 #include "compress.h"
12 #include "path.h"
13 #include "symbol.h"
14 #include "srcline.h"
15 #include "dso.h"
16 #include "machine.h"
17 #include "auxtrace.h"
18 #include "util.h"
19 #include "debug.h"
20 #include "string2.h"
21 #include "vdso.h"
22 
23 static const char * const debuglink_paths[] = {
24 	"%.0s%s",
25 	"%s/%s",
26 	"%s/.debug/%s",
27 	"/usr/lib/debug%s/%s"
28 };
29 
dso__symtab_origin(const struct dso * dso)30 char dso__symtab_origin(const struct dso *dso)
31 {
32 	static const char origin[] = {
33 		[DSO_BINARY_TYPE__KALLSYMS]			= 'k',
34 		[DSO_BINARY_TYPE__VMLINUX]			= 'v',
35 		[DSO_BINARY_TYPE__JAVA_JIT]			= 'j',
36 		[DSO_BINARY_TYPE__DEBUGLINK]			= 'l',
37 		[DSO_BINARY_TYPE__BUILD_ID_CACHE]		= 'B',
38 		[DSO_BINARY_TYPE__BUILD_ID_CACHE_DEBUGINFO]	= 'D',
39 		[DSO_BINARY_TYPE__FEDORA_DEBUGINFO]		= 'f',
40 		[DSO_BINARY_TYPE__UBUNTU_DEBUGINFO]		= 'u',
41 		[DSO_BINARY_TYPE__OPENEMBEDDED_DEBUGINFO]	= 'o',
42 		[DSO_BINARY_TYPE__BUILDID_DEBUGINFO]		= 'b',
43 		[DSO_BINARY_TYPE__SYSTEM_PATH_DSO]		= 'd',
44 		[DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE]		= 'K',
45 		[DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE_COMP]	= 'm',
46 		[DSO_BINARY_TYPE__GUEST_KALLSYMS]		= 'g',
47 		[DSO_BINARY_TYPE__GUEST_KMODULE]		= 'G',
48 		[DSO_BINARY_TYPE__GUEST_KMODULE_COMP]		= 'M',
49 		[DSO_BINARY_TYPE__GUEST_VMLINUX]		= 'V',
50 	};
51 
52 	if (dso == NULL || dso->symtab_type == DSO_BINARY_TYPE__NOT_FOUND)
53 		return '!';
54 	return origin[dso->symtab_type];
55 }
56 
dso__read_binary_type_filename(const struct dso * dso,enum dso_binary_type type,char * root_dir,char * filename,size_t size)57 int dso__read_binary_type_filename(const struct dso *dso,
58 				   enum dso_binary_type type,
59 				   char *root_dir, char *filename, size_t size)
60 {
61 	char build_id_hex[SBUILD_ID_SIZE];
62 	int ret = 0;
63 	size_t len;
64 
65 	switch (type) {
66 	case DSO_BINARY_TYPE__DEBUGLINK:
67 	{
68 		const char *last_slash;
69 		char dso_dir[PATH_MAX];
70 		char symfile[PATH_MAX];
71 		unsigned int i;
72 
73 		len = __symbol__join_symfs(filename, size, dso->long_name);
74 		last_slash = filename + len;
75 		while (last_slash != filename && *last_slash != '/')
76 			last_slash--;
77 
78 		strncpy(dso_dir, filename, last_slash - filename);
79 		dso_dir[last_slash-filename] = '\0';
80 
81 		if (!is_regular_file(filename)) {
82 			ret = -1;
83 			break;
84 		}
85 
86 		ret = filename__read_debuglink(filename, symfile, PATH_MAX);
87 		if (ret)
88 			break;
89 
90 		/* Check predefined locations where debug file might reside */
91 		ret = -1;
92 		for (i = 0; i < ARRAY_SIZE(debuglink_paths); i++) {
93 			snprintf(filename, size,
94 					debuglink_paths[i], dso_dir, symfile);
95 			if (is_regular_file(filename)) {
96 				ret = 0;
97 				break;
98 			}
99 		}
100 
101 		break;
102 	}
103 	case DSO_BINARY_TYPE__BUILD_ID_CACHE:
104 		if (dso__build_id_filename(dso, filename, size, false) == NULL)
105 			ret = -1;
106 		break;
107 
108 	case DSO_BINARY_TYPE__BUILD_ID_CACHE_DEBUGINFO:
109 		if (dso__build_id_filename(dso, filename, size, true) == NULL)
110 			ret = -1;
111 		break;
112 
113 	case DSO_BINARY_TYPE__FEDORA_DEBUGINFO:
114 		len = __symbol__join_symfs(filename, size, "/usr/lib/debug");
115 		snprintf(filename + len, size - len, "%s.debug", dso->long_name);
116 		break;
117 
118 	case DSO_BINARY_TYPE__UBUNTU_DEBUGINFO:
119 		len = __symbol__join_symfs(filename, size, "/usr/lib/debug");
120 		snprintf(filename + len, size - len, "%s", dso->long_name);
121 		break;
122 
123 	case DSO_BINARY_TYPE__OPENEMBEDDED_DEBUGINFO:
124 	{
125 		const char *last_slash;
126 		size_t dir_size;
127 
128 		last_slash = dso->long_name + dso->long_name_len;
129 		while (last_slash != dso->long_name && *last_slash != '/')
130 			last_slash--;
131 
132 		len = __symbol__join_symfs(filename, size, "");
133 		dir_size = last_slash - dso->long_name + 2;
134 		if (dir_size > (size - len)) {
135 			ret = -1;
136 			break;
137 		}
138 		len += scnprintf(filename + len, dir_size, "%s",  dso->long_name);
139 		len += scnprintf(filename + len , size - len, ".debug%s",
140 								last_slash);
141 		break;
142 	}
143 
144 	case DSO_BINARY_TYPE__BUILDID_DEBUGINFO:
145 		if (!dso->has_build_id) {
146 			ret = -1;
147 			break;
148 		}
149 
150 		build_id__sprintf(dso->build_id,
151 				  sizeof(dso->build_id),
152 				  build_id_hex);
153 		len = __symbol__join_symfs(filename, size, "/usr/lib/debug/.build-id/");
154 		snprintf(filename + len, size - len, "%.2s/%s.debug",
155 			 build_id_hex, build_id_hex + 2);
156 		break;
157 
158 	case DSO_BINARY_TYPE__VMLINUX:
159 	case DSO_BINARY_TYPE__GUEST_VMLINUX:
160 	case DSO_BINARY_TYPE__SYSTEM_PATH_DSO:
161 		__symbol__join_symfs(filename, size, dso->long_name);
162 		break;
163 
164 	case DSO_BINARY_TYPE__GUEST_KMODULE:
165 	case DSO_BINARY_TYPE__GUEST_KMODULE_COMP:
166 		path__join3(filename, size, symbol_conf.symfs,
167 			    root_dir, dso->long_name);
168 		break;
169 
170 	case DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE:
171 	case DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE_COMP:
172 		__symbol__join_symfs(filename, size, dso->long_name);
173 		break;
174 
175 	case DSO_BINARY_TYPE__KCORE:
176 	case DSO_BINARY_TYPE__GUEST_KCORE:
177 		snprintf(filename, size, "%s", dso->long_name);
178 		break;
179 
180 	default:
181 	case DSO_BINARY_TYPE__KALLSYMS:
182 	case DSO_BINARY_TYPE__GUEST_KALLSYMS:
183 	case DSO_BINARY_TYPE__JAVA_JIT:
184 	case DSO_BINARY_TYPE__NOT_FOUND:
185 		ret = -1;
186 		break;
187 	}
188 
189 	return ret;
190 }
191 
192 enum {
193 	COMP_ID__NONE = 0,
194 };
195 
196 static const struct {
197 	const char *fmt;
198 	int (*decompress)(const char *input, int output);
199 	bool (*is_compressed)(const char *input);
200 } compressions[] = {
201 	[COMP_ID__NONE] = { .fmt = NULL, },
202 #ifdef HAVE_ZLIB_SUPPORT
203 	{ "gz", gzip_decompress_to_file, gzip_is_compressed },
204 #endif
205 #ifdef HAVE_LZMA_SUPPORT
206 	{ "xz", lzma_decompress_to_file, lzma_is_compressed },
207 #endif
208 	{ NULL, NULL, NULL },
209 };
210 
is_supported_compression(const char * ext)211 static int is_supported_compression(const char *ext)
212 {
213 	unsigned i;
214 
215 	for (i = 1; compressions[i].fmt; i++) {
216 		if (!strcmp(ext, compressions[i].fmt))
217 			return i;
218 	}
219 	return COMP_ID__NONE;
220 }
221 
is_kernel_module(const char * pathname,int cpumode)222 bool is_kernel_module(const char *pathname, int cpumode)
223 {
224 	struct kmod_path m;
225 	int mode = cpumode & PERF_RECORD_MISC_CPUMODE_MASK;
226 
227 	WARN_ONCE(mode != cpumode,
228 		  "Internal error: passing unmasked cpumode (%x) to is_kernel_module",
229 		  cpumode);
230 
231 	switch (mode) {
232 	case PERF_RECORD_MISC_USER:
233 	case PERF_RECORD_MISC_HYPERVISOR:
234 	case PERF_RECORD_MISC_GUEST_USER:
235 		return false;
236 	/* Treat PERF_RECORD_MISC_CPUMODE_UNKNOWN as kernel */
237 	default:
238 		if (kmod_path__parse(&m, pathname)) {
239 			pr_err("Failed to check whether %s is a kernel module or not. Assume it is.",
240 					pathname);
241 			return true;
242 		}
243 	}
244 
245 	return m.kmod;
246 }
247 
dso__needs_decompress(struct dso * dso)248 bool dso__needs_decompress(struct dso *dso)
249 {
250 	return dso->symtab_type == DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE_COMP ||
251 		dso->symtab_type == DSO_BINARY_TYPE__GUEST_KMODULE_COMP;
252 }
253 
decompress_kmodule(struct dso * dso,const char * name,char * pathname,size_t len)254 static int decompress_kmodule(struct dso *dso, const char *name,
255 			      char *pathname, size_t len)
256 {
257 	char tmpbuf[] = KMOD_DECOMP_NAME;
258 	int fd = -1;
259 
260 	if (!dso__needs_decompress(dso))
261 		return -1;
262 
263 	if (dso->comp == COMP_ID__NONE)
264 		return -1;
265 
266 	/*
267 	 * We have proper compression id for DSO and yet the file
268 	 * behind the 'name' can still be plain uncompressed object.
269 	 *
270 	 * The reason is behind the logic we open the DSO object files,
271 	 * when we try all possible 'debug' objects until we find the
272 	 * data. So even if the DSO is represented by 'krava.xz' module,
273 	 * we can end up here opening ~/.debug/....23432432/debug' file
274 	 * which is not compressed.
275 	 *
276 	 * To keep this transparent, we detect this and return the file
277 	 * descriptor to the uncompressed file.
278 	 */
279 	if (!compressions[dso->comp].is_compressed(name))
280 		return open(name, O_RDONLY);
281 
282 	fd = mkstemp(tmpbuf);
283 	if (fd < 0) {
284 		dso->load_errno = errno;
285 		return -1;
286 	}
287 
288 	if (compressions[dso->comp].decompress(name, fd)) {
289 		dso->load_errno = DSO_LOAD_ERRNO__DECOMPRESSION_FAILURE;
290 		close(fd);
291 		fd = -1;
292 	}
293 
294 	if (!pathname || (fd < 0))
295 		unlink(tmpbuf);
296 
297 	if (pathname && (fd >= 0))
298 		strncpy(pathname, tmpbuf, len);
299 
300 	return fd;
301 }
302 
dso__decompress_kmodule_fd(struct dso * dso,const char * name)303 int dso__decompress_kmodule_fd(struct dso *dso, const char *name)
304 {
305 	return decompress_kmodule(dso, name, NULL, 0);
306 }
307 
dso__decompress_kmodule_path(struct dso * dso,const char * name,char * pathname,size_t len)308 int dso__decompress_kmodule_path(struct dso *dso, const char *name,
309 				 char *pathname, size_t len)
310 {
311 	int fd = decompress_kmodule(dso, name, pathname, len);
312 
313 	close(fd);
314 	return fd >= 0 ? 0 : -1;
315 }
316 
317 /*
318  * Parses kernel module specified in @path and updates
319  * @m argument like:
320  *
321  *    @comp - true if @path contains supported compression suffix,
322  *            false otherwise
323  *    @kmod - true if @path contains '.ko' suffix in right position,
324  *            false otherwise
325  *    @name - if (@alloc_name && @kmod) is true, it contains strdup-ed base name
326  *            of the kernel module without suffixes, otherwise strudup-ed
327  *            base name of @path
328  *    @ext  - if (@alloc_ext && @comp) is true, it contains strdup-ed string
329  *            the compression suffix
330  *
331  * Returns 0 if there's no strdup error, -ENOMEM otherwise.
332  */
__kmod_path__parse(struct kmod_path * m,const char * path,bool alloc_name)333 int __kmod_path__parse(struct kmod_path *m, const char *path,
334 		       bool alloc_name)
335 {
336 	const char *name = strrchr(path, '/');
337 	const char *ext  = strrchr(path, '.');
338 	bool is_simple_name = false;
339 
340 	memset(m, 0x0, sizeof(*m));
341 	name = name ? name + 1 : path;
342 
343 	/*
344 	 * '.' is also a valid character for module name. For example:
345 	 * [aaa.bbb] is a valid module name. '[' should have higher
346 	 * priority than '.ko' suffix.
347 	 *
348 	 * The kernel names are from machine__mmap_name. Such
349 	 * name should belong to kernel itself, not kernel module.
350 	 */
351 	if (name[0] == '[') {
352 		is_simple_name = true;
353 		if ((strncmp(name, "[kernel.kallsyms]", 17) == 0) ||
354 		    (strncmp(name, "[guest.kernel.kallsyms", 22) == 0) ||
355 		    (strncmp(name, "[vdso]", 6) == 0) ||
356 		    (strncmp(name, "[vdso32]", 8) == 0) ||
357 		    (strncmp(name, "[vdsox32]", 9) == 0) ||
358 		    (strncmp(name, "[vsyscall]", 10) == 0)) {
359 			m->kmod = false;
360 
361 		} else
362 			m->kmod = true;
363 	}
364 
365 	/* No extension, just return name. */
366 	if ((ext == NULL) || is_simple_name) {
367 		if (alloc_name) {
368 			m->name = strdup(name);
369 			return m->name ? 0 : -ENOMEM;
370 		}
371 		return 0;
372 	}
373 
374 	m->comp = is_supported_compression(ext + 1);
375 	if (m->comp > COMP_ID__NONE)
376 		ext -= 3;
377 
378 	/* Check .ko extension only if there's enough name left. */
379 	if (ext > name)
380 		m->kmod = !strncmp(ext, ".ko", 3);
381 
382 	if (alloc_name) {
383 		if (m->kmod) {
384 			if (asprintf(&m->name, "[%.*s]", (int) (ext - name), name) == -1)
385 				return -ENOMEM;
386 		} else {
387 			if (asprintf(&m->name, "%s", name) == -1)
388 				return -ENOMEM;
389 		}
390 
391 		strxfrchar(m->name, '-', '_');
392 	}
393 
394 	return 0;
395 }
396 
dso__set_module_info(struct dso * dso,struct kmod_path * m,struct machine * machine)397 void dso__set_module_info(struct dso *dso, struct kmod_path *m,
398 			  struct machine *machine)
399 {
400 	if (machine__is_host(machine))
401 		dso->symtab_type = DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE;
402 	else
403 		dso->symtab_type = DSO_BINARY_TYPE__GUEST_KMODULE;
404 
405 	/* _KMODULE_COMP should be next to _KMODULE */
406 	if (m->kmod && m->comp) {
407 		dso->symtab_type++;
408 		dso->comp = m->comp;
409 	}
410 
411 	dso__set_short_name(dso, strdup(m->name), true);
412 }
413 
414 /*
415  * Global list of open DSOs and the counter.
416  */
417 static LIST_HEAD(dso__data_open);
418 static long dso__data_open_cnt;
419 static pthread_mutex_t dso__data_open_lock = PTHREAD_MUTEX_INITIALIZER;
420 
dso__list_add(struct dso * dso)421 static void dso__list_add(struct dso *dso)
422 {
423 	list_add_tail(&dso->data.open_entry, &dso__data_open);
424 	dso__data_open_cnt++;
425 }
426 
dso__list_del(struct dso * dso)427 static void dso__list_del(struct dso *dso)
428 {
429 	list_del(&dso->data.open_entry);
430 	WARN_ONCE(dso__data_open_cnt <= 0,
431 		  "DSO data fd counter out of bounds.");
432 	dso__data_open_cnt--;
433 }
434 
435 static void close_first_dso(void);
436 
do_open(char * name)437 static int do_open(char *name)
438 {
439 	int fd;
440 	char sbuf[STRERR_BUFSIZE];
441 
442 	do {
443 		fd = open(name, O_RDONLY|O_CLOEXEC);
444 		if (fd >= 0)
445 			return fd;
446 
447 		pr_debug("dso open failed: %s\n",
448 			 str_error_r(errno, sbuf, sizeof(sbuf)));
449 		if (!dso__data_open_cnt || errno != EMFILE)
450 			break;
451 
452 		close_first_dso();
453 	} while (1);
454 
455 	return -1;
456 }
457 
__open_dso(struct dso * dso,struct machine * machine)458 static int __open_dso(struct dso *dso, struct machine *machine)
459 {
460 	int fd = -EINVAL;
461 	char *root_dir = (char *)"";
462 	char *name = malloc(PATH_MAX);
463 	bool decomp = false;
464 
465 	if (!name)
466 		return -ENOMEM;
467 
468 	if (machine)
469 		root_dir = machine->root_dir;
470 
471 	if (dso__read_binary_type_filename(dso, dso->binary_type,
472 					    root_dir, name, PATH_MAX))
473 		goto out;
474 
475 	if (!is_regular_file(name))
476 		goto out;
477 
478 	if (dso__needs_decompress(dso)) {
479 		char newpath[KMOD_DECOMP_LEN];
480 		size_t len = sizeof(newpath);
481 
482 		if (dso__decompress_kmodule_path(dso, name, newpath, len) < 0) {
483 			fd = -dso->load_errno;
484 			goto out;
485 		}
486 
487 		decomp = true;
488 		strcpy(name, newpath);
489 	}
490 
491 	fd = do_open(name);
492 
493 	if (decomp)
494 		unlink(name);
495 
496 out:
497 	free(name);
498 	return fd;
499 }
500 
501 static void check_data_close(void);
502 
503 /**
504  * dso_close - Open DSO data file
505  * @dso: dso object
506  *
507  * Open @dso's data file descriptor and updates
508  * list/count of open DSO objects.
509  */
open_dso(struct dso * dso,struct machine * machine)510 static int open_dso(struct dso *dso, struct machine *machine)
511 {
512 	int fd;
513 	struct nscookie nsc;
514 
515 	if (dso->binary_type != DSO_BINARY_TYPE__BUILD_ID_CACHE)
516 		nsinfo__mountns_enter(dso->nsinfo, &nsc);
517 	fd = __open_dso(dso, machine);
518 	if (dso->binary_type != DSO_BINARY_TYPE__BUILD_ID_CACHE)
519 		nsinfo__mountns_exit(&nsc);
520 
521 	if (fd >= 0) {
522 		dso__list_add(dso);
523 		/*
524 		 * Check if we crossed the allowed number
525 		 * of opened DSOs and close one if needed.
526 		 */
527 		check_data_close();
528 	}
529 
530 	return fd;
531 }
532 
close_data_fd(struct dso * dso)533 static void close_data_fd(struct dso *dso)
534 {
535 	if (dso->data.fd >= 0) {
536 		close(dso->data.fd);
537 		dso->data.fd = -1;
538 		dso->data.file_size = 0;
539 		dso__list_del(dso);
540 	}
541 }
542 
543 /**
544  * dso_close - Close DSO data file
545  * @dso: dso object
546  *
547  * Close @dso's data file descriptor and updates
548  * list/count of open DSO objects.
549  */
close_dso(struct dso * dso)550 static void close_dso(struct dso *dso)
551 {
552 	close_data_fd(dso);
553 }
554 
close_first_dso(void)555 static void close_first_dso(void)
556 {
557 	struct dso *dso;
558 
559 	dso = list_first_entry(&dso__data_open, struct dso, data.open_entry);
560 	close_dso(dso);
561 }
562 
get_fd_limit(void)563 static rlim_t get_fd_limit(void)
564 {
565 	struct rlimit l;
566 	rlim_t limit = 0;
567 
568 	/* Allow half of the current open fd limit. */
569 	if (getrlimit(RLIMIT_NOFILE, &l) == 0) {
570 		if (l.rlim_cur == RLIM_INFINITY)
571 			limit = l.rlim_cur;
572 		else
573 			limit = l.rlim_cur / 2;
574 	} else {
575 		pr_err("failed to get fd limit\n");
576 		limit = 1;
577 	}
578 
579 	return limit;
580 }
581 
582 static rlim_t fd_limit;
583 
584 /*
585  * Used only by tests/dso-data.c to reset the environment
586  * for tests. I dont expect we should change this during
587  * standard runtime.
588  */
reset_fd_limit(void)589 void reset_fd_limit(void)
590 {
591 	fd_limit = 0;
592 }
593 
may_cache_fd(void)594 static bool may_cache_fd(void)
595 {
596 	if (!fd_limit)
597 		fd_limit = get_fd_limit();
598 
599 	if (fd_limit == RLIM_INFINITY)
600 		return true;
601 
602 	return fd_limit > (rlim_t) dso__data_open_cnt;
603 }
604 
605 /*
606  * Check and close LRU dso if we crossed allowed limit
607  * for opened dso file descriptors. The limit is half
608  * of the RLIMIT_NOFILE files opened.
609 */
check_data_close(void)610 static void check_data_close(void)
611 {
612 	bool cache_fd = may_cache_fd();
613 
614 	if (!cache_fd)
615 		close_first_dso();
616 }
617 
618 /**
619  * dso__data_close - Close DSO data file
620  * @dso: dso object
621  *
622  * External interface to close @dso's data file descriptor.
623  */
dso__data_close(struct dso * dso)624 void dso__data_close(struct dso *dso)
625 {
626 	pthread_mutex_lock(&dso__data_open_lock);
627 	close_dso(dso);
628 	pthread_mutex_unlock(&dso__data_open_lock);
629 }
630 
try_to_open_dso(struct dso * dso,struct machine * machine)631 static void try_to_open_dso(struct dso *dso, struct machine *machine)
632 {
633 	enum dso_binary_type binary_type_data[] = {
634 		DSO_BINARY_TYPE__BUILD_ID_CACHE,
635 		DSO_BINARY_TYPE__SYSTEM_PATH_DSO,
636 		DSO_BINARY_TYPE__NOT_FOUND,
637 	};
638 	int i = 0;
639 
640 	if (dso->data.fd >= 0)
641 		return;
642 
643 	if (dso->binary_type != DSO_BINARY_TYPE__NOT_FOUND) {
644 		dso->data.fd = open_dso(dso, machine);
645 		goto out;
646 	}
647 
648 	do {
649 		dso->binary_type = binary_type_data[i++];
650 
651 		dso->data.fd = open_dso(dso, machine);
652 		if (dso->data.fd >= 0)
653 			goto out;
654 
655 	} while (dso->binary_type != DSO_BINARY_TYPE__NOT_FOUND);
656 out:
657 	if (dso->data.fd >= 0)
658 		dso->data.status = DSO_DATA_STATUS_OK;
659 	else
660 		dso->data.status = DSO_DATA_STATUS_ERROR;
661 }
662 
663 /**
664  * dso__data_get_fd - Get dso's data file descriptor
665  * @dso: dso object
666  * @machine: machine object
667  *
668  * External interface to find dso's file, open it and
669  * returns file descriptor.  It should be paired with
670  * dso__data_put_fd() if it returns non-negative value.
671  */
dso__data_get_fd(struct dso * dso,struct machine * machine)672 int dso__data_get_fd(struct dso *dso, struct machine *machine)
673 {
674 	if (dso->data.status == DSO_DATA_STATUS_ERROR)
675 		return -1;
676 
677 	if (pthread_mutex_lock(&dso__data_open_lock) < 0)
678 		return -1;
679 
680 	try_to_open_dso(dso, machine);
681 
682 	if (dso->data.fd < 0)
683 		pthread_mutex_unlock(&dso__data_open_lock);
684 
685 	return dso->data.fd;
686 }
687 
dso__data_put_fd(struct dso * dso __maybe_unused)688 void dso__data_put_fd(struct dso *dso __maybe_unused)
689 {
690 	pthread_mutex_unlock(&dso__data_open_lock);
691 }
692 
dso__data_status_seen(struct dso * dso,enum dso_data_status_seen by)693 bool dso__data_status_seen(struct dso *dso, enum dso_data_status_seen by)
694 {
695 	u32 flag = 1 << by;
696 
697 	if (dso->data.status_seen & flag)
698 		return true;
699 
700 	dso->data.status_seen |= flag;
701 
702 	return false;
703 }
704 
705 static void
dso_cache__free(struct dso * dso)706 dso_cache__free(struct dso *dso)
707 {
708 	struct rb_root *root = &dso->data.cache;
709 	struct rb_node *next = rb_first(root);
710 
711 	pthread_mutex_lock(&dso->lock);
712 	while (next) {
713 		struct dso_cache *cache;
714 
715 		cache = rb_entry(next, struct dso_cache, rb_node);
716 		next = rb_next(&cache->rb_node);
717 		rb_erase(&cache->rb_node, root);
718 		free(cache);
719 	}
720 	pthread_mutex_unlock(&dso->lock);
721 }
722 
dso_cache__find(struct dso * dso,u64 offset)723 static struct dso_cache *dso_cache__find(struct dso *dso, u64 offset)
724 {
725 	const struct rb_root *root = &dso->data.cache;
726 	struct rb_node * const *p = &root->rb_node;
727 	const struct rb_node *parent = NULL;
728 	struct dso_cache *cache;
729 
730 	while (*p != NULL) {
731 		u64 end;
732 
733 		parent = *p;
734 		cache = rb_entry(parent, struct dso_cache, rb_node);
735 		end = cache->offset + DSO__DATA_CACHE_SIZE;
736 
737 		if (offset < cache->offset)
738 			p = &(*p)->rb_left;
739 		else if (offset >= end)
740 			p = &(*p)->rb_right;
741 		else
742 			return cache;
743 	}
744 
745 	return NULL;
746 }
747 
748 static struct dso_cache *
dso_cache__insert(struct dso * dso,struct dso_cache * new)749 dso_cache__insert(struct dso *dso, struct dso_cache *new)
750 {
751 	struct rb_root *root = &dso->data.cache;
752 	struct rb_node **p = &root->rb_node;
753 	struct rb_node *parent = NULL;
754 	struct dso_cache *cache;
755 	u64 offset = new->offset;
756 
757 	pthread_mutex_lock(&dso->lock);
758 	while (*p != NULL) {
759 		u64 end;
760 
761 		parent = *p;
762 		cache = rb_entry(parent, struct dso_cache, rb_node);
763 		end = cache->offset + DSO__DATA_CACHE_SIZE;
764 
765 		if (offset < cache->offset)
766 			p = &(*p)->rb_left;
767 		else if (offset >= end)
768 			p = &(*p)->rb_right;
769 		else
770 			goto out;
771 	}
772 
773 	rb_link_node(&new->rb_node, parent, p);
774 	rb_insert_color(&new->rb_node, root);
775 
776 	cache = NULL;
777 out:
778 	pthread_mutex_unlock(&dso->lock);
779 	return cache;
780 }
781 
782 static ssize_t
dso_cache__memcpy(struct dso_cache * cache,u64 offset,u8 * data,u64 size)783 dso_cache__memcpy(struct dso_cache *cache, u64 offset,
784 		  u8 *data, u64 size)
785 {
786 	u64 cache_offset = offset - cache->offset;
787 	u64 cache_size   = min(cache->size - cache_offset, size);
788 
789 	memcpy(data, cache->data + cache_offset, cache_size);
790 	return cache_size;
791 }
792 
793 static ssize_t
dso_cache__read(struct dso * dso,struct machine * machine,u64 offset,u8 * data,ssize_t size)794 dso_cache__read(struct dso *dso, struct machine *machine,
795 		u64 offset, u8 *data, ssize_t size)
796 {
797 	struct dso_cache *cache;
798 	struct dso_cache *old;
799 	ssize_t ret;
800 
801 	do {
802 		u64 cache_offset;
803 
804 		cache = zalloc(sizeof(*cache) + DSO__DATA_CACHE_SIZE);
805 		if (!cache)
806 			return -ENOMEM;
807 
808 		pthread_mutex_lock(&dso__data_open_lock);
809 
810 		/*
811 		 * dso->data.fd might be closed if other thread opened another
812 		 * file (dso) due to open file limit (RLIMIT_NOFILE).
813 		 */
814 		try_to_open_dso(dso, machine);
815 
816 		if (dso->data.fd < 0) {
817 			ret = -errno;
818 			dso->data.status = DSO_DATA_STATUS_ERROR;
819 			break;
820 		}
821 
822 		cache_offset = offset & DSO__DATA_CACHE_MASK;
823 
824 		ret = pread(dso->data.fd, cache->data, DSO__DATA_CACHE_SIZE, cache_offset);
825 		if (ret <= 0)
826 			break;
827 
828 		cache->offset = cache_offset;
829 		cache->size   = ret;
830 	} while (0);
831 
832 	pthread_mutex_unlock(&dso__data_open_lock);
833 
834 	if (ret > 0) {
835 		old = dso_cache__insert(dso, cache);
836 		if (old) {
837 			/* we lose the race */
838 			free(cache);
839 			cache = old;
840 		}
841 
842 		ret = dso_cache__memcpy(cache, offset, data, size);
843 	}
844 
845 	if (ret <= 0)
846 		free(cache);
847 
848 	return ret;
849 }
850 
dso_cache_read(struct dso * dso,struct machine * machine,u64 offset,u8 * data,ssize_t size)851 static ssize_t dso_cache_read(struct dso *dso, struct machine *machine,
852 			      u64 offset, u8 *data, ssize_t size)
853 {
854 	struct dso_cache *cache;
855 
856 	cache = dso_cache__find(dso, offset);
857 	if (cache)
858 		return dso_cache__memcpy(cache, offset, data, size);
859 	else
860 		return dso_cache__read(dso, machine, offset, data, size);
861 }
862 
863 /*
864  * Reads and caches dso data DSO__DATA_CACHE_SIZE size chunks
865  * in the rb_tree. Any read to already cached data is served
866  * by cached data.
867  */
cached_read(struct dso * dso,struct machine * machine,u64 offset,u8 * data,ssize_t size)868 static ssize_t cached_read(struct dso *dso, struct machine *machine,
869 			   u64 offset, u8 *data, ssize_t size)
870 {
871 	ssize_t r = 0;
872 	u8 *p = data;
873 
874 	do {
875 		ssize_t ret;
876 
877 		ret = dso_cache_read(dso, machine, offset, p, size);
878 		if (ret < 0)
879 			return ret;
880 
881 		/* Reached EOF, return what we have. */
882 		if (!ret)
883 			break;
884 
885 		BUG_ON(ret > size);
886 
887 		r      += ret;
888 		p      += ret;
889 		offset += ret;
890 		size   -= ret;
891 
892 	} while (size);
893 
894 	return r;
895 }
896 
data_file_size(struct dso * dso,struct machine * machine)897 static int data_file_size(struct dso *dso, struct machine *machine)
898 {
899 	int ret = 0;
900 	struct stat st;
901 	char sbuf[STRERR_BUFSIZE];
902 
903 	if (dso->data.file_size)
904 		return 0;
905 
906 	if (dso->data.status == DSO_DATA_STATUS_ERROR)
907 		return -1;
908 
909 	pthread_mutex_lock(&dso__data_open_lock);
910 
911 	/*
912 	 * dso->data.fd might be closed if other thread opened another
913 	 * file (dso) due to open file limit (RLIMIT_NOFILE).
914 	 */
915 	try_to_open_dso(dso, machine);
916 
917 	if (dso->data.fd < 0) {
918 		ret = -errno;
919 		dso->data.status = DSO_DATA_STATUS_ERROR;
920 		goto out;
921 	}
922 
923 	if (fstat(dso->data.fd, &st) < 0) {
924 		ret = -errno;
925 		pr_err("dso cache fstat failed: %s\n",
926 		       str_error_r(errno, sbuf, sizeof(sbuf)));
927 		dso->data.status = DSO_DATA_STATUS_ERROR;
928 		goto out;
929 	}
930 	dso->data.file_size = st.st_size;
931 
932 out:
933 	pthread_mutex_unlock(&dso__data_open_lock);
934 	return ret;
935 }
936 
937 /**
938  * dso__data_size - Return dso data size
939  * @dso: dso object
940  * @machine: machine object
941  *
942  * Return: dso data size
943  */
dso__data_size(struct dso * dso,struct machine * machine)944 off_t dso__data_size(struct dso *dso, struct machine *machine)
945 {
946 	if (data_file_size(dso, machine))
947 		return -1;
948 
949 	/* For now just estimate dso data size is close to file size */
950 	return dso->data.file_size;
951 }
952 
data_read_offset(struct dso * dso,struct machine * machine,u64 offset,u8 * data,ssize_t size)953 static ssize_t data_read_offset(struct dso *dso, struct machine *machine,
954 				u64 offset, u8 *data, ssize_t size)
955 {
956 	if (data_file_size(dso, machine))
957 		return -1;
958 
959 	/* Check the offset sanity. */
960 	if (offset > dso->data.file_size)
961 		return -1;
962 
963 	if (offset + size < offset)
964 		return -1;
965 
966 	return cached_read(dso, machine, offset, data, size);
967 }
968 
969 /**
970  * dso__data_read_offset - Read data from dso file offset
971  * @dso: dso object
972  * @machine: machine object
973  * @offset: file offset
974  * @data: buffer to store data
975  * @size: size of the @data buffer
976  *
977  * External interface to read data from dso file offset. Open
978  * dso data file and use cached_read to get the data.
979  */
dso__data_read_offset(struct dso * dso,struct machine * machine,u64 offset,u8 * data,ssize_t size)980 ssize_t dso__data_read_offset(struct dso *dso, struct machine *machine,
981 			      u64 offset, u8 *data, ssize_t size)
982 {
983 	if (dso->data.status == DSO_DATA_STATUS_ERROR)
984 		return -1;
985 
986 	return data_read_offset(dso, machine, offset, data, size);
987 }
988 
989 /**
990  * dso__data_read_addr - Read data from dso address
991  * @dso: dso object
992  * @machine: machine object
993  * @add: virtual memory address
994  * @data: buffer to store data
995  * @size: size of the @data buffer
996  *
997  * External interface to read data from dso address.
998  */
dso__data_read_addr(struct dso * dso,struct map * map,struct machine * machine,u64 addr,u8 * data,ssize_t size)999 ssize_t dso__data_read_addr(struct dso *dso, struct map *map,
1000 			    struct machine *machine, u64 addr,
1001 			    u8 *data, ssize_t size)
1002 {
1003 	u64 offset = map->map_ip(map, addr);
1004 	return dso__data_read_offset(dso, machine, offset, data, size);
1005 }
1006 
dso__new_map(const char * name)1007 struct map *dso__new_map(const char *name)
1008 {
1009 	struct map *map = NULL;
1010 	struct dso *dso = dso__new(name);
1011 
1012 	if (dso)
1013 		map = map__new2(0, dso);
1014 
1015 	return map;
1016 }
1017 
machine__findnew_kernel(struct machine * machine,const char * name,const char * short_name,int dso_type)1018 struct dso *machine__findnew_kernel(struct machine *machine, const char *name,
1019 				    const char *short_name, int dso_type)
1020 {
1021 	/*
1022 	 * The kernel dso could be created by build_id processing.
1023 	 */
1024 	struct dso *dso = machine__findnew_dso(machine, name);
1025 
1026 	/*
1027 	 * We need to run this in all cases, since during the build_id
1028 	 * processing we had no idea this was the kernel dso.
1029 	 */
1030 	if (dso != NULL) {
1031 		dso__set_short_name(dso, short_name, false);
1032 		dso->kernel = dso_type;
1033 	}
1034 
1035 	return dso;
1036 }
1037 
1038 /*
1039  * Find a matching entry and/or link current entry to RB tree.
1040  * Either one of the dso or name parameter must be non-NULL or the
1041  * function will not work.
1042  */
__dso__findlink_by_longname(struct rb_root * root,struct dso * dso,const char * name)1043 static struct dso *__dso__findlink_by_longname(struct rb_root *root,
1044 					       struct dso *dso, const char *name)
1045 {
1046 	struct rb_node **p = &root->rb_node;
1047 	struct rb_node  *parent = NULL;
1048 
1049 	if (!name)
1050 		name = dso->long_name;
1051 	/*
1052 	 * Find node with the matching name
1053 	 */
1054 	while (*p) {
1055 		struct dso *this = rb_entry(*p, struct dso, rb_node);
1056 		int rc = strcmp(name, this->long_name);
1057 
1058 		parent = *p;
1059 		if (rc == 0) {
1060 			/*
1061 			 * In case the new DSO is a duplicate of an existing
1062 			 * one, print a one-time warning & put the new entry
1063 			 * at the end of the list of duplicates.
1064 			 */
1065 			if (!dso || (dso == this))
1066 				return this;	/* Find matching dso */
1067 			/*
1068 			 * The core kernel DSOs may have duplicated long name.
1069 			 * In this case, the short name should be different.
1070 			 * Comparing the short names to differentiate the DSOs.
1071 			 */
1072 			rc = strcmp(dso->short_name, this->short_name);
1073 			if (rc == 0) {
1074 				pr_err("Duplicated dso name: %s\n", name);
1075 				return NULL;
1076 			}
1077 		}
1078 		if (rc < 0)
1079 			p = &parent->rb_left;
1080 		else
1081 			p = &parent->rb_right;
1082 	}
1083 	if (dso) {
1084 		/* Add new node and rebalance tree */
1085 		rb_link_node(&dso->rb_node, parent, p);
1086 		rb_insert_color(&dso->rb_node, root);
1087 		dso->root = root;
1088 	}
1089 	return NULL;
1090 }
1091 
__dso__find_by_longname(struct rb_root * root,const char * name)1092 static inline struct dso *__dso__find_by_longname(struct rb_root *root,
1093 						  const char *name)
1094 {
1095 	return __dso__findlink_by_longname(root, NULL, name);
1096 }
1097 
dso__set_long_name(struct dso * dso,const char * name,bool name_allocated)1098 void dso__set_long_name(struct dso *dso, const char *name, bool name_allocated)
1099 {
1100 	struct rb_root *root = dso->root;
1101 
1102 	if (name == NULL)
1103 		return;
1104 
1105 	if (dso->long_name_allocated)
1106 		free((char *)dso->long_name);
1107 
1108 	if (root) {
1109 		rb_erase(&dso->rb_node, root);
1110 		/*
1111 		 * __dso__findlink_by_longname() isn't guaranteed to add it
1112 		 * back, so a clean removal is required here.
1113 		 */
1114 		RB_CLEAR_NODE(&dso->rb_node);
1115 		dso->root = NULL;
1116 	}
1117 
1118 	dso->long_name		 = name;
1119 	dso->long_name_len	 = strlen(name);
1120 	dso->long_name_allocated = name_allocated;
1121 
1122 	if (root)
1123 		__dso__findlink_by_longname(root, dso, NULL);
1124 }
1125 
dso__set_short_name(struct dso * dso,const char * name,bool name_allocated)1126 void dso__set_short_name(struct dso *dso, const char *name, bool name_allocated)
1127 {
1128 	if (name == NULL)
1129 		return;
1130 
1131 	if (dso->short_name_allocated)
1132 		free((char *)dso->short_name);
1133 
1134 	dso->short_name		  = name;
1135 	dso->short_name_len	  = strlen(name);
1136 	dso->short_name_allocated = name_allocated;
1137 }
1138 
dso__set_basename(struct dso * dso)1139 static void dso__set_basename(struct dso *dso)
1140 {
1141        /*
1142         * basename() may modify path buffer, so we must pass
1143         * a copy.
1144         */
1145        char *base, *lname = strdup(dso->long_name);
1146 
1147        if (!lname)
1148                return;
1149 
1150        /*
1151         * basename() may return a pointer to internal
1152         * storage which is reused in subsequent calls
1153         * so copy the result.
1154         */
1155        base = strdup(basename(lname));
1156 
1157        free(lname);
1158 
1159        if (!base)
1160                return;
1161 
1162        dso__set_short_name(dso, base, true);
1163 }
1164 
dso__name_len(const struct dso * dso)1165 int dso__name_len(const struct dso *dso)
1166 {
1167 	if (!dso)
1168 		return strlen("[unknown]");
1169 	if (verbose > 0)
1170 		return dso->long_name_len;
1171 
1172 	return dso->short_name_len;
1173 }
1174 
dso__loaded(const struct dso * dso)1175 bool dso__loaded(const struct dso *dso)
1176 {
1177 	return dso->loaded;
1178 }
1179 
dso__sorted_by_name(const struct dso * dso)1180 bool dso__sorted_by_name(const struct dso *dso)
1181 {
1182 	return dso->sorted_by_name;
1183 }
1184 
dso__set_sorted_by_name(struct dso * dso)1185 void dso__set_sorted_by_name(struct dso *dso)
1186 {
1187 	dso->sorted_by_name = true;
1188 }
1189 
dso__new(const char * name)1190 struct dso *dso__new(const char *name)
1191 {
1192 	struct dso *dso = calloc(1, sizeof(*dso) + strlen(name) + 1);
1193 
1194 	if (dso != NULL) {
1195 		strcpy(dso->name, name);
1196 		dso__set_long_name(dso, dso->name, false);
1197 		dso__set_short_name(dso, dso->name, false);
1198 		dso->symbols = dso->symbol_names = RB_ROOT;
1199 		dso->data.cache = RB_ROOT;
1200 		dso->inlined_nodes = RB_ROOT;
1201 		dso->srclines = RB_ROOT;
1202 		dso->data.fd = -1;
1203 		dso->data.status = DSO_DATA_STATUS_UNKNOWN;
1204 		dso->symtab_type = DSO_BINARY_TYPE__NOT_FOUND;
1205 		dso->binary_type = DSO_BINARY_TYPE__NOT_FOUND;
1206 		dso->is_64_bit = (sizeof(void *) == 8);
1207 		dso->loaded = 0;
1208 		dso->rel = 0;
1209 		dso->sorted_by_name = 0;
1210 		dso->has_build_id = 0;
1211 		dso->has_srcline = 1;
1212 		dso->a2l_fails = 1;
1213 		dso->kernel = DSO_TYPE_USER;
1214 		dso->needs_swap = DSO_SWAP__UNSET;
1215 		dso->comp = COMP_ID__NONE;
1216 		RB_CLEAR_NODE(&dso->rb_node);
1217 		dso->root = NULL;
1218 		INIT_LIST_HEAD(&dso->node);
1219 		INIT_LIST_HEAD(&dso->data.open_entry);
1220 		pthread_mutex_init(&dso->lock, NULL);
1221 		refcount_set(&dso->refcnt, 1);
1222 	}
1223 
1224 	return dso;
1225 }
1226 
dso__delete(struct dso * dso)1227 void dso__delete(struct dso *dso)
1228 {
1229 	if (!RB_EMPTY_NODE(&dso->rb_node))
1230 		pr_err("DSO %s is still in rbtree when being deleted!\n",
1231 		       dso->long_name);
1232 
1233 	/* free inlines first, as they reference symbols */
1234 	inlines__tree_delete(&dso->inlined_nodes);
1235 	srcline__tree_delete(&dso->srclines);
1236 	symbols__delete(&dso->symbols);
1237 
1238 	if (dso->short_name_allocated) {
1239 		zfree((char **)&dso->short_name);
1240 		dso->short_name_allocated = false;
1241 	}
1242 
1243 	if (dso->long_name_allocated) {
1244 		zfree((char **)&dso->long_name);
1245 		dso->long_name_allocated = false;
1246 	}
1247 
1248 	dso__data_close(dso);
1249 	auxtrace_cache__free(dso->auxtrace_cache);
1250 	dso_cache__free(dso);
1251 	dso__free_a2l(dso);
1252 	zfree(&dso->symsrc_filename);
1253 	nsinfo__zput(dso->nsinfo);
1254 	pthread_mutex_destroy(&dso->lock);
1255 	free(dso);
1256 }
1257 
dso__get(struct dso * dso)1258 struct dso *dso__get(struct dso *dso)
1259 {
1260 	if (dso)
1261 		refcount_inc(&dso->refcnt);
1262 	return dso;
1263 }
1264 
dso__put(struct dso * dso)1265 void dso__put(struct dso *dso)
1266 {
1267 	if (dso && refcount_dec_and_test(&dso->refcnt))
1268 		dso__delete(dso);
1269 }
1270 
dso__set_build_id(struct dso * dso,void * build_id)1271 void dso__set_build_id(struct dso *dso, void *build_id)
1272 {
1273 	memcpy(dso->build_id, build_id, sizeof(dso->build_id));
1274 	dso->has_build_id = 1;
1275 }
1276 
dso__build_id_equal(const struct dso * dso,u8 * build_id)1277 bool dso__build_id_equal(const struct dso *dso, u8 *build_id)
1278 {
1279 	return memcmp(dso->build_id, build_id, sizeof(dso->build_id)) == 0;
1280 }
1281 
dso__read_running_kernel_build_id(struct dso * dso,struct machine * machine)1282 void dso__read_running_kernel_build_id(struct dso *dso, struct machine *machine)
1283 {
1284 	char path[PATH_MAX];
1285 
1286 	if (machine__is_default_guest(machine))
1287 		return;
1288 	sprintf(path, "%s/sys/kernel/notes", machine->root_dir);
1289 	if (sysfs__read_build_id(path, dso->build_id,
1290 				 sizeof(dso->build_id)) == 0)
1291 		dso->has_build_id = true;
1292 }
1293 
dso__kernel_module_get_build_id(struct dso * dso,const char * root_dir)1294 int dso__kernel_module_get_build_id(struct dso *dso,
1295 				    const char *root_dir)
1296 {
1297 	char filename[PATH_MAX];
1298 	/*
1299 	 * kernel module short names are of the form "[module]" and
1300 	 * we need just "module" here.
1301 	 */
1302 	const char *name = dso->short_name + 1;
1303 
1304 	snprintf(filename, sizeof(filename),
1305 		 "%s/sys/module/%.*s/notes/.note.gnu.build-id",
1306 		 root_dir, (int)strlen(name) - 1, name);
1307 
1308 	if (sysfs__read_build_id(filename, dso->build_id,
1309 				 sizeof(dso->build_id)) == 0)
1310 		dso->has_build_id = true;
1311 
1312 	return 0;
1313 }
1314 
__dsos__read_build_ids(struct list_head * head,bool with_hits)1315 bool __dsos__read_build_ids(struct list_head *head, bool with_hits)
1316 {
1317 	bool have_build_id = false;
1318 	struct dso *pos;
1319 	struct nscookie nsc;
1320 
1321 	list_for_each_entry(pos, head, node) {
1322 		if (with_hits && !pos->hit && !dso__is_vdso(pos))
1323 			continue;
1324 		if (pos->has_build_id) {
1325 			have_build_id = true;
1326 			continue;
1327 		}
1328 		nsinfo__mountns_enter(pos->nsinfo, &nsc);
1329 		if (filename__read_build_id(pos->long_name, pos->build_id,
1330 					    sizeof(pos->build_id)) > 0) {
1331 			have_build_id	  = true;
1332 			pos->has_build_id = true;
1333 		}
1334 		nsinfo__mountns_exit(&nsc);
1335 	}
1336 
1337 	return have_build_id;
1338 }
1339 
__dsos__add(struct dsos * dsos,struct dso * dso)1340 void __dsos__add(struct dsos *dsos, struct dso *dso)
1341 {
1342 	list_add_tail(&dso->node, &dsos->head);
1343 	__dso__findlink_by_longname(&dsos->root, dso, NULL);
1344 	/*
1345 	 * It is now in the linked list, grab a reference, then garbage collect
1346 	 * this when needing memory, by looking at LRU dso instances in the
1347 	 * list with atomic_read(&dso->refcnt) == 1, i.e. no references
1348 	 * anywhere besides the one for the list, do, under a lock for the
1349 	 * list: remove it from the list, then a dso__put(), that probably will
1350 	 * be the last and will then call dso__delete(), end of life.
1351 	 *
1352 	 * That, or at the end of the 'struct machine' lifetime, when all
1353 	 * 'struct dso' instances will be removed from the list, in
1354 	 * dsos__exit(), if they have no other reference from some other data
1355 	 * structure.
1356 	 *
1357 	 * E.g.: after processing a 'perf.data' file and storing references
1358 	 * to objects instantiated while processing events, we will have
1359 	 * references to the 'thread', 'map', 'dso' structs all from 'struct
1360 	 * hist_entry' instances, but we may not need anything not referenced,
1361 	 * so we might as well call machines__exit()/machines__delete() and
1362 	 * garbage collect it.
1363 	 */
1364 	dso__get(dso);
1365 }
1366 
dsos__add(struct dsos * dsos,struct dso * dso)1367 void dsos__add(struct dsos *dsos, struct dso *dso)
1368 {
1369 	down_write(&dsos->lock);
1370 	__dsos__add(dsos, dso);
1371 	up_write(&dsos->lock);
1372 }
1373 
__dsos__find(struct dsos * dsos,const char * name,bool cmp_short)1374 struct dso *__dsos__find(struct dsos *dsos, const char *name, bool cmp_short)
1375 {
1376 	struct dso *pos;
1377 
1378 	if (cmp_short) {
1379 		list_for_each_entry(pos, &dsos->head, node)
1380 			if (strcmp(pos->short_name, name) == 0)
1381 				return pos;
1382 		return NULL;
1383 	}
1384 	return __dso__find_by_longname(&dsos->root, name);
1385 }
1386 
dsos__find(struct dsos * dsos,const char * name,bool cmp_short)1387 struct dso *dsos__find(struct dsos *dsos, const char *name, bool cmp_short)
1388 {
1389 	struct dso *dso;
1390 	down_read(&dsos->lock);
1391 	dso = __dsos__find(dsos, name, cmp_short);
1392 	up_read(&dsos->lock);
1393 	return dso;
1394 }
1395 
__dsos__addnew(struct dsos * dsos,const char * name)1396 struct dso *__dsos__addnew(struct dsos *dsos, const char *name)
1397 {
1398 	struct dso *dso = dso__new(name);
1399 
1400 	if (dso != NULL) {
1401 		__dsos__add(dsos, dso);
1402 		dso__set_basename(dso);
1403 		/* Put dso here because __dsos_add already got it */
1404 		dso__put(dso);
1405 	}
1406 	return dso;
1407 }
1408 
__dsos__findnew(struct dsos * dsos,const char * name)1409 struct dso *__dsos__findnew(struct dsos *dsos, const char *name)
1410 {
1411 	struct dso *dso = __dsos__find(dsos, name, false);
1412 
1413 	return dso ? dso : __dsos__addnew(dsos, name);
1414 }
1415 
dsos__findnew(struct dsos * dsos,const char * name)1416 struct dso *dsos__findnew(struct dsos *dsos, const char *name)
1417 {
1418 	struct dso *dso;
1419 	down_write(&dsos->lock);
1420 	dso = dso__get(__dsos__findnew(dsos, name));
1421 	up_write(&dsos->lock);
1422 	return dso;
1423 }
1424 
__dsos__fprintf_buildid(struct list_head * head,FILE * fp,bool (skip)(struct dso * dso,int parm),int parm)1425 size_t __dsos__fprintf_buildid(struct list_head *head, FILE *fp,
1426 			       bool (skip)(struct dso *dso, int parm), int parm)
1427 {
1428 	struct dso *pos;
1429 	size_t ret = 0;
1430 
1431 	list_for_each_entry(pos, head, node) {
1432 		if (skip && skip(pos, parm))
1433 			continue;
1434 		ret += dso__fprintf_buildid(pos, fp);
1435 		ret += fprintf(fp, " %s\n", pos->long_name);
1436 	}
1437 	return ret;
1438 }
1439 
__dsos__fprintf(struct list_head * head,FILE * fp)1440 size_t __dsos__fprintf(struct list_head *head, FILE *fp)
1441 {
1442 	struct dso *pos;
1443 	size_t ret = 0;
1444 
1445 	list_for_each_entry(pos, head, node) {
1446 		ret += dso__fprintf(pos, fp);
1447 	}
1448 
1449 	return ret;
1450 }
1451 
dso__fprintf_buildid(struct dso * dso,FILE * fp)1452 size_t dso__fprintf_buildid(struct dso *dso, FILE *fp)
1453 {
1454 	char sbuild_id[SBUILD_ID_SIZE];
1455 
1456 	build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
1457 	return fprintf(fp, "%s", sbuild_id);
1458 }
1459 
dso__fprintf(struct dso * dso,FILE * fp)1460 size_t dso__fprintf(struct dso *dso, FILE *fp)
1461 {
1462 	struct rb_node *nd;
1463 	size_t ret = fprintf(fp, "dso: %s (", dso->short_name);
1464 
1465 	if (dso->short_name != dso->long_name)
1466 		ret += fprintf(fp, "%s, ", dso->long_name);
1467 	ret += fprintf(fp, "%sloaded, ", dso__loaded(dso) ? "" : "NOT ");
1468 	ret += dso__fprintf_buildid(dso, fp);
1469 	ret += fprintf(fp, ")\n");
1470 	for (nd = rb_first(&dso->symbols); nd; nd = rb_next(nd)) {
1471 		struct symbol *pos = rb_entry(nd, struct symbol, rb_node);
1472 		ret += symbol__fprintf(pos, fp);
1473 	}
1474 
1475 	return ret;
1476 }
1477 
dso__type(struct dso * dso,struct machine * machine)1478 enum dso_type dso__type(struct dso *dso, struct machine *machine)
1479 {
1480 	int fd;
1481 	enum dso_type type = DSO__TYPE_UNKNOWN;
1482 
1483 	fd = dso__data_get_fd(dso, machine);
1484 	if (fd >= 0) {
1485 		type = dso__type_fd(fd);
1486 		dso__data_put_fd(dso);
1487 	}
1488 
1489 	return type;
1490 }
1491 
dso__strerror_load(struct dso * dso,char * buf,size_t buflen)1492 int dso__strerror_load(struct dso *dso, char *buf, size_t buflen)
1493 {
1494 	int idx, errnum = dso->load_errno;
1495 	/*
1496 	 * This must have a same ordering as the enum dso_load_errno.
1497 	 */
1498 	static const char *dso_load__error_str[] = {
1499 	"Internal tools/perf/ library error",
1500 	"Invalid ELF file",
1501 	"Can not read build id",
1502 	"Mismatching build id",
1503 	"Decompression failure",
1504 	};
1505 
1506 	BUG_ON(buflen == 0);
1507 
1508 	if (errnum >= 0) {
1509 		const char *err = str_error_r(errnum, buf, buflen);
1510 
1511 		if (err != buf)
1512 			scnprintf(buf, buflen, "%s", err);
1513 
1514 		return 0;
1515 	}
1516 
1517 	if (errnum <  __DSO_LOAD_ERRNO__START || errnum >= __DSO_LOAD_ERRNO__END)
1518 		return -1;
1519 
1520 	idx = errnum - __DSO_LOAD_ERRNO__START;
1521 	scnprintf(buf, buflen, "%s", dso_load__error_str[idx]);
1522 	return 0;
1523 }
1524