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