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