OSDN Git Service

perf tools: Fix a memory leak in __open_dso()
[uclinux-h8/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                 free(name);
417                 return -EINVAL;
418         }
419
420         fd = do_open(name);
421         free(name);
422         return fd;
423 }
424
425 static void check_data_close(void);
426
427 /**
428  * dso_close - Open DSO data file
429  * @dso: dso object
430  *
431  * Open @dso's data file descriptor and updates
432  * list/count of open DSO objects.
433  */
434 static int open_dso(struct dso *dso, struct machine *machine)
435 {
436         int fd = __open_dso(dso, machine);
437
438         if (fd >= 0) {
439                 dso__list_add(dso);
440                 /*
441                  * Check if we crossed the allowed number
442                  * of opened DSOs and close one if needed.
443                  */
444                 check_data_close();
445         }
446
447         return fd;
448 }
449
450 static void close_data_fd(struct dso *dso)
451 {
452         if (dso->data.fd >= 0) {
453                 close(dso->data.fd);
454                 dso->data.fd = -1;
455                 dso->data.file_size = 0;
456                 dso__list_del(dso);
457         }
458 }
459
460 /**
461  * dso_close - Close DSO data file
462  * @dso: dso object
463  *
464  * Close @dso's data file descriptor and updates
465  * list/count of open DSO objects.
466  */
467 static void close_dso(struct dso *dso)
468 {
469         close_data_fd(dso);
470 }
471
472 static void close_first_dso(void)
473 {
474         struct dso *dso;
475
476         dso = list_first_entry(&dso__data_open, struct dso, data.open_entry);
477         close_dso(dso);
478 }
479
480 static rlim_t get_fd_limit(void)
481 {
482         struct rlimit l;
483         rlim_t limit = 0;
484
485         /* Allow half of the current open fd limit. */
486         if (getrlimit(RLIMIT_NOFILE, &l) == 0) {
487                 if (l.rlim_cur == RLIM_INFINITY)
488                         limit = l.rlim_cur;
489                 else
490                         limit = l.rlim_cur / 2;
491         } else {
492                 pr_err("failed to get fd limit\n");
493                 limit = 1;
494         }
495
496         return limit;
497 }
498
499 static rlim_t fd_limit;
500
501 /*
502  * Used only by tests/dso-data.c to reset the environment
503  * for tests. I dont expect we should change this during
504  * standard runtime.
505  */
506 void reset_fd_limit(void)
507 {
508         fd_limit = 0;
509 }
510
511 static bool may_cache_fd(void)
512 {
513         if (!fd_limit)
514                 fd_limit = get_fd_limit();
515
516         if (fd_limit == RLIM_INFINITY)
517                 return true;
518
519         return fd_limit > (rlim_t) dso__data_open_cnt;
520 }
521
522 /*
523  * Check and close LRU dso if we crossed allowed limit
524  * for opened dso file descriptors. The limit is half
525  * of the RLIMIT_NOFILE files opened.
526 */
527 static void check_data_close(void)
528 {
529         bool cache_fd = may_cache_fd();
530
531         if (!cache_fd)
532                 close_first_dso();
533 }
534
535 /**
536  * dso__data_close - Close DSO data file
537  * @dso: dso object
538  *
539  * External interface to close @dso's data file descriptor.
540  */
541 void dso__data_close(struct dso *dso)
542 {
543         pthread_mutex_lock(&dso__data_open_lock);
544         close_dso(dso);
545         pthread_mutex_unlock(&dso__data_open_lock);
546 }
547
548 static void try_to_open_dso(struct dso *dso, struct machine *machine)
549 {
550         enum dso_binary_type binary_type_data[] = {
551                 DSO_BINARY_TYPE__BUILD_ID_CACHE,
552                 DSO_BINARY_TYPE__SYSTEM_PATH_DSO,
553                 DSO_BINARY_TYPE__NOT_FOUND,
554         };
555         int i = 0;
556
557         if (dso->data.fd >= 0)
558                 return;
559
560         if (dso->binary_type != DSO_BINARY_TYPE__NOT_FOUND) {
561                 dso->data.fd = open_dso(dso, machine);
562                 goto out;
563         }
564
565         do {
566                 dso->binary_type = binary_type_data[i++];
567
568                 dso->data.fd = open_dso(dso, machine);
569                 if (dso->data.fd >= 0)
570                         goto out;
571
572         } while (dso->binary_type != DSO_BINARY_TYPE__NOT_FOUND);
573 out:
574         if (dso->data.fd >= 0)
575                 dso->data.status = DSO_DATA_STATUS_OK;
576         else
577                 dso->data.status = DSO_DATA_STATUS_ERROR;
578 }
579
580 /**
581  * dso__data_get_fd - Get dso's data file descriptor
582  * @dso: dso object
583  * @machine: machine object
584  *
585  * External interface to find dso's file, open it and
586  * returns file descriptor.  It should be paired with
587  * dso__data_put_fd() if it returns non-negative value.
588  */
589 int dso__data_get_fd(struct dso *dso, struct machine *machine)
590 {
591         if (dso->data.status == DSO_DATA_STATUS_ERROR)
592                 return -1;
593
594         if (pthread_mutex_lock(&dso__data_open_lock) < 0)
595                 return -1;
596
597         try_to_open_dso(dso, machine);
598
599         if (dso->data.fd < 0)
600                 pthread_mutex_unlock(&dso__data_open_lock);
601
602         return dso->data.fd;
603 }
604
605 void dso__data_put_fd(struct dso *dso __maybe_unused)
606 {
607         pthread_mutex_unlock(&dso__data_open_lock);
608 }
609
610 bool dso__data_status_seen(struct dso *dso, enum dso_data_status_seen by)
611 {
612         u32 flag = 1 << by;
613
614         if (dso->data.status_seen & flag)
615                 return true;
616
617         dso->data.status_seen |= flag;
618
619         return false;
620 }
621
622 static void
623 dso_cache__free(struct dso *dso)
624 {
625         struct rb_root *root = &dso->data.cache;
626         struct rb_node *next = rb_first(root);
627
628         pthread_mutex_lock(&dso->lock);
629         while (next) {
630                 struct dso_cache *cache;
631
632                 cache = rb_entry(next, struct dso_cache, rb_node);
633                 next = rb_next(&cache->rb_node);
634                 rb_erase(&cache->rb_node, root);
635                 free(cache);
636         }
637         pthread_mutex_unlock(&dso->lock);
638 }
639
640 static struct dso_cache *dso_cache__find(struct dso *dso, u64 offset)
641 {
642         const struct rb_root *root = &dso->data.cache;
643         struct rb_node * const *p = &root->rb_node;
644         const struct rb_node *parent = NULL;
645         struct dso_cache *cache;
646
647         while (*p != NULL) {
648                 u64 end;
649
650                 parent = *p;
651                 cache = rb_entry(parent, struct dso_cache, rb_node);
652                 end = cache->offset + DSO__DATA_CACHE_SIZE;
653
654                 if (offset < cache->offset)
655                         p = &(*p)->rb_left;
656                 else if (offset >= end)
657                         p = &(*p)->rb_right;
658                 else
659                         return cache;
660         }
661
662         return NULL;
663 }
664
665 static struct dso_cache *
666 dso_cache__insert(struct dso *dso, struct dso_cache *new)
667 {
668         struct rb_root *root = &dso->data.cache;
669         struct rb_node **p = &root->rb_node;
670         struct rb_node *parent = NULL;
671         struct dso_cache *cache;
672         u64 offset = new->offset;
673
674         pthread_mutex_lock(&dso->lock);
675         while (*p != NULL) {
676                 u64 end;
677
678                 parent = *p;
679                 cache = rb_entry(parent, struct dso_cache, rb_node);
680                 end = cache->offset + DSO__DATA_CACHE_SIZE;
681
682                 if (offset < cache->offset)
683                         p = &(*p)->rb_left;
684                 else if (offset >= end)
685                         p = &(*p)->rb_right;
686                 else
687                         goto out;
688         }
689
690         rb_link_node(&new->rb_node, parent, p);
691         rb_insert_color(&new->rb_node, root);
692
693         cache = NULL;
694 out:
695         pthread_mutex_unlock(&dso->lock);
696         return cache;
697 }
698
699 static ssize_t
700 dso_cache__memcpy(struct dso_cache *cache, u64 offset,
701                   u8 *data, u64 size)
702 {
703         u64 cache_offset = offset - cache->offset;
704         u64 cache_size   = min(cache->size - cache_offset, size);
705
706         memcpy(data, cache->data + cache_offset, cache_size);
707         return cache_size;
708 }
709
710 static ssize_t
711 dso_cache__read(struct dso *dso, struct machine *machine,
712                 u64 offset, u8 *data, ssize_t size)
713 {
714         struct dso_cache *cache;
715         struct dso_cache *old;
716         ssize_t ret;
717
718         do {
719                 u64 cache_offset;
720
721                 cache = zalloc(sizeof(*cache) + DSO__DATA_CACHE_SIZE);
722                 if (!cache)
723                         return -ENOMEM;
724
725                 pthread_mutex_lock(&dso__data_open_lock);
726
727                 /*
728                  * dso->data.fd might be closed if other thread opened another
729                  * file (dso) due to open file limit (RLIMIT_NOFILE).
730                  */
731                 try_to_open_dso(dso, machine);
732
733                 if (dso->data.fd < 0) {
734                         ret = -errno;
735                         dso->data.status = DSO_DATA_STATUS_ERROR;
736                         break;
737                 }
738
739                 cache_offset = offset & DSO__DATA_CACHE_MASK;
740
741                 ret = pread(dso->data.fd, cache->data, DSO__DATA_CACHE_SIZE, cache_offset);
742                 if (ret <= 0)
743                         break;
744
745                 cache->offset = cache_offset;
746                 cache->size   = ret;
747         } while (0);
748
749         pthread_mutex_unlock(&dso__data_open_lock);
750
751         if (ret > 0) {
752                 old = dso_cache__insert(dso, cache);
753                 if (old) {
754                         /* we lose the race */
755                         free(cache);
756                         cache = old;
757                 }
758
759                 ret = dso_cache__memcpy(cache, offset, data, size);
760         }
761
762         if (ret <= 0)
763                 free(cache);
764
765         return ret;
766 }
767
768 static ssize_t dso_cache_read(struct dso *dso, struct machine *machine,
769                               u64 offset, u8 *data, ssize_t size)
770 {
771         struct dso_cache *cache;
772
773         cache = dso_cache__find(dso, offset);
774         if (cache)
775                 return dso_cache__memcpy(cache, offset, data, size);
776         else
777                 return dso_cache__read(dso, machine, offset, data, size);
778 }
779
780 /*
781  * Reads and caches dso data DSO__DATA_CACHE_SIZE size chunks
782  * in the rb_tree. Any read to already cached data is served
783  * by cached data.
784  */
785 static ssize_t cached_read(struct dso *dso, struct machine *machine,
786                            u64 offset, u8 *data, ssize_t size)
787 {
788         ssize_t r = 0;
789         u8 *p = data;
790
791         do {
792                 ssize_t ret;
793
794                 ret = dso_cache_read(dso, machine, offset, p, size);
795                 if (ret < 0)
796                         return ret;
797
798                 /* Reached EOF, return what we have. */
799                 if (!ret)
800                         break;
801
802                 BUG_ON(ret > size);
803
804                 r      += ret;
805                 p      += ret;
806                 offset += ret;
807                 size   -= ret;
808
809         } while (size);
810
811         return r;
812 }
813
814 static int data_file_size(struct dso *dso, struct machine *machine)
815 {
816         int ret = 0;
817         struct stat st;
818         char sbuf[STRERR_BUFSIZE];
819
820         if (dso->data.file_size)
821                 return 0;
822
823         if (dso->data.status == DSO_DATA_STATUS_ERROR)
824                 return -1;
825
826         pthread_mutex_lock(&dso__data_open_lock);
827
828         /*
829          * dso->data.fd might be closed if other thread opened another
830          * file (dso) due to open file limit (RLIMIT_NOFILE).
831          */
832         try_to_open_dso(dso, machine);
833
834         if (dso->data.fd < 0) {
835                 ret = -errno;
836                 dso->data.status = DSO_DATA_STATUS_ERROR;
837                 goto out;
838         }
839
840         if (fstat(dso->data.fd, &st) < 0) {
841                 ret = -errno;
842                 pr_err("dso cache fstat failed: %s\n",
843                        str_error_r(errno, sbuf, sizeof(sbuf)));
844                 dso->data.status = DSO_DATA_STATUS_ERROR;
845                 goto out;
846         }
847         dso->data.file_size = st.st_size;
848
849 out:
850         pthread_mutex_unlock(&dso__data_open_lock);
851         return ret;
852 }
853
854 /**
855  * dso__data_size - Return dso data size
856  * @dso: dso object
857  * @machine: machine object
858  *
859  * Return: dso data size
860  */
861 off_t dso__data_size(struct dso *dso, struct machine *machine)
862 {
863         if (data_file_size(dso, machine))
864                 return -1;
865
866         /* For now just estimate dso data size is close to file size */
867         return dso->data.file_size;
868 }
869
870 static ssize_t data_read_offset(struct dso *dso, struct machine *machine,
871                                 u64 offset, u8 *data, ssize_t size)
872 {
873         if (data_file_size(dso, machine))
874                 return -1;
875
876         /* Check the offset sanity. */
877         if (offset > dso->data.file_size)
878                 return -1;
879
880         if (offset + size < offset)
881                 return -1;
882
883         return cached_read(dso, machine, offset, data, size);
884 }
885
886 /**
887  * dso__data_read_offset - Read data from dso file offset
888  * @dso: dso object
889  * @machine: machine object
890  * @offset: file offset
891  * @data: buffer to store data
892  * @size: size of the @data buffer
893  *
894  * External interface to read data from dso file offset. Open
895  * dso data file and use cached_read to get the data.
896  */
897 ssize_t dso__data_read_offset(struct dso *dso, struct machine *machine,
898                               u64 offset, u8 *data, ssize_t size)
899 {
900         if (dso->data.status == DSO_DATA_STATUS_ERROR)
901                 return -1;
902
903         return data_read_offset(dso, machine, offset, data, size);
904 }
905
906 /**
907  * dso__data_read_addr - Read data from dso address
908  * @dso: dso object
909  * @machine: machine object
910  * @add: virtual memory address
911  * @data: buffer to store data
912  * @size: size of the @data buffer
913  *
914  * External interface to read data from dso address.
915  */
916 ssize_t dso__data_read_addr(struct dso *dso, struct map *map,
917                             struct machine *machine, u64 addr,
918                             u8 *data, ssize_t size)
919 {
920         u64 offset = map->map_ip(map, addr);
921         return dso__data_read_offset(dso, machine, offset, data, size);
922 }
923
924 struct map *dso__new_map(const char *name)
925 {
926         struct map *map = NULL;
927         struct dso *dso = dso__new(name);
928
929         if (dso)
930                 map = map__new2(0, dso, MAP__FUNCTION);
931
932         return map;
933 }
934
935 struct dso *machine__findnew_kernel(struct machine *machine, const char *name,
936                                     const char *short_name, int dso_type)
937 {
938         /*
939          * The kernel dso could be created by build_id processing.
940          */
941         struct dso *dso = machine__findnew_dso(machine, name);
942
943         /*
944          * We need to run this in all cases, since during the build_id
945          * processing we had no idea this was the kernel dso.
946          */
947         if (dso != NULL) {
948                 dso__set_short_name(dso, short_name, false);
949                 dso->kernel = dso_type;
950         }
951
952         return dso;
953 }
954
955 /*
956  * Find a matching entry and/or link current entry to RB tree.
957  * Either one of the dso or name parameter must be non-NULL or the
958  * function will not work.
959  */
960 static struct dso *__dso__findlink_by_longname(struct rb_root *root,
961                                                struct dso *dso, const char *name)
962 {
963         struct rb_node **p = &root->rb_node;
964         struct rb_node  *parent = NULL;
965
966         if (!name)
967                 name = dso->long_name;
968         /*
969          * Find node with the matching name
970          */
971         while (*p) {
972                 struct dso *this = rb_entry(*p, struct dso, rb_node);
973                 int rc = strcmp(name, this->long_name);
974
975                 parent = *p;
976                 if (rc == 0) {
977                         /*
978                          * In case the new DSO is a duplicate of an existing
979                          * one, print a one-time warning & put the new entry
980                          * at the end of the list of duplicates.
981                          */
982                         if (!dso || (dso == this))
983                                 return this;    /* Find matching dso */
984                         /*
985                          * The core kernel DSOs may have duplicated long name.
986                          * In this case, the short name should be different.
987                          * Comparing the short names to differentiate the DSOs.
988                          */
989                         rc = strcmp(dso->short_name, this->short_name);
990                         if (rc == 0) {
991                                 pr_err("Duplicated dso name: %s\n", name);
992                                 return NULL;
993                         }
994                 }
995                 if (rc < 0)
996                         p = &parent->rb_left;
997                 else
998                         p = &parent->rb_right;
999         }
1000         if (dso) {
1001                 /* Add new node and rebalance tree */
1002                 rb_link_node(&dso->rb_node, parent, p);
1003                 rb_insert_color(&dso->rb_node, root);
1004                 dso->root = root;
1005         }
1006         return NULL;
1007 }
1008
1009 static inline struct dso *__dso__find_by_longname(struct rb_root *root,
1010                                                   const char *name)
1011 {
1012         return __dso__findlink_by_longname(root, NULL, name);
1013 }
1014
1015 void dso__set_long_name(struct dso *dso, const char *name, bool name_allocated)
1016 {
1017         struct rb_root *root = dso->root;
1018
1019         if (name == NULL)
1020                 return;
1021
1022         if (dso->long_name_allocated)
1023                 free((char *)dso->long_name);
1024
1025         if (root) {
1026                 rb_erase(&dso->rb_node, root);
1027                 /*
1028                  * __dso__findlink_by_longname() isn't guaranteed to add it
1029                  * back, so a clean removal is required here.
1030                  */
1031                 RB_CLEAR_NODE(&dso->rb_node);
1032                 dso->root = NULL;
1033         }
1034
1035         dso->long_name           = name;
1036         dso->long_name_len       = strlen(name);
1037         dso->long_name_allocated = name_allocated;
1038
1039         if (root)
1040                 __dso__findlink_by_longname(root, dso, NULL);
1041 }
1042
1043 void dso__set_short_name(struct dso *dso, const char *name, bool name_allocated)
1044 {
1045         if (name == NULL)
1046                 return;
1047
1048         if (dso->short_name_allocated)
1049                 free((char *)dso->short_name);
1050
1051         dso->short_name           = name;
1052         dso->short_name_len       = strlen(name);
1053         dso->short_name_allocated = name_allocated;
1054 }
1055
1056 static void dso__set_basename(struct dso *dso)
1057 {
1058        /*
1059         * basename() may modify path buffer, so we must pass
1060         * a copy.
1061         */
1062        char *base, *lname = strdup(dso->long_name);
1063
1064        if (!lname)
1065                return;
1066
1067        /*
1068         * basename() may return a pointer to internal
1069         * storage which is reused in subsequent calls
1070         * so copy the result.
1071         */
1072        base = strdup(basename(lname));
1073
1074        free(lname);
1075
1076        if (!base)
1077                return;
1078
1079        dso__set_short_name(dso, base, true);
1080 }
1081
1082 int dso__name_len(const struct dso *dso)
1083 {
1084         if (!dso)
1085                 return strlen("[unknown]");
1086         if (verbose > 0)
1087                 return dso->long_name_len;
1088
1089         return dso->short_name_len;
1090 }
1091
1092 bool dso__loaded(const struct dso *dso, enum map_type type)
1093 {
1094         return dso->loaded & (1 << type);
1095 }
1096
1097 bool dso__sorted_by_name(const struct dso *dso, enum map_type type)
1098 {
1099         return dso->sorted_by_name & (1 << type);
1100 }
1101
1102 void dso__set_sorted_by_name(struct dso *dso, enum map_type type)
1103 {
1104         dso->sorted_by_name |= (1 << type);
1105 }
1106
1107 struct dso *dso__new(const char *name)
1108 {
1109         struct dso *dso = calloc(1, sizeof(*dso) + strlen(name) + 1);
1110
1111         if (dso != NULL) {
1112                 int i;
1113                 strcpy(dso->name, name);
1114                 dso__set_long_name(dso, dso->name, false);
1115                 dso__set_short_name(dso, dso->name, false);
1116                 for (i = 0; i < MAP__NR_TYPES; ++i)
1117                         dso->symbols[i] = dso->symbol_names[i] = RB_ROOT;
1118                 dso->data.cache = RB_ROOT;
1119                 dso->data.fd = -1;
1120                 dso->data.status = DSO_DATA_STATUS_UNKNOWN;
1121                 dso->symtab_type = DSO_BINARY_TYPE__NOT_FOUND;
1122                 dso->binary_type = DSO_BINARY_TYPE__NOT_FOUND;
1123                 dso->is_64_bit = (sizeof(void *) == 8);
1124                 dso->loaded = 0;
1125                 dso->rel = 0;
1126                 dso->sorted_by_name = 0;
1127                 dso->has_build_id = 0;
1128                 dso->has_srcline = 1;
1129                 dso->a2l_fails = 1;
1130                 dso->kernel = DSO_TYPE_USER;
1131                 dso->needs_swap = DSO_SWAP__UNSET;
1132                 RB_CLEAR_NODE(&dso->rb_node);
1133                 dso->root = NULL;
1134                 INIT_LIST_HEAD(&dso->node);
1135                 INIT_LIST_HEAD(&dso->data.open_entry);
1136                 pthread_mutex_init(&dso->lock, NULL);
1137                 refcount_set(&dso->refcnt, 1);
1138         }
1139
1140         return dso;
1141 }
1142
1143 void dso__delete(struct dso *dso)
1144 {
1145         int i;
1146
1147         if (!RB_EMPTY_NODE(&dso->rb_node))
1148                 pr_err("DSO %s is still in rbtree when being deleted!\n",
1149                        dso->long_name);
1150         for (i = 0; i < MAP__NR_TYPES; ++i)
1151                 symbols__delete(&dso->symbols[i]);
1152
1153         if (dso->short_name_allocated) {
1154                 zfree((char **)&dso->short_name);
1155                 dso->short_name_allocated = false;
1156         }
1157
1158         if (dso->long_name_allocated) {
1159                 zfree((char **)&dso->long_name);
1160                 dso->long_name_allocated = false;
1161         }
1162
1163         dso__data_close(dso);
1164         auxtrace_cache__free(dso->auxtrace_cache);
1165         dso_cache__free(dso);
1166         dso__free_a2l(dso);
1167         zfree(&dso->symsrc_filename);
1168         pthread_mutex_destroy(&dso->lock);
1169         free(dso);
1170 }
1171
1172 struct dso *dso__get(struct dso *dso)
1173 {
1174         if (dso)
1175                 refcount_inc(&dso->refcnt);
1176         return dso;
1177 }
1178
1179 void dso__put(struct dso *dso)
1180 {
1181         if (dso && refcount_dec_and_test(&dso->refcnt))
1182                 dso__delete(dso);
1183 }
1184
1185 void dso__set_build_id(struct dso *dso, void *build_id)
1186 {
1187         memcpy(dso->build_id, build_id, sizeof(dso->build_id));
1188         dso->has_build_id = 1;
1189 }
1190
1191 bool dso__build_id_equal(const struct dso *dso, u8 *build_id)
1192 {
1193         return memcmp(dso->build_id, build_id, sizeof(dso->build_id)) == 0;
1194 }
1195
1196 void dso__read_running_kernel_build_id(struct dso *dso, struct machine *machine)
1197 {
1198         char path[PATH_MAX];
1199
1200         if (machine__is_default_guest(machine))
1201                 return;
1202         sprintf(path, "%s/sys/kernel/notes", machine->root_dir);
1203         if (sysfs__read_build_id(path, dso->build_id,
1204                                  sizeof(dso->build_id)) == 0)
1205                 dso->has_build_id = true;
1206 }
1207
1208 int dso__kernel_module_get_build_id(struct dso *dso,
1209                                     const char *root_dir)
1210 {
1211         char filename[PATH_MAX];
1212         /*
1213          * kernel module short names are of the form "[module]" and
1214          * we need just "module" here.
1215          */
1216         const char *name = dso->short_name + 1;
1217
1218         snprintf(filename, sizeof(filename),
1219                  "%s/sys/module/%.*s/notes/.note.gnu.build-id",
1220                  root_dir, (int)strlen(name) - 1, name);
1221
1222         if (sysfs__read_build_id(filename, dso->build_id,
1223                                  sizeof(dso->build_id)) == 0)
1224                 dso->has_build_id = true;
1225
1226         return 0;
1227 }
1228
1229 bool __dsos__read_build_ids(struct list_head *head, bool with_hits)
1230 {
1231         bool have_build_id = false;
1232         struct dso *pos;
1233
1234         list_for_each_entry(pos, head, node) {
1235                 if (with_hits && !pos->hit && !dso__is_vdso(pos))
1236                         continue;
1237                 if (pos->has_build_id) {
1238                         have_build_id = true;
1239                         continue;
1240                 }
1241                 if (filename__read_build_id(pos->long_name, pos->build_id,
1242                                             sizeof(pos->build_id)) > 0) {
1243                         have_build_id     = true;
1244                         pos->has_build_id = true;
1245                 }
1246         }
1247
1248         return have_build_id;
1249 }
1250
1251 void __dsos__add(struct dsos *dsos, struct dso *dso)
1252 {
1253         list_add_tail(&dso->node, &dsos->head);
1254         __dso__findlink_by_longname(&dsos->root, dso, NULL);
1255         /*
1256          * It is now in the linked list, grab a reference, then garbage collect
1257          * this when needing memory, by looking at LRU dso instances in the
1258          * list with atomic_read(&dso->refcnt) == 1, i.e. no references
1259          * anywhere besides the one for the list, do, under a lock for the
1260          * list: remove it from the list, then a dso__put(), that probably will
1261          * be the last and will then call dso__delete(), end of life.
1262          *
1263          * That, or at the end of the 'struct machine' lifetime, when all
1264          * 'struct dso' instances will be removed from the list, in
1265          * dsos__exit(), if they have no other reference from some other data
1266          * structure.
1267          *
1268          * E.g.: after processing a 'perf.data' file and storing references
1269          * to objects instantiated while processing events, we will have
1270          * references to the 'thread', 'map', 'dso' structs all from 'struct
1271          * hist_entry' instances, but we may not need anything not referenced,
1272          * so we might as well call machines__exit()/machines__delete() and
1273          * garbage collect it.
1274          */
1275         dso__get(dso);
1276 }
1277
1278 void dsos__add(struct dsos *dsos, struct dso *dso)
1279 {
1280         pthread_rwlock_wrlock(&dsos->lock);
1281         __dsos__add(dsos, dso);
1282         pthread_rwlock_unlock(&dsos->lock);
1283 }
1284
1285 struct dso *__dsos__find(struct dsos *dsos, const char *name, bool cmp_short)
1286 {
1287         struct dso *pos;
1288
1289         if (cmp_short) {
1290                 list_for_each_entry(pos, &dsos->head, node)
1291                         if (strcmp(pos->short_name, name) == 0)
1292                                 return pos;
1293                 return NULL;
1294         }
1295         return __dso__find_by_longname(&dsos->root, name);
1296 }
1297
1298 struct dso *dsos__find(struct dsos *dsos, const char *name, bool cmp_short)
1299 {
1300         struct dso *dso;
1301         pthread_rwlock_rdlock(&dsos->lock);
1302         dso = __dsos__find(dsos, name, cmp_short);
1303         pthread_rwlock_unlock(&dsos->lock);
1304         return dso;
1305 }
1306
1307 struct dso *__dsos__addnew(struct dsos *dsos, const char *name)
1308 {
1309         struct dso *dso = dso__new(name);
1310
1311         if (dso != NULL) {
1312                 __dsos__add(dsos, dso);
1313                 dso__set_basename(dso);
1314                 /* Put dso here because __dsos_add already got it */
1315                 dso__put(dso);
1316         }
1317         return dso;
1318 }
1319
1320 struct dso *__dsos__findnew(struct dsos *dsos, const char *name)
1321 {
1322         struct dso *dso = __dsos__find(dsos, name, false);
1323
1324         return dso ? dso : __dsos__addnew(dsos, name);
1325 }
1326
1327 struct dso *dsos__findnew(struct dsos *dsos, const char *name)
1328 {
1329         struct dso *dso;
1330         pthread_rwlock_wrlock(&dsos->lock);
1331         dso = dso__get(__dsos__findnew(dsos, name));
1332         pthread_rwlock_unlock(&dsos->lock);
1333         return dso;
1334 }
1335
1336 size_t __dsos__fprintf_buildid(struct list_head *head, FILE *fp,
1337                                bool (skip)(struct dso *dso, int parm), int parm)
1338 {
1339         struct dso *pos;
1340         size_t ret = 0;
1341
1342         list_for_each_entry(pos, head, node) {
1343                 if (skip && skip(pos, parm))
1344                         continue;
1345                 ret += dso__fprintf_buildid(pos, fp);
1346                 ret += fprintf(fp, " %s\n", pos->long_name);
1347         }
1348         return ret;
1349 }
1350
1351 size_t __dsos__fprintf(struct list_head *head, FILE *fp)
1352 {
1353         struct dso *pos;
1354         size_t ret = 0;
1355
1356         list_for_each_entry(pos, head, node) {
1357                 int i;
1358                 for (i = 0; i < MAP__NR_TYPES; ++i)
1359                         ret += dso__fprintf(pos, i, fp);
1360         }
1361
1362         return ret;
1363 }
1364
1365 size_t dso__fprintf_buildid(struct dso *dso, FILE *fp)
1366 {
1367         char sbuild_id[SBUILD_ID_SIZE];
1368
1369         build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
1370         return fprintf(fp, "%s", sbuild_id);
1371 }
1372
1373 size_t dso__fprintf(struct dso *dso, enum map_type type, FILE *fp)
1374 {
1375         struct rb_node *nd;
1376         size_t ret = fprintf(fp, "dso: %s (", dso->short_name);
1377
1378         if (dso->short_name != dso->long_name)
1379                 ret += fprintf(fp, "%s, ", dso->long_name);
1380         ret += fprintf(fp, "%s, %sloaded, ", map_type__name[type],
1381                        dso__loaded(dso, type) ? "" : "NOT ");
1382         ret += dso__fprintf_buildid(dso, fp);
1383         ret += fprintf(fp, ")\n");
1384         for (nd = rb_first(&dso->symbols[type]); nd; nd = rb_next(nd)) {
1385                 struct symbol *pos = rb_entry(nd, struct symbol, rb_node);
1386                 ret += symbol__fprintf(pos, fp);
1387         }
1388
1389         return ret;
1390 }
1391
1392 enum dso_type dso__type(struct dso *dso, struct machine *machine)
1393 {
1394         int fd;
1395         enum dso_type type = DSO__TYPE_UNKNOWN;
1396
1397         fd = dso__data_get_fd(dso, machine);
1398         if (fd >= 0) {
1399                 type = dso__type_fd(fd);
1400                 dso__data_put_fd(dso);
1401         }
1402
1403         return type;
1404 }
1405
1406 int dso__strerror_load(struct dso *dso, char *buf, size_t buflen)
1407 {
1408         int idx, errnum = dso->load_errno;
1409         /*
1410          * This must have a same ordering as the enum dso_load_errno.
1411          */
1412         static const char *dso_load__error_str[] = {
1413         "Internal tools/perf/ library error",
1414         "Invalid ELF file",
1415         "Can not read build id",
1416         "Mismatching build id",
1417         "Decompression failure",
1418         };
1419
1420         BUG_ON(buflen == 0);
1421
1422         if (errnum >= 0) {
1423                 const char *err = str_error_r(errnum, buf, buflen);
1424
1425                 if (err != buf)
1426                         scnprintf(buf, buflen, "%s", err);
1427
1428                 return 0;
1429         }
1430
1431         if (errnum <  __DSO_LOAD_ERRNO__START || errnum >= __DSO_LOAD_ERRNO__END)
1432                 return -1;
1433
1434         idx = errnum - __DSO_LOAD_ERRNO__START;
1435         scnprintf(buf, buflen, "%s", dso_load__error_str[idx]);
1436         return 0;
1437 }