xref: /openbmc/linux/tools/perf/util/dso.c (revision 94cdda6b)
1 #include <asm/bug.h>
2 #include <sys/time.h>
3 #include <sys/resource.h>
4 #include "symbol.h"
5 #include "dso.h"
6 #include "machine.h"
7 #include "auxtrace.h"
8 #include "util.h"
9 #include "debug.h"
10 
11 char dso__symtab_origin(const struct dso *dso)
12 {
13 	static const char origin[] = {
14 		[DSO_BINARY_TYPE__KALLSYMS]			= 'k',
15 		[DSO_BINARY_TYPE__VMLINUX]			= 'v',
16 		[DSO_BINARY_TYPE__JAVA_JIT]			= 'j',
17 		[DSO_BINARY_TYPE__DEBUGLINK]			= 'l',
18 		[DSO_BINARY_TYPE__BUILD_ID_CACHE]		= 'B',
19 		[DSO_BINARY_TYPE__FEDORA_DEBUGINFO]		= 'f',
20 		[DSO_BINARY_TYPE__UBUNTU_DEBUGINFO]		= 'u',
21 		[DSO_BINARY_TYPE__OPENEMBEDDED_DEBUGINFO]	= 'o',
22 		[DSO_BINARY_TYPE__BUILDID_DEBUGINFO]		= 'b',
23 		[DSO_BINARY_TYPE__SYSTEM_PATH_DSO]		= 'd',
24 		[DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE]		= 'K',
25 		[DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE_COMP]	= 'm',
26 		[DSO_BINARY_TYPE__GUEST_KALLSYMS]		= 'g',
27 		[DSO_BINARY_TYPE__GUEST_KMODULE]		= 'G',
28 		[DSO_BINARY_TYPE__GUEST_KMODULE_COMP]		= 'M',
29 		[DSO_BINARY_TYPE__GUEST_VMLINUX]		= 'V',
30 	};
31 
32 	if (dso == NULL || dso->symtab_type == DSO_BINARY_TYPE__NOT_FOUND)
33 		return '!';
34 	return origin[dso->symtab_type];
35 }
36 
37 int dso__read_binary_type_filename(const struct dso *dso,
38 				   enum dso_binary_type type,
39 				   char *root_dir, char *filename, size_t size)
40 {
41 	char build_id_hex[BUILD_ID_SIZE * 2 + 1];
42 	int ret = 0;
43 	size_t len;
44 
45 	switch (type) {
46 	case DSO_BINARY_TYPE__DEBUGLINK: {
47 		char *debuglink;
48 
49 		len = __symbol__join_symfs(filename, size, dso->long_name);
50 		debuglink = filename + len;
51 		while (debuglink != filename && *debuglink != '/')
52 			debuglink--;
53 		if (*debuglink == '/')
54 			debuglink++;
55 		ret = filename__read_debuglink(filename, debuglink,
56 					       size - (debuglink - filename));
57 		}
58 		break;
59 	case DSO_BINARY_TYPE__BUILD_ID_CACHE:
60 		/* skip the locally configured cache if a symfs is given */
61 		if (symbol_conf.symfs[0] ||
62 		    (dso__build_id_filename(dso, filename, size) == NULL))
63 			ret = -1;
64 		break;
65 
66 	case DSO_BINARY_TYPE__FEDORA_DEBUGINFO:
67 		len = __symbol__join_symfs(filename, size, "/usr/lib/debug");
68 		snprintf(filename + len, size - len, "%s.debug", dso->long_name);
69 		break;
70 
71 	case DSO_BINARY_TYPE__UBUNTU_DEBUGINFO:
72 		len = __symbol__join_symfs(filename, size, "/usr/lib/debug");
73 		snprintf(filename + len, size - len, "%s", dso->long_name);
74 		break;
75 
76 	case DSO_BINARY_TYPE__OPENEMBEDDED_DEBUGINFO:
77 	{
78 		const char *last_slash;
79 		size_t dir_size;
80 
81 		last_slash = dso->long_name + dso->long_name_len;
82 		while (last_slash != dso->long_name && *last_slash != '/')
83 			last_slash--;
84 
85 		len = __symbol__join_symfs(filename, size, "");
86 		dir_size = last_slash - dso->long_name + 2;
87 		if (dir_size > (size - len)) {
88 			ret = -1;
89 			break;
90 		}
91 		len += scnprintf(filename + len, dir_size, "%s",  dso->long_name);
92 		len += scnprintf(filename + len , size - len, ".debug%s",
93 								last_slash);
94 		break;
95 	}
96 
97 	case DSO_BINARY_TYPE__BUILDID_DEBUGINFO:
98 		if (!dso->has_build_id) {
99 			ret = -1;
100 			break;
101 		}
102 
103 		build_id__sprintf(dso->build_id,
104 				  sizeof(dso->build_id),
105 				  build_id_hex);
106 		len = __symbol__join_symfs(filename, size, "/usr/lib/debug/.build-id/");
107 		snprintf(filename + len, size - len, "%.2s/%s.debug",
108 			 build_id_hex, build_id_hex + 2);
109 		break;
110 
111 	case DSO_BINARY_TYPE__VMLINUX:
112 	case DSO_BINARY_TYPE__GUEST_VMLINUX:
113 	case DSO_BINARY_TYPE__SYSTEM_PATH_DSO:
114 		__symbol__join_symfs(filename, size, dso->long_name);
115 		break;
116 
117 	case DSO_BINARY_TYPE__GUEST_KMODULE:
118 	case DSO_BINARY_TYPE__GUEST_KMODULE_COMP:
119 		path__join3(filename, size, symbol_conf.symfs,
120 			    root_dir, dso->long_name);
121 		break;
122 
123 	case DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE:
124 	case DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE_COMP:
125 		__symbol__join_symfs(filename, size, dso->long_name);
126 		break;
127 
128 	case DSO_BINARY_TYPE__KCORE:
129 	case DSO_BINARY_TYPE__GUEST_KCORE:
130 		snprintf(filename, size, "%s", dso->long_name);
131 		break;
132 
133 	default:
134 	case DSO_BINARY_TYPE__KALLSYMS:
135 	case DSO_BINARY_TYPE__GUEST_KALLSYMS:
136 	case DSO_BINARY_TYPE__JAVA_JIT:
137 	case DSO_BINARY_TYPE__NOT_FOUND:
138 		ret = -1;
139 		break;
140 	}
141 
142 	return ret;
143 }
144 
145 static const struct {
146 	const char *fmt;
147 	int (*decompress)(const char *input, int output);
148 } compressions[] = {
149 #ifdef HAVE_ZLIB_SUPPORT
150 	{ "gz", gzip_decompress_to_file },
151 #endif
152 #ifdef HAVE_LZMA_SUPPORT
153 	{ "xz", lzma_decompress_to_file },
154 #endif
155 	{ NULL, NULL },
156 };
157 
158 bool is_supported_compression(const char *ext)
159 {
160 	unsigned i;
161 
162 	for (i = 0; compressions[i].fmt; i++) {
163 		if (!strcmp(ext, compressions[i].fmt))
164 			return true;
165 	}
166 	return false;
167 }
168 
169 bool is_kernel_module(const char *pathname)
170 {
171 	struct kmod_path m;
172 
173 	if (kmod_path__parse(&m, pathname))
174 		return NULL;
175 
176 	return m.kmod;
177 }
178 
179 bool decompress_to_file(const char *ext, const char *filename, int output_fd)
180 {
181 	unsigned i;
182 
183 	for (i = 0; compressions[i].fmt; i++) {
184 		if (!strcmp(ext, compressions[i].fmt))
185 			return !compressions[i].decompress(filename,
186 							   output_fd);
187 	}
188 	return false;
189 }
190 
191 bool dso__needs_decompress(struct dso *dso)
192 {
193 	return dso->symtab_type == DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE_COMP ||
194 		dso->symtab_type == DSO_BINARY_TYPE__GUEST_KMODULE_COMP;
195 }
196 
197 /*
198  * Parses kernel module specified in @path and updates
199  * @m argument like:
200  *
201  *    @comp - true if @path contains supported compression suffix,
202  *            false otherwise
203  *    @kmod - true if @path contains '.ko' suffix in right position,
204  *            false otherwise
205  *    @name - if (@alloc_name && @kmod) is true, it contains strdup-ed base name
206  *            of the kernel module without suffixes, otherwise strudup-ed
207  *            base name of @path
208  *    @ext  - if (@alloc_ext && @comp) is true, it contains strdup-ed string
209  *            the compression suffix
210  *
211  * Returns 0 if there's no strdup error, -ENOMEM otherwise.
212  */
213 int __kmod_path__parse(struct kmod_path *m, const char *path,
214 		       bool alloc_name, bool alloc_ext)
215 {
216 	const char *name = strrchr(path, '/');
217 	const char *ext  = strrchr(path, '.');
218 
219 	memset(m, 0x0, sizeof(*m));
220 	name = name ? name + 1 : path;
221 
222 	/* No extension, just return name. */
223 	if (ext == NULL) {
224 		if (alloc_name) {
225 			m->name = strdup(name);
226 			return m->name ? 0 : -ENOMEM;
227 		}
228 		return 0;
229 	}
230 
231 	if (is_supported_compression(ext + 1)) {
232 		m->comp = true;
233 		ext -= 3;
234 	}
235 
236 	/* Check .ko extension only if there's enough name left. */
237 	if (ext > name)
238 		m->kmod = !strncmp(ext, ".ko", 3);
239 
240 	if (alloc_name) {
241 		if (m->kmod) {
242 			if (asprintf(&m->name, "[%.*s]", (int) (ext - name), name) == -1)
243 				return -ENOMEM;
244 		} else {
245 			if (asprintf(&m->name, "%s", name) == -1)
246 				return -ENOMEM;
247 		}
248 
249 		strxfrchar(m->name, '-', '_');
250 	}
251 
252 	if (alloc_ext && m->comp) {
253 		m->ext = strdup(ext + 4);
254 		if (!m->ext) {
255 			free((void *) m->name);
256 			return -ENOMEM;
257 		}
258 	}
259 
260 	return 0;
261 }
262 
263 /*
264  * Global list of open DSOs and the counter.
265  */
266 static LIST_HEAD(dso__data_open);
267 static long dso__data_open_cnt;
268 
269 static void dso__list_add(struct dso *dso)
270 {
271 	list_add_tail(&dso->data.open_entry, &dso__data_open);
272 	dso__data_open_cnt++;
273 }
274 
275 static void dso__list_del(struct dso *dso)
276 {
277 	list_del(&dso->data.open_entry);
278 	WARN_ONCE(dso__data_open_cnt <= 0,
279 		  "DSO data fd counter out of bounds.");
280 	dso__data_open_cnt--;
281 }
282 
283 static void close_first_dso(void);
284 
285 static int do_open(char *name)
286 {
287 	int fd;
288 	char sbuf[STRERR_BUFSIZE];
289 
290 	do {
291 		fd = open(name, O_RDONLY);
292 		if (fd >= 0)
293 			return fd;
294 
295 		pr_debug("dso open failed: %s\n",
296 			 strerror_r(errno, sbuf, sizeof(sbuf)));
297 		if (!dso__data_open_cnt || errno != EMFILE)
298 			break;
299 
300 		close_first_dso();
301 	} while (1);
302 
303 	return -1;
304 }
305 
306 static int __open_dso(struct dso *dso, struct machine *machine)
307 {
308 	int fd;
309 	char *root_dir = (char *)"";
310 	char *name = malloc(PATH_MAX);
311 
312 	if (!name)
313 		return -ENOMEM;
314 
315 	if (machine)
316 		root_dir = machine->root_dir;
317 
318 	if (dso__read_binary_type_filename(dso, dso->binary_type,
319 					    root_dir, name, PATH_MAX)) {
320 		free(name);
321 		return -EINVAL;
322 	}
323 
324 	fd = do_open(name);
325 	free(name);
326 	return fd;
327 }
328 
329 static void check_data_close(void);
330 
331 /**
332  * dso_close - Open DSO data file
333  * @dso: dso object
334  *
335  * Open @dso's data file descriptor and updates
336  * list/count of open DSO objects.
337  */
338 static int open_dso(struct dso *dso, struct machine *machine)
339 {
340 	int fd = __open_dso(dso, machine);
341 
342 	if (fd >= 0) {
343 		dso__list_add(dso);
344 		/*
345 		 * Check if we crossed the allowed number
346 		 * of opened DSOs and close one if needed.
347 		 */
348 		check_data_close();
349 	}
350 
351 	return fd;
352 }
353 
354 static void close_data_fd(struct dso *dso)
355 {
356 	if (dso->data.fd >= 0) {
357 		close(dso->data.fd);
358 		dso->data.fd = -1;
359 		dso->data.file_size = 0;
360 		dso__list_del(dso);
361 	}
362 }
363 
364 /**
365  * dso_close - Close DSO data file
366  * @dso: dso object
367  *
368  * Close @dso's data file descriptor and updates
369  * list/count of open DSO objects.
370  */
371 static void close_dso(struct dso *dso)
372 {
373 	close_data_fd(dso);
374 }
375 
376 static void close_first_dso(void)
377 {
378 	struct dso *dso;
379 
380 	dso = list_first_entry(&dso__data_open, struct dso, data.open_entry);
381 	close_dso(dso);
382 }
383 
384 static rlim_t get_fd_limit(void)
385 {
386 	struct rlimit l;
387 	rlim_t limit = 0;
388 
389 	/* Allow half of the current open fd limit. */
390 	if (getrlimit(RLIMIT_NOFILE, &l) == 0) {
391 		if (l.rlim_cur == RLIM_INFINITY)
392 			limit = l.rlim_cur;
393 		else
394 			limit = l.rlim_cur / 2;
395 	} else {
396 		pr_err("failed to get fd limit\n");
397 		limit = 1;
398 	}
399 
400 	return limit;
401 }
402 
403 static bool may_cache_fd(void)
404 {
405 	static rlim_t limit;
406 
407 	if (!limit)
408 		limit = get_fd_limit();
409 
410 	if (limit == RLIM_INFINITY)
411 		return true;
412 
413 	return limit > (rlim_t) dso__data_open_cnt;
414 }
415 
416 /*
417  * Check and close LRU dso if we crossed allowed limit
418  * for opened dso file descriptors. The limit is half
419  * of the RLIMIT_NOFILE files opened.
420 */
421 static void check_data_close(void)
422 {
423 	bool cache_fd = may_cache_fd();
424 
425 	if (!cache_fd)
426 		close_first_dso();
427 }
428 
429 /**
430  * dso__data_close - Close DSO data file
431  * @dso: dso object
432  *
433  * External interface to close @dso's data file descriptor.
434  */
435 void dso__data_close(struct dso *dso)
436 {
437 	close_dso(dso);
438 }
439 
440 /**
441  * dso__data_fd - Get dso's data file descriptor
442  * @dso: dso object
443  * @machine: machine object
444  *
445  * External interface to find dso's file, open it and
446  * returns file descriptor.
447  */
448 int dso__data_fd(struct dso *dso, struct machine *machine)
449 {
450 	enum dso_binary_type binary_type_data[] = {
451 		DSO_BINARY_TYPE__BUILD_ID_CACHE,
452 		DSO_BINARY_TYPE__SYSTEM_PATH_DSO,
453 		DSO_BINARY_TYPE__NOT_FOUND,
454 	};
455 	int i = 0;
456 
457 	if (dso->data.status == DSO_DATA_STATUS_ERROR)
458 		return -1;
459 
460 	if (dso->data.fd >= 0)
461 		goto out;
462 
463 	if (dso->binary_type != DSO_BINARY_TYPE__NOT_FOUND) {
464 		dso->data.fd = open_dso(dso, machine);
465 		goto out;
466 	}
467 
468 	do {
469 		dso->binary_type = binary_type_data[i++];
470 
471 		dso->data.fd = open_dso(dso, machine);
472 		if (dso->data.fd >= 0)
473 			goto out;
474 
475 	} while (dso->binary_type != DSO_BINARY_TYPE__NOT_FOUND);
476 out:
477 	if (dso->data.fd >= 0)
478 		dso->data.status = DSO_DATA_STATUS_OK;
479 	else
480 		dso->data.status = DSO_DATA_STATUS_ERROR;
481 
482 	return dso->data.fd;
483 }
484 
485 bool dso__data_status_seen(struct dso *dso, enum dso_data_status_seen by)
486 {
487 	u32 flag = 1 << by;
488 
489 	if (dso->data.status_seen & flag)
490 		return true;
491 
492 	dso->data.status_seen |= flag;
493 
494 	return false;
495 }
496 
497 static void
498 dso_cache__free(struct rb_root *root)
499 {
500 	struct rb_node *next = rb_first(root);
501 
502 	while (next) {
503 		struct dso_cache *cache;
504 
505 		cache = rb_entry(next, struct dso_cache, rb_node);
506 		next = rb_next(&cache->rb_node);
507 		rb_erase(&cache->rb_node, root);
508 		free(cache);
509 	}
510 }
511 
512 static struct dso_cache *dso_cache__find(const struct rb_root *root, u64 offset)
513 {
514 	struct rb_node * const *p = &root->rb_node;
515 	const struct rb_node *parent = NULL;
516 	struct dso_cache *cache;
517 
518 	while (*p != NULL) {
519 		u64 end;
520 
521 		parent = *p;
522 		cache = rb_entry(parent, struct dso_cache, rb_node);
523 		end = cache->offset + DSO__DATA_CACHE_SIZE;
524 
525 		if (offset < cache->offset)
526 			p = &(*p)->rb_left;
527 		else if (offset >= end)
528 			p = &(*p)->rb_right;
529 		else
530 			return cache;
531 	}
532 	return NULL;
533 }
534 
535 static void
536 dso_cache__insert(struct rb_root *root, struct dso_cache *new)
537 {
538 	struct rb_node **p = &root->rb_node;
539 	struct rb_node *parent = NULL;
540 	struct dso_cache *cache;
541 	u64 offset = new->offset;
542 
543 	while (*p != NULL) {
544 		u64 end;
545 
546 		parent = *p;
547 		cache = rb_entry(parent, struct dso_cache, rb_node);
548 		end = cache->offset + DSO__DATA_CACHE_SIZE;
549 
550 		if (offset < cache->offset)
551 			p = &(*p)->rb_left;
552 		else if (offset >= end)
553 			p = &(*p)->rb_right;
554 	}
555 
556 	rb_link_node(&new->rb_node, parent, p);
557 	rb_insert_color(&new->rb_node, root);
558 }
559 
560 static ssize_t
561 dso_cache__memcpy(struct dso_cache *cache, u64 offset,
562 		  u8 *data, u64 size)
563 {
564 	u64 cache_offset = offset - cache->offset;
565 	u64 cache_size   = min(cache->size - cache_offset, size);
566 
567 	memcpy(data, cache->data + cache_offset, cache_size);
568 	return cache_size;
569 }
570 
571 static ssize_t
572 dso_cache__read(struct dso *dso, u64 offset, u8 *data, ssize_t size)
573 {
574 	struct dso_cache *cache;
575 	ssize_t ret;
576 
577 	do {
578 		u64 cache_offset;
579 
580 		ret = -ENOMEM;
581 
582 		cache = zalloc(sizeof(*cache) + DSO__DATA_CACHE_SIZE);
583 		if (!cache)
584 			break;
585 
586 		cache_offset = offset & DSO__DATA_CACHE_MASK;
587 
588 		ret = pread(dso->data.fd, cache->data, DSO__DATA_CACHE_SIZE, cache_offset);
589 		if (ret <= 0)
590 			break;
591 
592 		cache->offset = cache_offset;
593 		cache->size   = ret;
594 		dso_cache__insert(&dso->data.cache, cache);
595 
596 		ret = dso_cache__memcpy(cache, offset, data, size);
597 
598 	} while (0);
599 
600 	if (ret <= 0)
601 		free(cache);
602 
603 	return ret;
604 }
605 
606 static ssize_t dso_cache_read(struct dso *dso, u64 offset,
607 			      u8 *data, ssize_t size)
608 {
609 	struct dso_cache *cache;
610 
611 	cache = dso_cache__find(&dso->data.cache, offset);
612 	if (cache)
613 		return dso_cache__memcpy(cache, offset, data, size);
614 	else
615 		return dso_cache__read(dso, offset, data, size);
616 }
617 
618 /*
619  * Reads and caches dso data DSO__DATA_CACHE_SIZE size chunks
620  * in the rb_tree. Any read to already cached data is served
621  * by cached data.
622  */
623 static ssize_t cached_read(struct dso *dso, u64 offset, u8 *data, ssize_t size)
624 {
625 	ssize_t r = 0;
626 	u8 *p = data;
627 
628 	do {
629 		ssize_t ret;
630 
631 		ret = dso_cache_read(dso, offset, p, size);
632 		if (ret < 0)
633 			return ret;
634 
635 		/* Reached EOF, return what we have. */
636 		if (!ret)
637 			break;
638 
639 		BUG_ON(ret > size);
640 
641 		r      += ret;
642 		p      += ret;
643 		offset += ret;
644 		size   -= ret;
645 
646 	} while (size);
647 
648 	return r;
649 }
650 
651 static int data_file_size(struct dso *dso)
652 {
653 	struct stat st;
654 	char sbuf[STRERR_BUFSIZE];
655 
656 	if (!dso->data.file_size) {
657 		if (fstat(dso->data.fd, &st)) {
658 			pr_err("dso mmap failed, fstat: %s\n",
659 				strerror_r(errno, sbuf, sizeof(sbuf)));
660 			return -1;
661 		}
662 		dso->data.file_size = st.st_size;
663 	}
664 
665 	return 0;
666 }
667 
668 /**
669  * dso__data_size - Return dso data size
670  * @dso: dso object
671  * @machine: machine object
672  *
673  * Return: dso data size
674  */
675 off_t dso__data_size(struct dso *dso, struct machine *machine)
676 {
677 	int fd;
678 
679 	fd = dso__data_fd(dso, machine);
680 	if (fd < 0)
681 		return fd;
682 
683 	if (data_file_size(dso))
684 		return -1;
685 
686 	/* For now just estimate dso data size is close to file size */
687 	return dso->data.file_size;
688 }
689 
690 static ssize_t data_read_offset(struct dso *dso, u64 offset,
691 				u8 *data, ssize_t size)
692 {
693 	if (data_file_size(dso))
694 		return -1;
695 
696 	/* Check the offset sanity. */
697 	if (offset > dso->data.file_size)
698 		return -1;
699 
700 	if (offset + size < offset)
701 		return -1;
702 
703 	return cached_read(dso, offset, data, size);
704 }
705 
706 /**
707  * dso__data_read_offset - Read data from dso file offset
708  * @dso: dso object
709  * @machine: machine object
710  * @offset: file offset
711  * @data: buffer to store data
712  * @size: size of the @data buffer
713  *
714  * External interface to read data from dso file offset. Open
715  * dso data file and use cached_read to get the data.
716  */
717 ssize_t dso__data_read_offset(struct dso *dso, struct machine *machine,
718 			      u64 offset, u8 *data, ssize_t size)
719 {
720 	if (dso__data_fd(dso, machine) < 0)
721 		return -1;
722 
723 	return data_read_offset(dso, offset, data, size);
724 }
725 
726 /**
727  * dso__data_read_addr - Read data from dso address
728  * @dso: dso object
729  * @machine: machine object
730  * @add: virtual memory address
731  * @data: buffer to store data
732  * @size: size of the @data buffer
733  *
734  * External interface to read data from dso address.
735  */
736 ssize_t dso__data_read_addr(struct dso *dso, struct map *map,
737 			    struct machine *machine, u64 addr,
738 			    u8 *data, ssize_t size)
739 {
740 	u64 offset = map->map_ip(map, addr);
741 	return dso__data_read_offset(dso, machine, offset, data, size);
742 }
743 
744 struct map *dso__new_map(const char *name)
745 {
746 	struct map *map = NULL;
747 	struct dso *dso = dso__new(name);
748 
749 	if (dso)
750 		map = map__new2(0, dso, MAP__FUNCTION);
751 
752 	return map;
753 }
754 
755 struct dso *dso__kernel_findnew(struct machine *machine, const char *name,
756 		    const char *short_name, int dso_type)
757 {
758 	/*
759 	 * The kernel dso could be created by build_id processing.
760 	 */
761 	struct dso *dso = __dsos__findnew(&machine->kernel_dsos, name);
762 
763 	/*
764 	 * We need to run this in all cases, since during the build_id
765 	 * processing we had no idea this was the kernel dso.
766 	 */
767 	if (dso != NULL) {
768 		dso__set_short_name(dso, short_name, false);
769 		dso->kernel = dso_type;
770 	}
771 
772 	return dso;
773 }
774 
775 /*
776  * Find a matching entry and/or link current entry to RB tree.
777  * Either one of the dso or name parameter must be non-NULL or the
778  * function will not work.
779  */
780 static struct dso *dso__findlink_by_longname(struct rb_root *root,
781 					     struct dso *dso, const char *name)
782 {
783 	struct rb_node **p = &root->rb_node;
784 	struct rb_node  *parent = NULL;
785 
786 	if (!name)
787 		name = dso->long_name;
788 	/*
789 	 * Find node with the matching name
790 	 */
791 	while (*p) {
792 		struct dso *this = rb_entry(*p, struct dso, rb_node);
793 		int rc = strcmp(name, this->long_name);
794 
795 		parent = *p;
796 		if (rc == 0) {
797 			/*
798 			 * In case the new DSO is a duplicate of an existing
799 			 * one, print an one-time warning & put the new entry
800 			 * at the end of the list of duplicates.
801 			 */
802 			if (!dso || (dso == this))
803 				return this;	/* Find matching dso */
804 			/*
805 			 * The core kernel DSOs may have duplicated long name.
806 			 * In this case, the short name should be different.
807 			 * Comparing the short names to differentiate the DSOs.
808 			 */
809 			rc = strcmp(dso->short_name, this->short_name);
810 			if (rc == 0) {
811 				pr_err("Duplicated dso name: %s\n", name);
812 				return NULL;
813 			}
814 		}
815 		if (rc < 0)
816 			p = &parent->rb_left;
817 		else
818 			p = &parent->rb_right;
819 	}
820 	if (dso) {
821 		/* Add new node and rebalance tree */
822 		rb_link_node(&dso->rb_node, parent, p);
823 		rb_insert_color(&dso->rb_node, root);
824 	}
825 	return NULL;
826 }
827 
828 static inline struct dso *
829 dso__find_by_longname(const struct rb_root *root, const char *name)
830 {
831 	return dso__findlink_by_longname((struct rb_root *)root, NULL, name);
832 }
833 
834 void dso__set_long_name(struct dso *dso, const char *name, bool name_allocated)
835 {
836 	if (name == NULL)
837 		return;
838 
839 	if (dso->long_name_allocated)
840 		free((char *)dso->long_name);
841 
842 	dso->long_name		 = name;
843 	dso->long_name_len	 = strlen(name);
844 	dso->long_name_allocated = name_allocated;
845 }
846 
847 void dso__set_short_name(struct dso *dso, const char *name, bool name_allocated)
848 {
849 	if (name == NULL)
850 		return;
851 
852 	if (dso->short_name_allocated)
853 		free((char *)dso->short_name);
854 
855 	dso->short_name		  = name;
856 	dso->short_name_len	  = strlen(name);
857 	dso->short_name_allocated = name_allocated;
858 }
859 
860 static void dso__set_basename(struct dso *dso)
861 {
862        /*
863         * basename() may modify path buffer, so we must pass
864         * a copy.
865         */
866        char *base, *lname = strdup(dso->long_name);
867 
868        if (!lname)
869                return;
870 
871        /*
872         * basename() may return a pointer to internal
873         * storage which is reused in subsequent calls
874         * so copy the result.
875         */
876        base = strdup(basename(lname));
877 
878        free(lname);
879 
880        if (!base)
881                return;
882 
883        dso__set_short_name(dso, base, true);
884 }
885 
886 int dso__name_len(const struct dso *dso)
887 {
888 	if (!dso)
889 		return strlen("[unknown]");
890 	if (verbose)
891 		return dso->long_name_len;
892 
893 	return dso->short_name_len;
894 }
895 
896 bool dso__loaded(const struct dso *dso, enum map_type type)
897 {
898 	return dso->loaded & (1 << type);
899 }
900 
901 bool dso__sorted_by_name(const struct dso *dso, enum map_type type)
902 {
903 	return dso->sorted_by_name & (1 << type);
904 }
905 
906 void dso__set_sorted_by_name(struct dso *dso, enum map_type type)
907 {
908 	dso->sorted_by_name |= (1 << type);
909 }
910 
911 struct dso *dso__new(const char *name)
912 {
913 	struct dso *dso = calloc(1, sizeof(*dso) + strlen(name) + 1);
914 
915 	if (dso != NULL) {
916 		int i;
917 		strcpy(dso->name, name);
918 		dso__set_long_name(dso, dso->name, false);
919 		dso__set_short_name(dso, dso->name, false);
920 		for (i = 0; i < MAP__NR_TYPES; ++i)
921 			dso->symbols[i] = dso->symbol_names[i] = RB_ROOT;
922 		dso->data.cache = RB_ROOT;
923 		dso->data.fd = -1;
924 		dso->data.status = DSO_DATA_STATUS_UNKNOWN;
925 		dso->symtab_type = DSO_BINARY_TYPE__NOT_FOUND;
926 		dso->binary_type = DSO_BINARY_TYPE__NOT_FOUND;
927 		dso->is_64_bit = (sizeof(void *) == 8);
928 		dso->loaded = 0;
929 		dso->rel = 0;
930 		dso->sorted_by_name = 0;
931 		dso->has_build_id = 0;
932 		dso->has_srcline = 1;
933 		dso->a2l_fails = 1;
934 		dso->kernel = DSO_TYPE_USER;
935 		dso->needs_swap = DSO_SWAP__UNSET;
936 		RB_CLEAR_NODE(&dso->rb_node);
937 		INIT_LIST_HEAD(&dso->node);
938 		INIT_LIST_HEAD(&dso->data.open_entry);
939 	}
940 
941 	return dso;
942 }
943 
944 void dso__delete(struct dso *dso)
945 {
946 	int i;
947 
948 	if (!RB_EMPTY_NODE(&dso->rb_node))
949 		pr_err("DSO %s is still in rbtree when being deleted!\n",
950 		       dso->long_name);
951 	for (i = 0; i < MAP__NR_TYPES; ++i)
952 		symbols__delete(&dso->symbols[i]);
953 
954 	if (dso->short_name_allocated) {
955 		zfree((char **)&dso->short_name);
956 		dso->short_name_allocated = false;
957 	}
958 
959 	if (dso->long_name_allocated) {
960 		zfree((char **)&dso->long_name);
961 		dso->long_name_allocated = false;
962 	}
963 
964 	dso__data_close(dso);
965 	auxtrace_cache__free(dso->auxtrace_cache);
966 	dso_cache__free(&dso->data.cache);
967 	dso__free_a2l(dso);
968 	zfree(&dso->symsrc_filename);
969 	free(dso);
970 }
971 
972 void dso__set_build_id(struct dso *dso, void *build_id)
973 {
974 	memcpy(dso->build_id, build_id, sizeof(dso->build_id));
975 	dso->has_build_id = 1;
976 }
977 
978 bool dso__build_id_equal(const struct dso *dso, u8 *build_id)
979 {
980 	return memcmp(dso->build_id, build_id, sizeof(dso->build_id)) == 0;
981 }
982 
983 void dso__read_running_kernel_build_id(struct dso *dso, struct machine *machine)
984 {
985 	char path[PATH_MAX];
986 
987 	if (machine__is_default_guest(machine))
988 		return;
989 	sprintf(path, "%s/sys/kernel/notes", machine->root_dir);
990 	if (sysfs__read_build_id(path, dso->build_id,
991 				 sizeof(dso->build_id)) == 0)
992 		dso->has_build_id = true;
993 }
994 
995 int dso__kernel_module_get_build_id(struct dso *dso,
996 				    const char *root_dir)
997 {
998 	char filename[PATH_MAX];
999 	/*
1000 	 * kernel module short names are of the form "[module]" and
1001 	 * we need just "module" here.
1002 	 */
1003 	const char *name = dso->short_name + 1;
1004 
1005 	snprintf(filename, sizeof(filename),
1006 		 "%s/sys/module/%.*s/notes/.note.gnu.build-id",
1007 		 root_dir, (int)strlen(name) - 1, name);
1008 
1009 	if (sysfs__read_build_id(filename, dso->build_id,
1010 				 sizeof(dso->build_id)) == 0)
1011 		dso->has_build_id = true;
1012 
1013 	return 0;
1014 }
1015 
1016 bool __dsos__read_build_ids(struct list_head *head, bool with_hits)
1017 {
1018 	bool have_build_id = false;
1019 	struct dso *pos;
1020 
1021 	list_for_each_entry(pos, head, node) {
1022 		if (with_hits && !pos->hit)
1023 			continue;
1024 		if (pos->has_build_id) {
1025 			have_build_id = true;
1026 			continue;
1027 		}
1028 		if (filename__read_build_id(pos->long_name, pos->build_id,
1029 					    sizeof(pos->build_id)) > 0) {
1030 			have_build_id	  = true;
1031 			pos->has_build_id = true;
1032 		}
1033 	}
1034 
1035 	return have_build_id;
1036 }
1037 
1038 void dsos__add(struct dsos *dsos, struct dso *dso)
1039 {
1040 	list_add_tail(&dso->node, &dsos->head);
1041 	dso__findlink_by_longname(&dsos->root, dso, NULL);
1042 }
1043 
1044 struct dso *dsos__find(const struct dsos *dsos, const char *name,
1045 		       bool cmp_short)
1046 {
1047 	struct dso *pos;
1048 
1049 	if (cmp_short) {
1050 		list_for_each_entry(pos, &dsos->head, node)
1051 			if (strcmp(pos->short_name, name) == 0)
1052 				return pos;
1053 		return NULL;
1054 	}
1055 	return dso__find_by_longname(&dsos->root, name);
1056 }
1057 
1058 struct dso *dsos__addnew(struct dsos *dsos, const char *name)
1059 {
1060 	struct dso *dso = dso__new(name);
1061 
1062 	if (dso != NULL) {
1063 		dsos__add(dsos, dso);
1064 		dso__set_basename(dso);
1065 	}
1066 	return dso;
1067 }
1068 
1069 struct dso *__dsos__findnew(struct dsos *dsos, const char *name)
1070 {
1071 	struct dso *dso = dsos__find(dsos, name, false);
1072 
1073 	return dso ? dso : dsos__addnew(dsos, name);
1074 }
1075 
1076 size_t __dsos__fprintf_buildid(struct list_head *head, FILE *fp,
1077 			       bool (skip)(struct dso *dso, int parm), int parm)
1078 {
1079 	struct dso *pos;
1080 	size_t ret = 0;
1081 
1082 	list_for_each_entry(pos, head, node) {
1083 		if (skip && skip(pos, parm))
1084 			continue;
1085 		ret += dso__fprintf_buildid(pos, fp);
1086 		ret += fprintf(fp, " %s\n", pos->long_name);
1087 	}
1088 	return ret;
1089 }
1090 
1091 size_t __dsos__fprintf(struct list_head *head, FILE *fp)
1092 {
1093 	struct dso *pos;
1094 	size_t ret = 0;
1095 
1096 	list_for_each_entry(pos, head, node) {
1097 		int i;
1098 		for (i = 0; i < MAP__NR_TYPES; ++i)
1099 			ret += dso__fprintf(pos, i, fp);
1100 	}
1101 
1102 	return ret;
1103 }
1104 
1105 size_t dso__fprintf_buildid(struct dso *dso, FILE *fp)
1106 {
1107 	char sbuild_id[BUILD_ID_SIZE * 2 + 1];
1108 
1109 	build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
1110 	return fprintf(fp, "%s", sbuild_id);
1111 }
1112 
1113 size_t dso__fprintf(struct dso *dso, enum map_type type, FILE *fp)
1114 {
1115 	struct rb_node *nd;
1116 	size_t ret = fprintf(fp, "dso: %s (", dso->short_name);
1117 
1118 	if (dso->short_name != dso->long_name)
1119 		ret += fprintf(fp, "%s, ", dso->long_name);
1120 	ret += fprintf(fp, "%s, %sloaded, ", map_type__name[type],
1121 		       dso__loaded(dso, type) ? "" : "NOT ");
1122 	ret += dso__fprintf_buildid(dso, fp);
1123 	ret += fprintf(fp, ")\n");
1124 	for (nd = rb_first(&dso->symbols[type]); nd; nd = rb_next(nd)) {
1125 		struct symbol *pos = rb_entry(nd, struct symbol, rb_node);
1126 		ret += symbol__fprintf(pos, fp);
1127 	}
1128 
1129 	return ret;
1130 }
1131 
1132 enum dso_type dso__type(struct dso *dso, struct machine *machine)
1133 {
1134 	int fd;
1135 
1136 	fd = dso__data_fd(dso, machine);
1137 	if (fd < 0)
1138 		return DSO__TYPE_UNKNOWN;
1139 
1140 	return dso__type_fd(fd);
1141 }
1142 
1143 int dso__strerror_load(struct dso *dso, char *buf, size_t buflen)
1144 {
1145 	int idx, errnum = dso->load_errno;
1146 	/*
1147 	 * This must have a same ordering as the enum dso_load_errno.
1148 	 */
1149 	static const char *dso_load__error_str[] = {
1150 	"Internal tools/perf/ library error",
1151 	"Invalid ELF file",
1152 	"Can not read build id",
1153 	"Mismatching build id",
1154 	"Decompression failure",
1155 	};
1156 
1157 	BUG_ON(buflen == 0);
1158 
1159 	if (errnum >= 0) {
1160 		const char *err = strerror_r(errnum, buf, buflen);
1161 
1162 		if (err != buf)
1163 			scnprintf(buf, buflen, "%s", err);
1164 
1165 		return 0;
1166 	}
1167 
1168 	if (errnum <  __DSO_LOAD_ERRNO__START || errnum >= __DSO_LOAD_ERRNO__END)
1169 		return -1;
1170 
1171 	idx = errnum - __DSO_LOAD_ERRNO__START;
1172 	scnprintf(buf, buflen, "%s", dso_load__error_str[idx]);
1173 	return 0;
1174 }
1175