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