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