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