PR gdb/14704:
[external/binutils.git] / gdb / gdb_bfd.c
1 /* Definitions for BFD wrappers used by GDB.
2
3    Copyright (C) 2011, 2012
4    Free Software Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22 #include "gdb_bfd.h"
23 #include "gdb_assert.h"
24 #include "gdb_string.h"
25 #include "ui-out.h"
26 #include "gdbcmd.h"
27 #include "hashtab.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   /* If the BFD comes from an archive, this points to the archive's
86      BFD.  Otherwise, this is NULL.  */
87   bfd *archive_bfd;
88
89   /* The registry.  */
90   REGISTRY_FIELDS;
91 };
92
93 #define GDB_BFD_DATA_ACCESSOR(ABFD) \
94   ((struct gdb_bfd_data *) bfd_usrdata (ABFD))
95
96 DEFINE_REGISTRY (bfd, GDB_BFD_DATA_ACCESSOR)
97
98 /* A hash table storing all the BFDs maintained in the cache.  */
99
100 static htab_t gdb_bfd_cache;
101
102 /* The type of an object being looked up in gdb_bfd_cache.  We use
103    htab's capability of storing one kind of object (BFD in this case)
104    and using a different sort of object for searching.  */
105
106 struct gdb_bfd_cache_search
107 {
108   /* The filename.  */
109   const char *filename;
110   /* The mtime.  */
111   time_t mtime;
112 };
113
114 /* A hash function for BFDs.  */
115
116 static hashval_t
117 hash_bfd (const void *b)
118 {
119   const bfd *abfd = b;
120
121   /* It is simplest to just hash the filename.  */
122   return htab_hash_string (bfd_get_filename (abfd));
123 }
124
125 /* An equality function for BFDs.  Note that this expects the caller
126    to search using struct gdb_bfd_cache_search only, not BFDs.  */
127
128 static int
129 eq_bfd (const void *a, const void *b)
130 {
131   const bfd *abfd = a;
132   const struct gdb_bfd_cache_search *s = b;
133   struct gdb_bfd_data *gdata = bfd_usrdata (abfd);
134
135   return (gdata->mtime == s->mtime
136           && strcmp (bfd_get_filename (abfd), s->filename) == 0);
137 }
138
139 /* See gdb_bfd.h.  */
140
141 struct bfd *
142 gdb_bfd_open (const char *name, const char *target, int fd)
143 {
144   hashval_t hash;
145   void **slot;
146   bfd *abfd;
147   struct gdb_bfd_cache_search search;
148   struct stat st;
149
150   if (gdb_bfd_cache == NULL)
151     gdb_bfd_cache = htab_create_alloc (1, hash_bfd, eq_bfd, NULL,
152                                        xcalloc, xfree);
153
154   if (fd == -1)
155     {
156       fd = open (name, O_RDONLY | O_BINARY);
157       if (fd == -1)
158         {
159           bfd_set_error (bfd_error_system_call);
160           return NULL;
161         }
162     }
163
164   search.filename = name;
165   if (fstat (fd, &st) < 0)
166     {
167       /* Weird situation here.  */
168       search.mtime = 0;
169     }
170   else
171     search.mtime = st.st_mtime;
172
173   /* Note that this must compute the same result as hash_bfd.  */
174   hash = htab_hash_string (name);
175   /* Note that we cannot use htab_find_slot_with_hash here, because
176      opening the BFD may fail; and this would violate hashtab
177      invariants.  */
178   abfd = htab_find_with_hash (gdb_bfd_cache, &search, hash);
179   if (abfd != NULL)
180     {
181       close (fd);
182       gdb_bfd_ref (abfd);
183       return abfd;
184     }
185
186   abfd = bfd_fopen (name, target, FOPEN_RB, fd);
187   if (abfd == NULL)
188     return NULL;
189
190   slot = htab_find_slot_with_hash (gdb_bfd_cache, &search, hash, INSERT);
191   gdb_assert (!*slot);
192   *slot = abfd;
193
194   gdb_bfd_stash_filename (abfd);
195   gdb_bfd_ref (abfd);
196   return abfd;
197 }
198
199 /* A helper function that releases any section data attached to the
200    BFD.  */
201
202 static void
203 free_one_bfd_section (bfd *abfd, asection *sectp, void *ignore)
204 {
205   struct gdb_bfd_section_data *sect = bfd_get_section_userdata (abfd, sectp);
206
207   if (sect != NULL && sect->data != NULL)
208     {
209 #ifdef HAVE_MMAP
210       if (sect->map_addr != NULL)
211         {
212           int res;
213
214           res = munmap (sect->map_addr, sect->map_len);
215           gdb_assert (res == 0);
216         }
217       else
218 #endif
219         xfree (sect->data);
220     }
221 }
222
223 /* Close ABFD, and warn if that fails.  */
224
225 static int
226 gdb_bfd_close_or_warn (struct bfd *abfd)
227 {
228   int ret;
229   char *name = bfd_get_filename (abfd);
230
231   bfd_map_over_sections (abfd, free_one_bfd_section, NULL);
232
233   ret = bfd_close (abfd);
234
235   if (!ret)
236     warning (_("cannot close \"%s\": %s"),
237              name, bfd_errmsg (bfd_get_error ()));
238
239   return ret;
240 }
241
242 /* See gdb_bfd.h.  */
243
244 void
245 gdb_bfd_ref (struct bfd *abfd)
246 {
247   struct gdb_bfd_data *gdata;
248   void **slot;
249
250   if (abfd == NULL)
251     return;
252
253   gdata = bfd_usrdata (abfd);
254
255   if (gdata != NULL)
256     {
257       gdata->refc += 1;
258       return;
259     }
260
261   /* Ask BFD to decompress sections in bfd_get_full_section_contents.  */
262   abfd->flags |= BFD_DECOMPRESS;
263
264   gdata = bfd_zalloc (abfd, sizeof (struct gdb_bfd_data));
265   gdata->refc = 1;
266   gdata->mtime = bfd_get_mtime (abfd);
267   gdata->archive_bfd = NULL;
268   bfd_usrdata (abfd) = gdata;
269
270   bfd_alloc_data (abfd);
271
272   /* This is the first we've seen it, so add it to the hash table.  */
273   slot = htab_find_slot (all_bfds, abfd, INSERT);
274   gdb_assert (slot && !*slot);
275   *slot = abfd;
276 }
277
278 /* See gdb_bfd.h.  */
279
280 void
281 gdb_bfd_unref (struct bfd *abfd)
282 {
283   struct gdb_bfd_data *gdata;
284   struct gdb_bfd_cache_search search;
285   bfd *archive_bfd;
286
287   if (abfd == NULL)
288     return;
289
290   gdata = bfd_usrdata (abfd);
291   gdb_assert (gdata->refc >= 1);
292
293   gdata->refc -= 1;
294   if (gdata->refc > 0)
295     return;
296
297   archive_bfd = gdata->archive_bfd;
298   search.filename = bfd_get_filename (abfd);
299
300   if (gdb_bfd_cache && search.filename)
301     {
302       hashval_t hash = htab_hash_string (search.filename);
303       void **slot;
304
305       search.mtime = gdata->mtime;
306       slot = htab_find_slot_with_hash (gdb_bfd_cache, &search, hash,
307                                        NO_INSERT);
308
309       if (slot && *slot)
310         htab_clear_slot (gdb_bfd_cache, slot);
311     }
312
313   bfd_free_data (abfd);
314   bfd_usrdata (abfd) = NULL;  /* Paranoia.  */
315
316   htab_remove_elt (all_bfds, abfd);
317
318   gdb_bfd_close_or_warn (abfd);
319
320   gdb_bfd_unref (archive_bfd);
321 }
322
323 /* A helper function that returns the section data descriptor
324    associated with SECTION.  If no such descriptor exists, a new one
325    is allocated and cleared.  */
326
327 static struct gdb_bfd_section_data *
328 get_section_descriptor (asection *section)
329 {
330   struct gdb_bfd_section_data *result;
331
332   result = bfd_get_section_userdata (section->owner, section);
333
334   if (result == NULL)
335     {
336       result = bfd_zalloc (section->owner, sizeof (*result));
337       bfd_set_section_userdata (section->owner, section, result);
338     }
339
340   return result;
341 }
342
343 /* See gdb_bfd.h.  */
344
345 const gdb_byte *
346 gdb_bfd_map_section (asection *sectp, bfd_size_type *size)
347 {
348   bfd *abfd;
349   unsigned char header[4];
350   struct gdb_bfd_section_data *descriptor;
351   bfd_byte *data;
352
353   gdb_assert ((sectp->flags & SEC_RELOC) == 0);
354   gdb_assert (size != NULL);
355
356   abfd = sectp->owner;
357
358   descriptor = get_section_descriptor (sectp);
359
360   /* If the data was already read for this BFD, just reuse it.  */
361   if (descriptor->data != NULL)
362     goto done;
363
364 #ifdef HAVE_MMAP
365   if (!bfd_is_section_compressed (abfd, sectp))
366     {
367       /* The page size, used when mmapping.  */
368       static int pagesize;
369
370       if (pagesize == 0)
371         pagesize = getpagesize ();
372
373       /* Only try to mmap sections which are large enough: we don't want
374          to waste space due to fragmentation.  */
375
376       if (bfd_get_section_size (sectp) > 4 * pagesize)
377         {
378           descriptor->size = bfd_get_section_size (sectp);
379           descriptor->data = bfd_mmap (abfd, 0, descriptor->size, PROT_READ,
380                                        MAP_PRIVATE, sectp->filepos,
381                                        &descriptor->map_addr,
382                                        &descriptor->map_len);
383
384           if ((caddr_t)descriptor->data != MAP_FAILED)
385             {
386 #if HAVE_POSIX_MADVISE
387               posix_madvise (descriptor->map_addr, descriptor->map_len,
388                              POSIX_MADV_WILLNEED);
389 #endif
390               goto done;
391             }
392
393           /* On failure, clear out the section data and try again.  */
394           memset (descriptor, 0, sizeof (*descriptor));
395         }
396     }
397 #endif /* HAVE_MMAP */
398
399   /* Handle compressed sections, or ordinary uncompressed sections in
400      the no-mmap case.  */
401
402   descriptor->size = bfd_get_section_size (sectp);
403   descriptor->data = NULL;
404
405   data = NULL;
406   if (!bfd_get_full_section_contents (abfd, sectp, &data))
407     error (_("Can't read data for section '%s' in file '%s'"),
408            bfd_get_section_name (abfd, sectp),
409            bfd_get_filename (abfd));
410   descriptor->data = data;
411
412  done:
413   gdb_assert (descriptor->data != NULL);
414   *size = descriptor->size;
415   return descriptor->data;
416 }
417
418 \f
419
420 /* See gdb_bfd.h.  */
421
422 bfd *
423 gdb_bfd_fopen (const char *filename, const char *target, const char *mode,
424                int fd)
425 {
426   bfd *result = bfd_fopen (filename, target, mode, fd);
427
428   if (result)
429     {
430       gdb_bfd_stash_filename (result);
431       gdb_bfd_ref (result);
432     }
433
434   return result;
435 }
436
437 /* See gdb_bfd.h.  */
438
439 bfd *
440 gdb_bfd_openr (const char *filename, const char *target)
441 {
442   bfd *result = bfd_openr (filename, target);
443
444   if (result)
445     {
446       gdb_bfd_stash_filename (result);
447       gdb_bfd_ref (result);
448     }
449
450   return result;
451 }
452
453 /* See gdb_bfd.h.  */
454
455 bfd *
456 gdb_bfd_openw (const char *filename, const char *target)
457 {
458   bfd *result = bfd_openw (filename, target);
459
460   if (result)
461     {
462       gdb_bfd_stash_filename (result);
463       gdb_bfd_ref (result);
464     }
465
466   return result;
467 }
468
469 /* See gdb_bfd.h.  */
470
471 bfd *
472 gdb_bfd_openr_iovec (const char *filename, const char *target,
473                      void *(*open_func) (struct bfd *nbfd,
474                                          void *open_closure),
475                      void *open_closure,
476                      file_ptr (*pread_func) (struct bfd *nbfd,
477                                              void *stream,
478                                              void *buf,
479                                              file_ptr nbytes,
480                                              file_ptr offset),
481                      int (*close_func) (struct bfd *nbfd,
482                                         void *stream),
483                      int (*stat_func) (struct bfd *abfd,
484                                        void *stream,
485                                        struct stat *sb))
486 {
487   bfd *result = bfd_openr_iovec (filename, target,
488                                  open_func, open_closure,
489                                  pread_func, close_func, stat_func);
490
491   if (result)
492     {
493       gdb_bfd_ref (result);
494       gdb_bfd_stash_filename (result);
495     }
496
497   return result;
498 }
499
500 /* See gdb_bfd.h.  */
501
502 bfd *
503 gdb_bfd_openr_next_archived_file (bfd *archive, bfd *previous)
504 {
505   bfd *result = bfd_openr_next_archived_file (archive, previous);
506
507   if (result)
508     {
509       struct gdb_bfd_data *gdata;
510
511       gdb_bfd_ref (result);
512       /* No need to stash the filename here, because we also keep a
513          reference on the parent archive.  */
514
515       gdata = bfd_usrdata (result);
516       gdb_assert (gdata->archive_bfd == NULL || gdata->archive_bfd == archive);
517       gdata->archive_bfd = archive;
518       gdb_bfd_ref (archive);
519     }
520
521   return result;
522 }
523
524 /* See gdb_bfd.h.  */
525
526 bfd *
527 gdb_bfd_fdopenr (const char *filename, const char *target, int fd)
528 {
529   bfd *result = bfd_fdopenr (filename, target, fd);
530
531   if (result)
532     {
533       gdb_bfd_ref (result);
534       gdb_bfd_stash_filename (result);
535     }
536
537   return result;
538 }
539
540 \f
541
542 /* A callback for htab_traverse that prints a single BFD.  */
543
544 static int
545 print_one_bfd (void **slot, void *data)
546 {
547   bfd *abfd = *slot;
548   struct gdb_bfd_data *gdata = bfd_usrdata (abfd);
549   struct ui_out *uiout = data;
550   struct cleanup *inner;
551
552   inner = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
553   ui_out_field_int (uiout, "refcount", gdata->refc);
554   ui_out_field_string (uiout, "addr", host_address_to_string (abfd));
555   ui_out_field_string (uiout, "filename", bfd_get_filename (abfd));
556   ui_out_text (uiout, "\n");
557   do_cleanups (inner);
558
559   return 1;
560 }
561
562 /* Implement the 'maint info bfd' command.  */
563
564 static void
565 maintenance_info_bfds (char *arg, int from_tty)
566 {
567   struct cleanup *cleanup;
568   struct ui_out *uiout = current_uiout;
569
570   cleanup = make_cleanup_ui_out_table_begin_end (uiout, 3, -1, "bfds");
571   ui_out_table_header (uiout, 10, ui_left, "refcount", "Refcount");
572   ui_out_table_header (uiout, 18, ui_left, "addr", "Address");
573   ui_out_table_header (uiout, 40, ui_left, "filename", "Filename");
574
575   ui_out_table_body (uiout);
576   htab_traverse (all_bfds, print_one_bfd, uiout);
577
578   do_cleanups (cleanup);
579 }
580
581 /* -Wmissing-prototypes */
582 extern initialize_file_ftype _initialize_gdb_bfd;
583
584 void
585 _initialize_gdb_bfd (void)
586 {
587   all_bfds = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
588                                 NULL, xcalloc, xfree);
589
590   add_cmd ("bfds", class_maintenance, maintenance_info_bfds, _("\
591 List the BFDs that are currently open."),
592            &maintenanceinfolist);
593 }