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