OSDN Git Service

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