Fix crash on optimized-out entry data values
[platform/upstream/binutils.git] / gdb / gdb_bfd.c
1 /* Definitions for BFD wrappers used by GDB.
2
3    Copyright (C) 2011-2014 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "gdb_bfd.h"
22 #include "gdb_assert.h"
23 #include <string.h>
24 #include "ui-out.h"
25 #include "gdbcmd.h"
26 #include "hashtab.h"
27 #include "filestuff.h"
28 #include "vec.h"
29 #ifdef HAVE_ZLIB_H
30 #include <zlib.h>
31 #endif
32 #ifdef HAVE_MMAP
33 #include <sys/mman.h>
34 #ifndef MAP_FAILED
35 #define MAP_FAILED ((void *) -1)
36 #endif
37 #endif
38
39 typedef bfd *bfdp;
40 DEF_VEC_P (bfdp);
41
42 /* An object of this type is stored in the section's user data when
43    mapping a section.  */
44
45 struct gdb_bfd_section_data
46 {
47   /* Size of the data.  */
48   bfd_size_type size;
49   /* If the data was mmapped, this is the length of the map.  */
50   bfd_size_type map_len;
51   /* The data.  If NULL, the section data has not been read.  */
52   void *data;
53   /* If the data was mmapped, this is the map address.  */
54   void *map_addr;
55 };
56
57 /* A hash table holding every BFD that gdb knows about.  This is not
58    to be confused with 'gdb_bfd_cache', which is used for sharing
59    BFDs; in contrast, this hash is used just to implement
60    "maint info bfd".  */
61
62 static htab_t all_bfds;
63
64 /* An object of this type is stored in each BFD's user data.  */
65
66 struct gdb_bfd_data
67 {
68   /* The reference count.  */
69   int refc;
70
71   /* The mtime of the BFD at the point the cache entry was made.  */
72   time_t mtime;
73
74   /* This is true if we have determined whether this BFD has any
75      sections requiring relocation.  */
76   unsigned int relocation_computed : 1;
77
78   /* This is true if any section needs relocation.  */
79   unsigned int needs_relocations : 1;
80
81   /* This is true if we have successfully computed the file's CRC.  */
82   unsigned int crc_computed : 1;
83
84   /* The file's CRC.  */
85   unsigned long crc;
86
87   /* If the BFD comes from an archive, this points to the archive's
88      BFD.  Otherwise, this is NULL.  */
89   bfd *archive_bfd;
90
91   /* Table of all the bfds this bfd has included.  */
92   VEC (bfdp) *included_bfds;
93
94   /* The registry.  */
95   REGISTRY_FIELDS;
96 };
97
98 #define GDB_BFD_DATA_ACCESSOR(ABFD) \
99   ((struct gdb_bfd_data *) bfd_usrdata (ABFD))
100
101 DEFINE_REGISTRY (bfd, GDB_BFD_DATA_ACCESSOR)
102
103 /* A hash table storing all the BFDs maintained in the cache.  */
104
105 static htab_t gdb_bfd_cache;
106
107 /* The type of an object being looked up in gdb_bfd_cache.  We use
108    htab's capability of storing one kind of object (BFD in this case)
109    and using a different sort of object for searching.  */
110
111 struct gdb_bfd_cache_search
112 {
113   /* The filename.  */
114   const char *filename;
115   /* The mtime.  */
116   time_t mtime;
117 };
118
119 /* A hash function for BFDs.  */
120
121 static hashval_t
122 hash_bfd (const void *b)
123 {
124   const bfd *abfd = b;
125
126   /* It is simplest to just hash the filename.  */
127   return htab_hash_string (bfd_get_filename (abfd));
128 }
129
130 /* An equality function for BFDs.  Note that this expects the caller
131    to search using struct gdb_bfd_cache_search only, not BFDs.  */
132
133 static int
134 eq_bfd (const void *a, const void *b)
135 {
136   const bfd *abfd = a;
137   const struct gdb_bfd_cache_search *s = b;
138   struct gdb_bfd_data *gdata = bfd_usrdata (abfd);
139
140   return (gdata->mtime == s->mtime
141           && strcmp (bfd_get_filename (abfd), s->filename) == 0);
142 }
143
144 /* See gdb_bfd.h.  */
145
146 struct bfd *
147 gdb_bfd_open (const char *name, const char *target, int fd)
148 {
149   hashval_t hash;
150   void **slot;
151   bfd *abfd;
152   struct gdb_bfd_cache_search search;
153   struct stat st;
154
155   if (gdb_bfd_cache == NULL)
156     gdb_bfd_cache = htab_create_alloc (1, hash_bfd, eq_bfd, NULL,
157                                        xcalloc, xfree);
158
159   if (fd == -1)
160     {
161       fd = gdb_open_cloexec (name, O_RDONLY | O_BINARY, 0);
162       if (fd == -1)
163         {
164           bfd_set_error (bfd_error_system_call);
165           return NULL;
166         }
167     }
168
169   search.filename = name;
170   if (fstat (fd, &st) < 0)
171     {
172       /* Weird situation here.  */
173       search.mtime = 0;
174     }
175   else
176     search.mtime = st.st_mtime;
177
178   /* Note that this must compute the same result as hash_bfd.  */
179   hash = htab_hash_string (name);
180   /* Note that we cannot use htab_find_slot_with_hash here, because
181      opening the BFD may fail; and this would violate hashtab
182      invariants.  */
183   abfd = htab_find_with_hash (gdb_bfd_cache, &search, hash);
184   if (abfd != NULL)
185     {
186       close (fd);
187       gdb_bfd_ref (abfd);
188       return abfd;
189     }
190
191   abfd = bfd_fopen (name, target, FOPEN_RB, fd);
192   if (abfd == NULL)
193     return NULL;
194
195   slot = htab_find_slot_with_hash (gdb_bfd_cache, &search, hash, INSERT);
196   gdb_assert (!*slot);
197   *slot = abfd;
198
199   gdb_bfd_ref (abfd);
200   return abfd;
201 }
202
203 /* A helper function that releases any section data attached to the
204    BFD.  */
205
206 static void
207 free_one_bfd_section (bfd *abfd, asection *sectp, void *ignore)
208 {
209   struct gdb_bfd_section_data *sect = bfd_get_section_userdata (abfd, sectp);
210
211   if (sect != NULL && sect->data != NULL)
212     {
213 #ifdef HAVE_MMAP
214       if (sect->map_addr != NULL)
215         {
216           int res;
217
218           res = munmap (sect->map_addr, sect->map_len);
219           gdb_assert (res == 0);
220         }
221       else
222 #endif
223         xfree (sect->data);
224     }
225 }
226
227 /* Close ABFD, and warn if that fails.  */
228
229 static int
230 gdb_bfd_close_or_warn (struct bfd *abfd)
231 {
232   int ret;
233   char *name = bfd_get_filename (abfd);
234
235   bfd_map_over_sections (abfd, free_one_bfd_section, NULL);
236
237   ret = bfd_close (abfd);
238
239   if (!ret)
240     warning (_("cannot close \"%s\": %s"),
241              name, bfd_errmsg (bfd_get_error ()));
242
243   return ret;
244 }
245
246 /* See gdb_bfd.h.  */
247
248 void
249 gdb_bfd_ref (struct bfd *abfd)
250 {
251   struct gdb_bfd_data *gdata;
252   void **slot;
253
254   if (abfd == NULL)
255     return;
256
257   gdata = bfd_usrdata (abfd);
258
259   if (gdata != NULL)
260     {
261       gdata->refc += 1;
262       return;
263     }
264
265   /* Ask BFD to decompress sections in bfd_get_full_section_contents.  */
266   abfd->flags |= BFD_DECOMPRESS;
267
268   gdata = bfd_zalloc (abfd, sizeof (struct gdb_bfd_data));
269   gdata->refc = 1;
270   gdata->mtime = bfd_get_mtime (abfd);
271   gdata->archive_bfd = NULL;
272   bfd_usrdata (abfd) = gdata;
273
274   bfd_alloc_data (abfd);
275
276   /* This is the first we've seen it, so add it to the hash table.  */
277   slot = htab_find_slot (all_bfds, abfd, INSERT);
278   gdb_assert (slot && !*slot);
279   *slot = abfd;
280 }
281
282 /* See gdb_bfd.h.  */
283
284 void
285 gdb_bfd_unref (struct bfd *abfd)
286 {
287   int ix;
288   struct gdb_bfd_data *gdata;
289   struct gdb_bfd_cache_search search;
290   bfd *archive_bfd, *included_bfd;
291
292   if (abfd == NULL)
293     return;
294
295   gdata = bfd_usrdata (abfd);
296   gdb_assert (gdata->refc >= 1);
297
298   gdata->refc -= 1;
299   if (gdata->refc > 0)
300     return;
301
302   archive_bfd = gdata->archive_bfd;
303   search.filename = bfd_get_filename (abfd);
304
305   if (gdb_bfd_cache && search.filename)
306     {
307       hashval_t hash = htab_hash_string (search.filename);
308       void **slot;
309
310       search.mtime = gdata->mtime;
311       slot = htab_find_slot_with_hash (gdb_bfd_cache, &search, hash,
312                                        NO_INSERT);
313
314       if (slot && *slot)
315         htab_clear_slot (gdb_bfd_cache, slot);
316     }
317
318   for (ix = 0;
319        VEC_iterate (bfdp, gdata->included_bfds, ix, included_bfd);
320        ++ix)
321     gdb_bfd_unref (included_bfd);
322   VEC_free (bfdp, gdata->included_bfds);
323
324   bfd_free_data (abfd);
325   bfd_usrdata (abfd) = NULL;  /* Paranoia.  */
326
327   htab_remove_elt (all_bfds, abfd);
328
329   gdb_bfd_close_or_warn (abfd);
330
331   gdb_bfd_unref (archive_bfd);
332 }
333
334 /* A helper function that returns the section data descriptor
335    associated with SECTION.  If no such descriptor exists, a new one
336    is allocated and cleared.  */
337
338 static struct gdb_bfd_section_data *
339 get_section_descriptor (asection *section)
340 {
341   struct gdb_bfd_section_data *result;
342
343   result = bfd_get_section_userdata (section->owner, section);
344
345   if (result == NULL)
346     {
347       result = bfd_zalloc (section->owner, sizeof (*result));
348       bfd_set_section_userdata (section->owner, section, result);
349     }
350
351   return result;
352 }
353
354 /* See gdb_bfd.h.  */
355
356 const gdb_byte *
357 gdb_bfd_map_section (asection *sectp, bfd_size_type *size)
358 {
359   bfd *abfd;
360   struct gdb_bfd_section_data *descriptor;
361   bfd_byte *data;
362
363   gdb_assert ((sectp->flags & SEC_RELOC) == 0);
364   gdb_assert (size != NULL);
365
366   abfd = sectp->owner;
367
368   descriptor = get_section_descriptor (sectp);
369
370   /* If the data was already read for this BFD, just reuse it.  */
371   if (descriptor->data != NULL)
372     goto done;
373
374 #ifdef HAVE_MMAP
375   if (!bfd_is_section_compressed (abfd, sectp))
376     {
377       /* The page size, used when mmapping.  */
378       static int pagesize;
379
380       if (pagesize == 0)
381         pagesize = getpagesize ();
382
383       /* Only try to mmap sections which are large enough: we don't want
384          to waste space due to fragmentation.  */
385
386       if (bfd_get_section_size (sectp) > 4 * pagesize)
387         {
388           descriptor->size = bfd_get_section_size (sectp);
389           descriptor->data = bfd_mmap (abfd, 0, descriptor->size, PROT_READ,
390                                        MAP_PRIVATE, sectp->filepos,
391                                        &descriptor->map_addr,
392                                        &descriptor->map_len);
393
394           if ((caddr_t)descriptor->data != MAP_FAILED)
395             {
396 #if HAVE_POSIX_MADVISE
397               posix_madvise (descriptor->map_addr, descriptor->map_len,
398                              POSIX_MADV_WILLNEED);
399 #endif
400               goto done;
401             }
402
403           /* On failure, clear out the section data and try again.  */
404           memset (descriptor, 0, sizeof (*descriptor));
405         }
406     }
407 #endif /* HAVE_MMAP */
408
409   /* Handle compressed sections, or ordinary uncompressed sections in
410      the no-mmap case.  */
411
412   descriptor->size = bfd_get_section_size (sectp);
413   descriptor->data = NULL;
414
415   data = NULL;
416   if (!bfd_get_full_section_contents (abfd, sectp, &data))
417     error (_("Can't read data for section '%s' in file '%s'"),
418            bfd_get_section_name (abfd, sectp),
419            bfd_get_filename (abfd));
420   descriptor->data = data;
421
422  done:
423   gdb_assert (descriptor->data != NULL);
424   *size = descriptor->size;
425   return descriptor->data;
426 }
427
428 /* Return 32-bit CRC for ABFD.  If successful store it to *FILE_CRC_RETURN and
429    return 1.  Otherwise print a warning and return 0.  ABFD seek position is
430    not preserved.  */
431
432 static int
433 get_file_crc (bfd *abfd, unsigned long *file_crc_return)
434 {
435   unsigned long file_crc = 0;
436
437   if (bfd_seek (abfd, 0, SEEK_SET) != 0)
438     {
439       warning (_("Problem reading \"%s\" for CRC: %s"),
440                bfd_get_filename (abfd), bfd_errmsg (bfd_get_error ()));
441       return 0;
442     }
443
444   for (;;)
445     {
446       gdb_byte buffer[8 * 1024];
447       bfd_size_type count;
448
449       count = bfd_bread (buffer, sizeof (buffer), abfd);
450       if (count == (bfd_size_type) -1)
451         {
452           warning (_("Problem reading \"%s\" for CRC: %s"),
453                    bfd_get_filename (abfd), bfd_errmsg (bfd_get_error ()));
454           return 0;
455         }
456       if (count == 0)
457         break;
458       file_crc = bfd_calc_gnu_debuglink_crc32 (file_crc, buffer, count);
459     }
460
461   *file_crc_return = file_crc;
462   return 1;
463 }
464
465 /* See gdb_bfd.h.  */
466
467 int
468 gdb_bfd_crc (struct bfd *abfd, unsigned long *crc_out)
469 {
470   struct gdb_bfd_data *gdata = bfd_usrdata (abfd);
471
472   if (!gdata->crc_computed)
473     gdata->crc_computed = get_file_crc (abfd, &gdata->crc);
474
475   if (gdata->crc_computed)
476     *crc_out = gdata->crc;
477   return gdata->crc_computed;
478 }
479
480 \f
481
482 /* See gdb_bfd.h.  */
483
484 bfd *
485 gdb_bfd_fopen (const char *filename, const char *target, const char *mode,
486                int fd)
487 {
488   bfd *result = bfd_fopen (filename, target, mode, fd);
489
490   if (result)
491     gdb_bfd_ref (result);
492
493   return result;
494 }
495
496 /* See gdb_bfd.h.  */
497
498 bfd *
499 gdb_bfd_openr (const char *filename, const char *target)
500 {
501   bfd *result = bfd_openr (filename, target);
502
503   if (result)
504     gdb_bfd_ref (result);
505
506   return result;
507 }
508
509 /* See gdb_bfd.h.  */
510
511 bfd *
512 gdb_bfd_openw (const char *filename, const char *target)
513 {
514   bfd *result = bfd_openw (filename, target);
515
516   if (result)
517     gdb_bfd_ref (result);
518
519   return result;
520 }
521
522 /* See gdb_bfd.h.  */
523
524 bfd *
525 gdb_bfd_openr_iovec (const char *filename, const char *target,
526                      void *(*open_func) (struct bfd *nbfd,
527                                          void *open_closure),
528                      void *open_closure,
529                      file_ptr (*pread_func) (struct bfd *nbfd,
530                                              void *stream,
531                                              void *buf,
532                                              file_ptr nbytes,
533                                              file_ptr offset),
534                      int (*close_func) (struct bfd *nbfd,
535                                         void *stream),
536                      int (*stat_func) (struct bfd *abfd,
537                                        void *stream,
538                                        struct stat *sb))
539 {
540   bfd *result = bfd_openr_iovec (filename, target,
541                                  open_func, open_closure,
542                                  pread_func, close_func, stat_func);
543
544   if (result)
545     gdb_bfd_ref (result);
546
547   return result;
548 }
549
550 /* See gdb_bfd.h.  */
551
552 void
553 gdb_bfd_mark_parent (bfd *child, bfd *parent)
554 {
555   struct gdb_bfd_data *gdata;
556
557   gdb_bfd_ref (child);
558   /* No need to stash the filename here, because we also keep a
559      reference on the parent archive.  */
560
561   gdata = bfd_usrdata (child);
562   if (gdata->archive_bfd == NULL)
563     {
564       gdata->archive_bfd = parent;
565       gdb_bfd_ref (parent);
566     }
567   else
568     gdb_assert (gdata->archive_bfd == parent);
569 }
570
571 /* See gdb_bfd.h.  */
572
573 bfd *
574 gdb_bfd_openr_next_archived_file (bfd *archive, bfd *previous)
575 {
576   bfd *result = bfd_openr_next_archived_file (archive, previous);
577
578   if (result)
579     gdb_bfd_mark_parent (result, archive);
580
581   return result;
582 }
583
584 /* See gdb_bfd.h.  */
585
586 void
587 gdb_bfd_record_inclusion (bfd *includer, bfd *includee)
588 {
589   struct gdb_bfd_data *gdata;
590
591   gdb_bfd_ref (includee);
592   gdata = bfd_usrdata (includer);
593   VEC_safe_push (bfdp, gdata->included_bfds, includee);
594 }
595
596 /* See gdb_bfd.h.  */
597
598 bfd *
599 gdb_bfd_fdopenr (const char *filename, const char *target, int fd)
600 {
601   bfd *result = bfd_fdopenr (filename, target, fd);
602
603   if (result)
604     gdb_bfd_ref (result);
605
606   return result;
607 }
608
609 \f
610
611 gdb_static_assert (ARRAY_SIZE (_bfd_std_section) == 4);
612
613 /* See gdb_bfd.h.  */
614
615 int
616 gdb_bfd_section_index (bfd *abfd, asection *section)
617 {
618   if (section == NULL)
619     return -1;
620   else if (section == bfd_com_section_ptr)
621     return bfd_count_sections (abfd) + 1;
622   else if (section == bfd_und_section_ptr)
623     return bfd_count_sections (abfd) + 2;
624   else if (section == bfd_abs_section_ptr)
625     return bfd_count_sections (abfd) + 3;
626   else if (section == bfd_ind_section_ptr)
627     return bfd_count_sections (abfd) + 4;
628   return section->index;
629 }
630
631 /* See gdb_bfd.h.  */
632
633 int
634 gdb_bfd_count_sections (bfd *abfd)
635 {
636   return bfd_count_sections (abfd) + 4;
637 }
638
639 /* See gdb_bfd.h.  */
640
641 int
642 gdb_bfd_requires_relocations (bfd *abfd)
643 {
644   struct gdb_bfd_data *gdata = bfd_usrdata (abfd);
645
646   if (gdata->relocation_computed == 0)
647     {
648       asection *sect;
649
650       for (sect = abfd->sections; sect != NULL; sect = sect->next)
651         if ((sect->flags & SEC_RELOC) != 0)
652           {
653             gdata->needs_relocations = 1;
654             break;
655           }
656
657       gdata->relocation_computed = 1;
658     }
659
660   return gdata->needs_relocations;
661 }
662
663 \f
664
665 /* A callback for htab_traverse that prints a single BFD.  */
666
667 static int
668 print_one_bfd (void **slot, void *data)
669 {
670   bfd *abfd = *slot;
671   struct gdb_bfd_data *gdata = bfd_usrdata (abfd);
672   struct ui_out *uiout = data;
673   struct cleanup *inner;
674
675   inner = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
676   ui_out_field_int (uiout, "refcount", gdata->refc);
677   ui_out_field_string (uiout, "addr", host_address_to_string (abfd));
678   ui_out_field_string (uiout, "filename", bfd_get_filename (abfd));
679   ui_out_text (uiout, "\n");
680   do_cleanups (inner);
681
682   return 1;
683 }
684
685 /* Implement the 'maint info bfd' command.  */
686
687 static void
688 maintenance_info_bfds (char *arg, int from_tty)
689 {
690   struct cleanup *cleanup;
691   struct ui_out *uiout = current_uiout;
692
693   cleanup = make_cleanup_ui_out_table_begin_end (uiout, 3, -1, "bfds");
694   ui_out_table_header (uiout, 10, ui_left, "refcount", "Refcount");
695   ui_out_table_header (uiout, 18, ui_left, "addr", "Address");
696   ui_out_table_header (uiout, 40, ui_left, "filename", "Filename");
697
698   ui_out_table_body (uiout);
699   htab_traverse (all_bfds, print_one_bfd, uiout);
700
701   do_cleanups (cleanup);
702 }
703
704 /* -Wmissing-prototypes */
705 extern initialize_file_ftype _initialize_gdb_bfd;
706
707 void
708 _initialize_gdb_bfd (void)
709 {
710   all_bfds = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
711                                 NULL, xcalloc, xfree);
712
713   add_cmd ("bfds", class_maintenance, maintenance_info_bfds, _("\
714 List the BFDs that are currently open."),
715            &maintenanceinfolist);
716 }