* dwarf2read.c: Don't include zlib.h or sys/mman.h.
[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 "hashtab.h"
26 #ifdef HAVE_ZLIB_H
27 #include <zlib.h>
28 #endif
29 #ifdef HAVE_MMAP
30 #include <sys/mman.h>
31 #ifndef MAP_FAILED
32 #define MAP_FAILED ((void *) -1)
33 #endif
34 #endif
35
36 /* An object of this type is stored in the section's user data when
37    mapping a section.  */
38
39 struct gdb_bfd_section_data
40 {
41   /* Size of the data.  */
42   bfd_size_type size;
43   /* If the data was mmapped, this is the length of the map.  */
44   bfd_size_type map_len;
45   /* The data.  If NULL, the section data has not been read.  */
46   void *data;
47   /* If the data was mmapped, this is the map address.  */
48   void *map_addr;
49 };
50
51 /* See gdb_bfd.h.  */
52
53 void
54 gdb_bfd_stash_filename (struct bfd *abfd)
55 {
56   char *name = bfd_get_filename (abfd);
57   char *data;
58
59   data = bfd_alloc (abfd, strlen (name) + 1);
60   strcpy (data, name);
61
62   /* Unwarranted chumminess with BFD.  */
63   abfd->filename = data;
64 }
65
66 /* An object of this type is stored in each BFD's user data.  */
67
68 struct gdb_bfd_data
69 {
70   /* The reference count.  */
71   int refc;
72
73   /* The mtime of the BFD at the point the cache entry was made.  */
74   time_t mtime;
75 };
76
77 /* A hash table storing all the BFDs maintained in the cache.  */
78
79 static htab_t gdb_bfd_cache;
80
81 /* The type of an object being looked up in gdb_bfd_cache.  We use
82    htab's capability of storing one kind of object (BFD in this case)
83    and using a different sort of object for searching.  */
84
85 struct gdb_bfd_cache_search
86 {
87   /* The filename.  */
88   const char *filename;
89   /* The mtime.  */
90   time_t mtime;
91 };
92
93 /* A hash function for BFDs.  */
94
95 static hashval_t
96 hash_bfd (const void *b)
97 {
98   const bfd *abfd = b;
99
100   /* It is simplest to just hash the filename.  */
101   return htab_hash_string (bfd_get_filename (abfd));
102 }
103
104 /* An equality function for BFDs.  Note that this expects the caller
105    to search using struct gdb_bfd_cache_search only, not BFDs.  */
106
107 static int
108 eq_bfd (const void *a, const void *b)
109 {
110   const bfd *abfd = a;
111   const struct gdb_bfd_cache_search *s = b;
112   struct gdb_bfd_data *gdata = bfd_usrdata (abfd);
113
114   return (gdata->mtime == s->mtime
115           && strcmp (bfd_get_filename (abfd), s->filename) == 0);
116 }
117
118 /* See gdb_bfd.h.  */
119
120 struct bfd *
121 gdb_bfd_open (const char *name, const char *target, int fd)
122 {
123   hashval_t hash;
124   void **slot;
125   bfd *abfd;
126   struct gdb_bfd_cache_search search;
127   struct stat st;
128
129   if (gdb_bfd_cache == NULL)
130     gdb_bfd_cache = htab_create_alloc (1, hash_bfd, eq_bfd, NULL,
131                                        xcalloc, xfree);
132
133   if (fd == -1)
134     {
135       fd = open (name, O_RDONLY | O_BINARY);
136       if (fd == -1)
137         {
138           bfd_set_error (bfd_error_system_call);
139           return NULL;
140         }
141     }
142
143   search.filename = name;
144   if (fstat (fd, &st) < 0)
145     {
146       /* Weird situation here.  */
147       search.mtime = 0;
148     }
149   else
150     search.mtime = st.st_mtime;
151
152   /* Note that this must compute the same result as hash_bfd.  */
153   hash = htab_hash_string (name);
154   /* Note that we cannot use htab_find_slot_with_hash here, because
155      opening the BFD may fail; and this would violate hashtab
156      invariants.  */
157   abfd = htab_find_with_hash (gdb_bfd_cache, &search, hash);
158   if (abfd != NULL)
159     {
160       close (fd);
161       return gdb_bfd_ref (abfd);
162     }
163
164   abfd = bfd_fopen (name, target, FOPEN_RB, fd);
165   if (abfd == NULL)
166     return NULL;
167
168   slot = htab_find_slot_with_hash (gdb_bfd_cache, &search, hash, INSERT);
169   gdb_assert (!*slot);
170   *slot = abfd;
171
172   gdb_bfd_stash_filename (abfd);
173   return gdb_bfd_ref (abfd);
174 }
175
176 /* A helper function that releases any section data attached to the
177    BFD.  */
178
179 static void
180 free_one_bfd_section (bfd *abfd, asection *sectp, void *ignore)
181 {
182   struct gdb_bfd_section_data *sect = bfd_get_section_userdata (abfd, sectp);
183
184   if (sect != NULL && sect->data != NULL)
185     {
186 #ifdef HAVE_MMAP
187       if (sect->map_addr != NULL)
188         {
189           int res;
190
191           res = munmap (sect->map_addr, sect->map_len);
192           gdb_assert (res == 0);
193         }
194       else
195 #endif
196         xfree (sect->data);
197     }
198 }
199
200 /* Close ABFD, and warn if that fails.  */
201
202 static int
203 gdb_bfd_close_or_warn (struct bfd *abfd)
204 {
205   int ret;
206   char *name = bfd_get_filename (abfd);
207
208   bfd_map_over_sections (abfd, free_one_bfd_section, NULL);
209
210   ret = bfd_close (abfd);
211
212   if (!ret)
213     warning (_("cannot close \"%s\": %s"),
214              name, bfd_errmsg (bfd_get_error ()));
215
216   return ret;
217 }
218
219 /* Add reference to ABFD.  Returns ABFD.  */
220
221 struct bfd *
222 gdb_bfd_ref (struct bfd *abfd)
223 {
224   struct gdb_bfd_data *gdata;
225
226   if (abfd == NULL)
227     return NULL;
228
229   gdata = bfd_usrdata (abfd);
230
231   if (gdata != NULL)
232     {
233       gdata->refc += 1;
234       return abfd;
235     }
236
237   gdata = bfd_zalloc (abfd, sizeof (struct gdb_bfd_data));
238   gdata->refc = 1;
239   gdata->mtime = bfd_get_mtime (abfd);
240   bfd_usrdata (abfd) = gdata;
241
242   return abfd;
243 }
244
245 /* Unreference and possibly close ABFD.  */
246
247 void
248 gdb_bfd_unref (struct bfd *abfd)
249 {
250   struct gdb_bfd_data *gdata;
251   struct gdb_bfd_cache_search search;
252
253   if (abfd == NULL)
254     return;
255
256   gdata = bfd_usrdata (abfd);
257   gdb_assert (gdata->refc >= 1);
258
259   gdata->refc -= 1;
260   if (gdata->refc > 0)
261     return;
262
263   search.filename = bfd_get_filename (abfd);
264
265   if (gdb_bfd_cache && search.filename)
266     {
267       hashval_t hash = htab_hash_string (search.filename);
268       void **slot;
269
270       search.mtime = gdata->mtime;
271       slot = htab_find_slot_with_hash (gdb_bfd_cache, &search, hash,
272                                        NO_INSERT);
273
274       if (slot && *slot)
275         htab_clear_slot (gdb_bfd_cache, slot);
276     }
277
278   bfd_usrdata (abfd) = NULL;  /* Paranoia.  */
279
280   gdb_bfd_close_or_warn (abfd);
281 }
282
283 /* A helper function that returns the section data descriptor
284    associated with SECTION.  If no such descriptor exists, a new one
285    is allocated and cleared.  */
286
287 static struct gdb_bfd_section_data *
288 get_section_descriptor (asection *section)
289 {
290   struct gdb_bfd_section_data *result;
291
292   result = bfd_get_section_userdata (section->owner, section);
293
294   if (result == NULL)
295     {
296       result = bfd_zalloc (section->owner, sizeof (*result));
297       bfd_set_section_userdata (section->owner, section, result);
298     }
299
300   return result;
301 }
302
303 /* Decompress a section that was compressed using zlib.  Store the
304    decompressed buffer, and its size, in DESCRIPTOR.  */
305
306 static void
307 zlib_decompress_section (asection *sectp,
308                          struct gdb_bfd_section_data *descriptor)
309 {
310   bfd *abfd = sectp->owner;
311 #ifndef HAVE_ZLIB_H
312   error (_("Support for zlib-compressed data (from '%s', section '%s') "
313            "is disabled in this copy of GDB"),
314          bfd_get_filename (abfd),
315          bfd_get_section_name (sectp));
316 #else
317   bfd_size_type compressed_size = bfd_get_section_size (sectp);
318   gdb_byte *compressed_buffer = xmalloc (compressed_size);
319   struct cleanup *cleanup = make_cleanup (xfree, compressed_buffer);
320   struct cleanup *inner_cleanup;
321   bfd_size_type uncompressed_size;
322   gdb_byte *uncompressed_buffer;
323   z_stream strm;
324   int rc;
325   int header_size = 12;
326   struct dwarf2_per_bfd_section *section_data;
327
328   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
329       || bfd_bread (compressed_buffer,
330                     compressed_size, abfd) != compressed_size)
331     error (_("can't read data from '%s', section '%s'"),
332            bfd_get_filename (abfd),
333            bfd_get_section_name (abfd, sectp));
334
335   /* Read the zlib header.  In this case, it should be "ZLIB" followed
336      by the uncompressed section size, 8 bytes in big-endian order.  */
337   if (compressed_size < header_size
338       || strncmp (compressed_buffer, "ZLIB", 4) != 0)
339     error (_("corrupt ZLIB header from '%s', section '%s'"),
340            bfd_get_filename (abfd),
341            bfd_get_section_name (abfd, sectp));
342   uncompressed_size = compressed_buffer[4]; uncompressed_size <<= 8;
343   uncompressed_size += compressed_buffer[5]; uncompressed_size <<= 8;
344   uncompressed_size += compressed_buffer[6]; uncompressed_size <<= 8;
345   uncompressed_size += compressed_buffer[7]; uncompressed_size <<= 8;
346   uncompressed_size += compressed_buffer[8]; uncompressed_size <<= 8;
347   uncompressed_size += compressed_buffer[9]; uncompressed_size <<= 8;
348   uncompressed_size += compressed_buffer[10]; uncompressed_size <<= 8;
349   uncompressed_size += compressed_buffer[11];
350
351   /* It is possible the section consists of several compressed
352      buffers concatenated together, so we uncompress in a loop.  */
353   strm.zalloc = NULL;
354   strm.zfree = NULL;
355   strm.opaque = NULL;
356   strm.avail_in = compressed_size - header_size;
357   strm.next_in = (Bytef*) compressed_buffer + header_size;
358   strm.avail_out = uncompressed_size;
359   uncompressed_buffer = xmalloc (uncompressed_size);
360   inner_cleanup = make_cleanup (xfree, uncompressed_buffer);
361   rc = inflateInit (&strm);
362   while (strm.avail_in > 0)
363     {
364       if (rc != Z_OK)
365         error (_("setting up uncompression in '%s', section '%s': %d"),
366                bfd_get_filename (abfd),
367                bfd_get_section_name (abfd, sectp),
368                rc);
369       strm.next_out = ((Bytef*) uncompressed_buffer
370                        + (uncompressed_size - strm.avail_out));
371       rc = inflate (&strm, Z_FINISH);
372       if (rc != Z_STREAM_END)
373         error (_("zlib error uncompressing from '%s', section '%s': %d"),
374                bfd_get_filename (abfd),
375                bfd_get_section_name (abfd, sectp),
376                rc);
377       rc = inflateReset (&strm);
378     }
379   rc = inflateEnd (&strm);
380   if (rc != Z_OK
381       || strm.avail_out != 0)
382     error (_("concluding uncompression in '%s', section '%s': %d"),
383            bfd_get_filename (abfd),
384            bfd_get_section_name (abfd, sectp),
385            rc);
386
387   discard_cleanups (inner_cleanup);
388   do_cleanups (cleanup);
389
390   /* Attach the data to the BFD section.  */
391   descriptor->data = uncompressed_buffer;
392   descriptor->size = uncompressed_size;
393 #endif
394 }
395
396 /* See gdb_bfd.h.  */
397
398 const gdb_byte *
399 gdb_bfd_map_section (asection *sectp, bfd_size_type *size)
400 {
401   bfd *abfd;
402   gdb_byte *buf, *retbuf;
403   unsigned char header[4];
404   struct gdb_bfd_section_data *descriptor;
405
406   gdb_assert ((sectp->flags & SEC_RELOC) == 0);
407   gdb_assert (size != NULL);
408
409   abfd = sectp->owner;
410
411   descriptor = get_section_descriptor (sectp);
412
413   /* If the data was already read for this BFD, just reuse it.  */
414   if (descriptor->data != NULL)
415     goto done;
416
417   /* Check if the file has a 4-byte header indicating compression.  */
418   if (bfd_get_section_size (sectp) > sizeof (header)
419       && bfd_seek (abfd, sectp->filepos, SEEK_SET) == 0
420       && bfd_bread (header, sizeof (header), abfd) == sizeof (header))
421     {
422       /* Upon decompression, update the buffer and its size.  */
423       if (strncmp (header, "ZLIB", sizeof (header)) == 0)
424         {
425           zlib_decompress_section (sectp, descriptor);
426           goto done;
427         }
428     }
429
430 #ifdef HAVE_MMAP
431   {
432     /* The page size, used when mmapping.  */
433     static int pagesize;
434
435     if (pagesize == 0)
436       pagesize = getpagesize ();
437
438     /* Only try to mmap sections which are large enough: we don't want
439        to waste space due to fragmentation.  */
440
441     if (bfd_get_section_size (sectp) > 4 * pagesize)
442       {
443         descriptor->size = bfd_get_section_size (sectp);
444         descriptor->data = bfd_mmap (abfd, 0, descriptor->size, PROT_READ,
445                                      MAP_PRIVATE, sectp->filepos,
446                                      &descriptor->map_addr,
447                                      &descriptor->map_len);
448
449         if ((caddr_t)descriptor->data != MAP_FAILED)
450           {
451 #if HAVE_POSIX_MADVISE
452             posix_madvise (descriptor->map_addr, descriptor->map_len,
453                            POSIX_MADV_WILLNEED);
454 #endif
455             goto done;
456           }
457
458         /* On failure, clear out the section data and try again.  */
459         memset (descriptor, 0, sizeof (*descriptor));
460       }
461   }
462 #endif /* HAVE_MMAP */
463
464   /* If we get here, we are a normal, not-compressed section.  */
465
466   descriptor->size = bfd_get_section_size (sectp);
467   descriptor->data = xmalloc (descriptor->size);
468
469   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
470       || bfd_bread (descriptor->data, bfd_get_section_size (sectp),
471                     abfd) != bfd_get_section_size (sectp))
472     {
473       xfree (descriptor->data);
474       descriptor->data = NULL;
475       error (_("Can't read data for section '%s'"),
476              bfd_get_filename (abfd));
477     }
478
479  done:
480   gdb_assert (descriptor->data != NULL);
481   *size = descriptor->size;
482   return descriptor->data;
483 }