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