1 /* Definitions for BFD wrappers used by GDB.
2 
3    Copyright (C) 2011-2024 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 "gdb_bfd.h"
21 #include "event-top.h"
22 #include "ui-out.h"
23 #include "cli/cli-cmds.h"
24 #include "hashtab.h"
25 #include "gdbsupport/filestuff.h"
26 #ifdef HAVE_MMAP
27 #include <sys/mman.h>
28 #ifndef MAP_FAILED
29 #define MAP_FAILED ((void *) -1)
30 #endif
31 #endif
32 #include "target.h"
33 #include "gdbsupport/fileio.h"
34 #include "inferior.h"
35 #include "cli/cli-style.h"
36 #include <unordered_map>
37 
38 #if CXX_STD_THREAD
39 
40 #include <mutex>
41 
42 /* Lock held when doing BFD operations.  A recursive mutex is used
43    because we use this mutex internally and also for BFD, just to make
44    life a bit simpler, and we may sometimes hold it while calling into
45    BFD.  */
46 static std::recursive_mutex gdb_bfd_mutex;
47 
48 /* BFD locking function.  */
49 
50 static bool
gdb_bfd_lock(void * ignore)51 gdb_bfd_lock (void *ignore)
52 {
53   gdb_bfd_mutex.lock ();
54   return true;
55 }
56 
57 /* BFD unlocking function.  */
58 
59 static bool
gdb_bfd_unlock(void * ignore)60 gdb_bfd_unlock (void *ignore)
61 {
62   gdb_bfd_mutex.unlock ();
63   return true;
64 }
65 
66 #endif /* CXX_STD_THREAD */
67 
68 /* An object of this type is stored in the section's user data when
69    mapping a section.  */
70 
71 struct gdb_bfd_section_data
72 {
73   /* Size of the data.  */
74   size_t size;
75   /* If the data was mmapped, this is the length of the map.  */
76   size_t map_len;
77   /* The data.  If NULL, the section data has not been read.  */
78   void *data;
79   /* If the data was mmapped, this is the map address.  */
80   void *map_addr;
81 };
82 
83 /* A hash table holding every BFD that gdb knows about.  This is not
84    to be confused with 'gdb_bfd_cache', which is used for sharing
85    BFDs; in contrast, this hash is used just to implement
86    "maint info bfd".  */
87 
88 static htab_t all_bfds;
89 
90 /* An object of this type is stored in each BFD's user data.  */
91 
92 struct gdb_bfd_data
93 {
94   /* Note that if ST is nullptr, then we simply fill in zeroes.  */
gdb_bfd_datagdb_bfd_data95   gdb_bfd_data (bfd *abfd, struct stat *st)
96     : mtime (st == nullptr ? 0 : st->st_mtime),
97       size (st == nullptr ? 0 : st->st_size),
98       inode (st == nullptr ? 0 : st->st_ino),
99       device_id (st == nullptr ? 0 : st->st_dev),
100       relocation_computed (0),
101       needs_relocations (0),
102       crc_computed (0)
103   {
104   }
105 
~gdb_bfd_datagdb_bfd_data106   ~gdb_bfd_data ()
107   {
108   }
109 
110   /* The reference count.  */
111   int refc = 1;
112 
113   /* The mtime of the BFD at the point the cache entry was made.  */
114   time_t mtime;
115 
116   /* The file size (in bytes) at the point the cache entry was made.  */
117   off_t size;
118 
119   /* The inode of the file at the point the cache entry was made.  */
120   ino_t inode;
121 
122   /* The device id of the file at the point the cache entry was made.  */
123   dev_t device_id;
124 
125   /* This is true if we have determined whether this BFD has any
126      sections requiring relocation.  */
127   unsigned int relocation_computed : 1;
128 
129   /* This is true if any section needs relocation.  */
130   unsigned int needs_relocations : 1;
131 
132   /* This is true if we have successfully computed the file's CRC.  */
133   unsigned int crc_computed : 1;
134 
135   /* The file's CRC.  */
136   unsigned long crc = 0;
137 
138   /* If the BFD comes from an archive, this points to the archive's
139      BFD.  Otherwise, this is NULL.  */
140   bfd *archive_bfd = nullptr;
141 
142   /* Table of all the bfds this bfd has included.  */
143   std::vector<gdb_bfd_ref_ptr> included_bfds;
144 
145   /* The registry.  */
146   registry<bfd> registry_fields;
147 };
148 
149 registry<bfd> *
get(bfd * abfd)150 registry_accessor<bfd>::get (bfd *abfd)
151 {
152   struct gdb_bfd_data *gdata = (struct gdb_bfd_data *) bfd_usrdata (abfd);
153   return &gdata->registry_fields;
154 }
155 
156 /* A hash table storing all the BFDs maintained in the cache.  */
157 
158 static htab_t gdb_bfd_cache;
159 
160 /* When true gdb will reuse an existing bfd object if the filename,
161    modification time, and file size all match.  */
162 
163 static bool bfd_sharing = true;
164 static void
show_bfd_sharing(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)165 show_bfd_sharing  (struct ui_file *file, int from_tty,
166                        struct cmd_list_element *c, const char *value)
167 {
168   gdb_printf (file, _("BFD sharing is %s.\n"), value);
169 }
170 
171 /* When true debugging of the bfd caches is enabled.  */
172 
173 static bool debug_bfd_cache;
174 
175 /* Print an "bfd-cache" debug statement.  */
176 
177 #define bfd_cache_debug_printf(fmt, ...) \
178   debug_prefixed_printf_cond (debug_bfd_cache, "bfd-cache", fmt, ##__VA_ARGS__)
179 
180 static void
show_bfd_cache_debug(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)181 show_bfd_cache_debug (struct ui_file *file, int from_tty,
182                           struct cmd_list_element *c, const char *value)
183 {
184   gdb_printf (file, _("BFD cache debugging is %s.\n"), value);
185 }
186 
187 /* The type of an object being looked up in gdb_bfd_cache.  We use
188    htab's capability of storing one kind of object (BFD in this case)
189    and using a different sort of object for searching.  */
190 
191 struct gdb_bfd_cache_search
192 {
193   /* The filename.  */
194   const char *filename;
195   /* The mtime.  */
196   time_t mtime;
197   /* The file size (in bytes).  */
198   off_t size;
199   /* The inode of the file.  */
200   ino_t inode;
201   /* The device id of the file.  */
202   dev_t device_id;
203 };
204 
205 /* A hash function for BFDs.  */
206 
207 static hashval_t
hash_bfd(const void * b)208 hash_bfd (const void *b)
209 {
210   const bfd *abfd = (const struct bfd *) b;
211 
212   /* It is simplest to just hash the filename.  */
213   return htab_hash_string (bfd_get_filename (abfd));
214 }
215 
216 /* An equality function for BFDs.  Note that this expects the caller
217    to search using struct gdb_bfd_cache_search only, not BFDs.  */
218 
219 static int
eq_bfd(const void * a,const void * b)220 eq_bfd (const void *a, const void *b)
221 {
222   const bfd *abfd = (const struct bfd *) a;
223   const struct gdb_bfd_cache_search *s
224     = (const struct gdb_bfd_cache_search *) b;
225   struct gdb_bfd_data *gdata = (struct gdb_bfd_data *) bfd_usrdata (abfd);
226 
227   return (gdata->mtime == s->mtime
228             && gdata->size == s->size
229             && gdata->inode == s->inode
230             && gdata->device_id == s->device_id
231             && strcmp (bfd_get_filename (abfd), s->filename) == 0);
232 }
233 
234 /* See gdb_bfd.h.  */
235 
236 int
is_target_filename(const char * name)237 is_target_filename (const char *name)
238 {
239   return startswith (name, TARGET_SYSROOT_PREFIX);
240 }
241 
242 /* See gdb_bfd.h.  */
243 
244 int
gdb_bfd_has_target_filename(struct bfd * abfd)245 gdb_bfd_has_target_filename (struct bfd *abfd)
246 {
247   return is_target_filename (bfd_get_filename (abfd));
248 }
249 
250 /* For `gdb_bfd_open_from_target_memory`.  An object that manages the
251    details of a BFD in target memory.  */
252 
253 struct target_buffer : public gdb_bfd_iovec_base
254 {
255   /* Constructor.  BASE and SIZE define where the BFD can be found in
256      target memory.  */
target_buffertarget_buffer257   target_buffer (CORE_ADDR base, ULONGEST size)
258     : m_base (base),
259       m_size (size),
260       m_filename (xstrprintf ("<in-memory@%s-%s>",
261                                     core_addr_to_string_nz (m_base),
262                                     core_addr_to_string_nz (m_base + m_size)))
263   {
264   }
265 
266   /* Return the size of the in-memory BFD file.  */
sizetarget_buffer267   ULONGEST size () const
268   { return m_size; }
269 
270   /* Return the base address of the in-memory BFD file.  */
basetarget_buffer271   CORE_ADDR base () const
272   { return m_base; }
273 
274   /* Return a generated filename for the in-memory BFD file.  The generated
275      name will include the begin and end address of the in-memory file.  */
filenametarget_buffer276   const char *filename () const
277   { return m_filename.get (); }
278 
279   file_ptr read (bfd *abfd, void *buffer, file_ptr nbytes,
280                      file_ptr offset) override;
281 
282   int stat (struct bfd *abfd, struct stat *sb) override;
283 
284 private:
285   /* The base address of the in-memory BFD file.  */
286   CORE_ADDR m_base;
287 
288   /* The size (in-bytes) of the in-memory BFD file.  */
289   ULONGEST m_size;
290 
291   /* Holds the generated name of the in-memory BFD file.  */
292   gdb::unique_xmalloc_ptr<char> m_filename;
293 };
294 
295 /* For `gdb_bfd_open_from_target_memory`.  For reading the file, we just need to
296    pass through to target_read_memory and fix up the arguments and return
297    values.  */
298 
299 file_ptr
read(struct bfd * abfd,void * buf,file_ptr nbytes,file_ptr offset)300 target_buffer::read (struct bfd *abfd, void *buf,
301                          file_ptr nbytes, file_ptr offset)
302 {
303   /* If this read will read all of the file, limit it to just the rest.  */
304   if (offset + nbytes > size ())
305     nbytes = size () - offset;
306 
307   /* If there are no more bytes left, we've reached EOF.  */
308   if (nbytes == 0)
309     return 0;
310 
311   int err = target_read_memory (base () + offset, (gdb_byte *) buf, nbytes);
312   if (err)
313     return -1;
314 
315   return nbytes;
316 }
317 
318 /* For `gdb_bfd_open_from_target_memory`.  For statting the file, we only
319    support the st_size attribute.  */
320 
321 int
stat(struct bfd * abfd,struct stat * sb)322 target_buffer::stat (struct bfd *abfd, struct stat *sb)
323 {
324   memset (sb, 0, sizeof (struct stat));
325   sb->st_size = size ();
326   return 0;
327 }
328 
329 /* See gdb_bfd.h.  */
330 
331 gdb_bfd_ref_ptr
gdb_bfd_open_from_target_memory(CORE_ADDR addr,ULONGEST size,const char * target)332 gdb_bfd_open_from_target_memory (CORE_ADDR addr, ULONGEST size,
333                                          const char *target)
334 {
335   std::unique_ptr<target_buffer> buffer
336     = std::make_unique<target_buffer> (addr, size);
337 
338   return gdb_bfd_openr_iovec (buffer->filename (), target,
339                                     [&] (bfd *nbfd)
340                                     {
341                                         return buffer.release ();
342                                     });
343 }
344 
345 /* An object that manages the underlying stream for a BFD, using
346    target file I/O.  */
347 
348 struct target_fileio_stream : public gdb_bfd_iovec_base
349 {
target_fileio_streamtarget_fileio_stream350   target_fileio_stream (bfd *nbfd, int fd)
351     : m_bfd (nbfd),
352       m_fd (fd)
353   {
354   }
355 
356   ~target_fileio_stream ();
357 
358   file_ptr read (bfd *abfd, void *buffer, file_ptr nbytes,
359                      file_ptr offset) override;
360 
361   int stat (struct bfd *abfd, struct stat *sb) override;
362 
363 private:
364 
365   /* The BFD.  Saved for the destructor.  */
366   bfd *m_bfd;
367 
368   /* The file descriptor.  */
369   int m_fd;
370 };
371 
372 /* Wrapper for target_fileio_open suitable for use as a helper
373    function for gdb_bfd_openr_iovec.  */
374 
375 static target_fileio_stream *
gdb_bfd_iovec_fileio_open(struct bfd * abfd,inferior * inf,bool warn_if_slow)376 gdb_bfd_iovec_fileio_open (struct bfd *abfd, inferior *inf, bool warn_if_slow)
377 {
378   const char *filename = bfd_get_filename (abfd);
379   int fd;
380   fileio_error target_errno;
381 
382   gdb_assert (is_target_filename (filename));
383 
384   fd = target_fileio_open (inf,
385                                  filename + strlen (TARGET_SYSROOT_PREFIX),
386                                  FILEIO_O_RDONLY, 0, warn_if_slow,
387                                  &target_errno);
388   if (fd == -1)
389     {
390       errno = fileio_error_to_host (target_errno);
391       bfd_set_error (bfd_error_system_call);
392       return NULL;
393     }
394 
395   return new target_fileio_stream (abfd, fd);
396 }
397 
398 /* Wrapper for target_fileio_pread.  */
399 
400 file_ptr
read(struct bfd * abfd,void * buf,file_ptr nbytes,file_ptr offset)401 target_fileio_stream::read (struct bfd *abfd, void *buf,
402                                   file_ptr nbytes, file_ptr offset)
403 {
404   fileio_error target_errno;
405   file_ptr pos, bytes;
406 
407   pos = 0;
408   while (nbytes > pos)
409     {
410       QUIT;
411 
412       bytes = target_fileio_pread (m_fd, (gdb_byte *) buf + pos,
413                                            nbytes - pos, offset + pos,
414                                            &target_errno);
415       if (bytes == 0)
416           /* Success, but no bytes, means end-of-file.  */
417           break;
418       if (bytes == -1)
419           {
420             errno = fileio_error_to_host (target_errno);
421             bfd_set_error (bfd_error_system_call);
422             return -1;
423           }
424 
425       pos += bytes;
426     }
427 
428   return pos;
429 }
430 
431 /* Warn that it wasn't possible to close a bfd for file NAME, because
432    of REASON.  */
433 
434 static void
gdb_bfd_close_warning(const char * name,const char * reason)435 gdb_bfd_close_warning (const char *name, const char *reason)
436 {
437   warning (_("cannot close \"%s\": %s"), name, reason);
438 }
439 
440 /* Wrapper for target_fileio_close.  */
441 
~target_fileio_stream()442 target_fileio_stream::~target_fileio_stream ()
443 {
444   fileio_error target_errno;
445 
446   /* Ignore errors on close.  These may happen with remote
447      targets if the connection has already been torn down.  */
448   try
449     {
450       target_fileio_close (m_fd, &target_errno);
451     }
452   catch (const gdb_exception &ex)
453     {
454       /* Also avoid crossing exceptions over bfd.  */
455       gdb_bfd_close_warning (bfd_get_filename (m_bfd),
456                                    ex.message->c_str ());
457     }
458 }
459 
460 /* Wrapper for target_fileio_fstat.  */
461 
462 int
stat(struct bfd * abfd,struct stat * sb)463 target_fileio_stream::stat (struct bfd *abfd, struct stat *sb)
464 {
465   fileio_error target_errno;
466   int result;
467 
468   result = target_fileio_fstat (m_fd, sb, &target_errno);
469   if (result == -1)
470     {
471       errno = fileio_error_to_host (target_errno);
472       bfd_set_error (bfd_error_system_call);
473     }
474 
475   return result;
476 }
477 
478 /* A helper function to initialize the data that gdb attaches to each
479    BFD.  */
480 
481 static void
gdb_bfd_init_data(struct bfd * abfd,struct stat * st)482 gdb_bfd_init_data (struct bfd *abfd, struct stat *st)
483 {
484   struct gdb_bfd_data *gdata;
485   void **slot;
486 
487   gdb_assert (bfd_usrdata (abfd) == nullptr);
488 
489   /* Ask BFD to decompress sections in bfd_get_full_section_contents.  */
490   abfd->flags |= BFD_DECOMPRESS;
491 
492   gdata = new gdb_bfd_data (abfd, st);
493   bfd_set_usrdata (abfd, gdata);
494 
495   /* This is the first we've seen it, so add it to the hash table.  */
496   slot = htab_find_slot (all_bfds, abfd, INSERT);
497   gdb_assert (slot && !*slot);
498   *slot = abfd;
499 }
500 
501 /* See gdb_bfd.h.  */
502 
503 gdb_bfd_ref_ptr
gdb_bfd_open(const char * name,const char * target,int fd,bool warn_if_slow)504 gdb_bfd_open (const char *name, const char *target, int fd,
505                 bool warn_if_slow)
506 {
507   hashval_t hash;
508   void **slot;
509   bfd *abfd;
510   struct gdb_bfd_cache_search search;
511   struct stat st;
512 
513   if (is_target_filename (name))
514     {
515       if (!target_filesystem_is_local ())
516           {
517             gdb_assert (fd == -1);
518 
519             auto open = [&] (bfd *nbfd) -> gdb_bfd_iovec_base *
520             {
521               return gdb_bfd_iovec_fileio_open (nbfd, current_inferior (),
522                                                         warn_if_slow);
523             };
524 
525             return gdb_bfd_openr_iovec (name, target, open);
526           }
527 
528       name += strlen (TARGET_SYSROOT_PREFIX);
529     }
530 
531 #if CXX_STD_THREAD
532   std::lock_guard<std::recursive_mutex> guard (gdb_bfd_mutex);
533 #endif
534 
535   if (gdb_bfd_cache == NULL)
536     gdb_bfd_cache = htab_create_alloc (1, hash_bfd, eq_bfd, NULL,
537                                                xcalloc, xfree);
538 
539   if (fd == -1)
540     {
541       fd = gdb_open_cloexec (name, O_RDONLY | O_BINARY, 0).release ();
542       if (fd == -1)
543           {
544             bfd_set_error (bfd_error_system_call);
545             return NULL;
546           }
547     }
548 
549   if (fstat (fd, &st) < 0)
550     {
551       /* Weird situation here -- don't cache if we can't stat.  */
552       bfd_cache_debug_printf ("Could not stat %s - not caching", name);
553       abfd = bfd_fopen (name, target, FOPEN_RB, fd);
554       if (abfd == nullptr)
555           return nullptr;
556       return gdb_bfd_ref_ptr::new_reference (abfd);
557     }
558 
559   search.filename = name;
560   search.mtime = st.st_mtime;
561   search.size = st.st_size;
562   search.inode = st.st_ino;
563   search.device_id = st.st_dev;
564 
565   /* Note that this must compute the same result as hash_bfd.  */
566   hash = htab_hash_string (name);
567   /* Note that we cannot use htab_find_slot_with_hash here, because
568      opening the BFD may fail; and this would violate hashtab
569      invariants.  */
570   abfd = (struct bfd *) htab_find_with_hash (gdb_bfd_cache, &search, hash);
571   if (bfd_sharing && abfd != NULL)
572     {
573       bfd_cache_debug_printf ("Reusing cached bfd %s for %s",
574                                     host_address_to_string (abfd),
575                                     bfd_get_filename (abfd));
576       close (fd);
577       return gdb_bfd_ref_ptr::new_reference (abfd);
578     }
579 
580   abfd = bfd_fopen (name, target, FOPEN_RB, fd);
581   if (abfd == NULL)
582     return NULL;
583 
584   bfd_set_cacheable (abfd, 1);
585 
586   bfd_cache_debug_printf ("Creating new bfd %s for %s",
587                                 host_address_to_string (abfd),
588                                 bfd_get_filename (abfd));
589 
590   if (bfd_sharing)
591     {
592       slot = htab_find_slot_with_hash (gdb_bfd_cache, &search, hash, INSERT);
593       gdb_assert (!*slot);
594       *slot = abfd;
595     }
596 
597   /* It's important to pass the already-computed stat info here,
598      rather than, say, calling gdb_bfd_ref_ptr::new_reference.  BFD by
599      default will "stat" the file each time bfd_get_mtime is called --
600      and since we already entered it into the hash table using this
601      mtime, if the file changed at the wrong moment, the race would
602      lead to a hash table corruption.  */
603   gdb_bfd_init_data (abfd, &st);
604   return gdb_bfd_ref_ptr (abfd);
605 }
606 
607 /* A helper function that releases any section data attached to the
608    BFD.  */
609 
610 static void
free_one_bfd_section(asection * sectp)611 free_one_bfd_section (asection *sectp)
612 {
613   struct gdb_bfd_section_data *sect
614     = (struct gdb_bfd_section_data *) bfd_section_userdata (sectp);
615 
616   if (sect != NULL && sect->data != NULL)
617     {
618 #ifdef HAVE_MMAP
619       if (sect->map_addr != NULL)
620           {
621             int res;
622 
623             res = munmap (sect->map_addr, sect->map_len);
624             gdb_assert (res == 0);
625           }
626       else
627 #endif
628           xfree (sect->data);
629     }
630 }
631 
632 /* Close ABFD, and warn if that fails.  */
633 
634 static int
gdb_bfd_close_or_warn(struct bfd * abfd)635 gdb_bfd_close_or_warn (struct bfd *abfd)
636 {
637   int ret;
638   const char *name = bfd_get_filename (abfd);
639 
640   for (asection *sect : gdb_bfd_sections (abfd))
641     free_one_bfd_section (sect);
642 
643   ret = bfd_close (abfd);
644 
645   if (!ret)
646     gdb_bfd_close_warning (name,
647                                  bfd_errmsg (bfd_get_error ()));
648 
649   return ret;
650 }
651 
652 /* See gdb_bfd.h.  */
653 
654 void
gdb_bfd_ref(struct bfd * abfd)655 gdb_bfd_ref (struct bfd *abfd)
656 {
657   struct gdb_bfd_data *gdata;
658 
659   if (abfd == NULL)
660     return;
661 
662 #if CXX_STD_THREAD
663   std::lock_guard<std::recursive_mutex> guard (gdb_bfd_mutex);
664 #endif
665 
666   gdata = (struct gdb_bfd_data *) bfd_usrdata (abfd);
667 
668   bfd_cache_debug_printf ("Increase reference count on bfd %s (%s)",
669                                 host_address_to_string (abfd),
670                                 bfd_get_filename (abfd));
671 
672   if (gdata != NULL)
673     {
674       gdata->refc += 1;
675       return;
676     }
677 
678   /* Caching only happens via gdb_bfd_open, so passing nullptr here is
679      fine.  */
680   gdb_bfd_init_data (abfd, nullptr);
681 }
682 
683 /* See gdb_bfd.h.  */
684 
685 void
gdb_bfd_unref(struct bfd * abfd)686 gdb_bfd_unref (struct bfd *abfd)
687 {
688   struct gdb_bfd_data *gdata;
689   struct gdb_bfd_cache_search search;
690   bfd *archive_bfd;
691 
692   if (abfd == NULL)
693     return;
694 
695 #if CXX_STD_THREAD
696   std::lock_guard<std::recursive_mutex> guard (gdb_bfd_mutex);
697 #endif
698 
699   gdata = (struct gdb_bfd_data *) bfd_usrdata (abfd);
700   gdb_assert (gdata->refc >= 1);
701 
702   gdata->refc -= 1;
703   if (gdata->refc > 0)
704     {
705       bfd_cache_debug_printf ("Decrease reference count on bfd %s (%s)",
706                                     host_address_to_string (abfd),
707                                     bfd_get_filename (abfd));
708       return;
709     }
710 
711   bfd_cache_debug_printf ("Delete final reference count on bfd %s (%s)",
712                                 host_address_to_string (abfd),
713                                 bfd_get_filename (abfd));
714 
715   archive_bfd = gdata->archive_bfd;
716   search.filename = bfd_get_filename (abfd);
717 
718   if (gdb_bfd_cache && search.filename)
719     {
720       hashval_t hash = htab_hash_string (search.filename);
721       void **slot;
722 
723       search.mtime = gdata->mtime;
724       search.size = gdata->size;
725       search.inode = gdata->inode;
726       search.device_id = gdata->device_id;
727       slot = htab_find_slot_with_hash (gdb_bfd_cache, &search, hash,
728                                                NO_INSERT);
729 
730       if (slot && *slot)
731           htab_clear_slot (gdb_bfd_cache, slot);
732     }
733 
734   delete gdata;
735   bfd_set_usrdata (abfd, NULL);  /* Paranoia.  */
736 
737   htab_remove_elt (all_bfds, abfd);
738 
739   gdb_bfd_close_or_warn (abfd);
740 
741   gdb_bfd_unref (archive_bfd);
742 }
743 
744 /* A helper function that returns the section data descriptor
745    associated with SECTION.  If no such descriptor exists, a new one
746    is allocated and cleared.  */
747 
748 static struct gdb_bfd_section_data *
get_section_descriptor(asection * section)749 get_section_descriptor (asection *section)
750 {
751   struct gdb_bfd_section_data *result;
752 
753   result = (struct gdb_bfd_section_data *) bfd_section_userdata (section);
754 
755   if (result == NULL)
756     {
757       result = ((struct gdb_bfd_section_data *)
758                     bfd_zalloc (section->owner, sizeof (*result)));
759       bfd_set_section_userdata (section, result);
760     }
761 
762   return result;
763 }
764 
765 /* See gdb_bfd.h.  */
766 
767 const gdb_byte *
gdb_bfd_map_section(asection * sectp,bfd_size_type * size)768 gdb_bfd_map_section (asection *sectp, bfd_size_type *size)
769 {
770   bfd *abfd;
771   struct gdb_bfd_section_data *descriptor;
772   bfd_byte *data;
773 
774   gdb_assert ((sectp->flags & SEC_RELOC) == 0);
775   gdb_assert (size != NULL);
776 
777   abfd = sectp->owner;
778 
779   descriptor = get_section_descriptor (sectp);
780 
781   /* If the data was already read for this BFD, just reuse it.  */
782   if (descriptor->data != NULL)
783     goto done;
784 
785 #ifdef HAVE_MMAP
786   if (!bfd_is_section_compressed (abfd, sectp))
787     {
788       /* The page size, used when mmapping.  */
789       static int pagesize;
790 
791       if (pagesize == 0)
792           pagesize = getpagesize ();
793 
794       /* Only try to mmap sections which are large enough: we don't want
795            to waste space due to fragmentation.  */
796 
797       if (bfd_section_size (sectp) > 4 * pagesize)
798           {
799             descriptor->size = bfd_section_size (sectp);
800             descriptor->data = bfd_mmap (abfd, 0, descriptor->size, PROT_READ,
801                                                MAP_PRIVATE, sectp->filepos,
802                                                &descriptor->map_addr,
803                                                &descriptor->map_len);
804 
805             if ((caddr_t)descriptor->data != MAP_FAILED)
806               {
807 #if HAVE_POSIX_MADVISE
808                 posix_madvise (descriptor->map_addr, descriptor->map_len,
809                                    POSIX_MADV_WILLNEED);
810 #endif
811                 goto done;
812               }
813 
814             /* On failure, clear out the section data and try again.  */
815             memset (descriptor, 0, sizeof (*descriptor));
816           }
817     }
818 #endif /* HAVE_MMAP */
819 
820   /* Handle compressed sections, or ordinary uncompressed sections in
821      the no-mmap case.  */
822 
823   descriptor->size = bfd_section_size (sectp);
824   descriptor->data = NULL;
825 
826   data = NULL;
827   if (!bfd_get_full_section_contents (abfd, sectp, &data))
828     {
829       warning (_("Can't read data for section '%s' in file '%s'"),
830                  bfd_section_name (sectp),
831                  bfd_get_filename (abfd));
832       /* Set size to 0 to prevent further attempts to read the invalid
833            section.  */
834       *size = 0;
835       return NULL;
836     }
837   descriptor->data = data;
838 
839  done:
840   gdb_assert (descriptor->data != NULL);
841   *size = descriptor->size;
842   return (const gdb_byte *) descriptor->data;
843 }
844 
845 /* Return 32-bit CRC for ABFD.  If successful store it to *FILE_CRC_RETURN and
846    return 1.  Otherwise print a warning and return 0.  ABFD seek position is
847    not preserved.  */
848 
849 static int
get_file_crc(bfd * abfd,unsigned long * file_crc_return)850 get_file_crc (bfd *abfd, unsigned long *file_crc_return)
851 {
852   uint32_t file_crc = 0;
853 
854   if (bfd_seek (abfd, 0, SEEK_SET) != 0)
855     {
856       warning (_("Problem reading \"%s\" for CRC: %s"),
857                  bfd_get_filename (abfd), bfd_errmsg (bfd_get_error ()));
858       return 0;
859     }
860 
861   for (;;)
862     {
863       gdb_byte buffer[8 * 1024];
864       bfd_size_type count;
865 
866       count = bfd_read (buffer, sizeof (buffer), abfd);
867       if (count == (bfd_size_type) -1)
868           {
869             warning (_("Problem reading \"%s\" for CRC: %s"),
870                        bfd_get_filename (abfd), bfd_errmsg (bfd_get_error ()));
871             return 0;
872           }
873       if (count == 0)
874           break;
875       file_crc = bfd_calc_gnu_debuglink_crc32 (file_crc, buffer, count);
876     }
877 
878   *file_crc_return = file_crc;
879   return 1;
880 }
881 
882 /* See gdb_bfd.h.  */
883 
884 int
gdb_bfd_crc(struct bfd * abfd,unsigned long * crc_out)885 gdb_bfd_crc (struct bfd *abfd, unsigned long *crc_out)
886 {
887   struct gdb_bfd_data *gdata = (struct gdb_bfd_data *) bfd_usrdata (abfd);
888 
889   if (!gdata->crc_computed)
890     gdata->crc_computed = get_file_crc (abfd, &gdata->crc);
891 
892   if (gdata->crc_computed)
893     *crc_out = gdata->crc;
894   return gdata->crc_computed;
895 }
896 
897 
898 
899 /* See gdb_bfd.h.  */
900 
901 gdb_bfd_ref_ptr
gdb_bfd_fopen(const char * filename,const char * target,const char * mode,int fd)902 gdb_bfd_fopen (const char *filename, const char *target, const char *mode,
903                  int fd)
904 {
905   bfd *result = bfd_fopen (filename, target, mode, fd);
906 
907   if (result != nullptr)
908     bfd_set_cacheable (result, 1);
909 
910   return gdb_bfd_ref_ptr::new_reference (result);
911 }
912 
913 /* See gdb_bfd.h.  */
914 
915 gdb_bfd_ref_ptr
gdb_bfd_openr(const char * filename,const char * target)916 gdb_bfd_openr (const char *filename, const char *target)
917 {
918   bfd *result = bfd_openr (filename, target);
919 
920   return gdb_bfd_ref_ptr::new_reference (result);
921 }
922 
923 /* See gdb_bfd.h.  */
924 
925 gdb_bfd_ref_ptr
gdb_bfd_openw(const char * filename,const char * target)926 gdb_bfd_openw (const char *filename, const char *target)
927 {
928   bfd *result = bfd_openw (filename, target);
929 
930   return gdb_bfd_ref_ptr::new_reference (result);
931 }
932 
933 /* Wrap f (args) and handle exceptions by:
934    - returning val, and
935    - calling set_quit_flag or set_force_quit_flag, if needed.  */
936 
937 template <typename R, R val, typename F, typename... Args>
938 static R
catch_exceptions(F && f,Args &&...args)939 catch_exceptions (F &&f, Args&&... args)
940 {
941    try
942      {
943        return f (std::forward<Args> (args)...);
944      }
945    catch (const gdb_exception &ex)
946      {
947        if (ex.reason == RETURN_QUIT)
948            set_quit_flag ();
949        else if (ex.reason == RETURN_FORCED_QUIT)
950            set_force_quit_flag ();
951      }
952 
953    return val;
954 }
955 
956 /* See gdb_bfd.h.  */
957 
958 gdb_bfd_ref_ptr
gdb_bfd_openr_iovec(const char * filename,const char * target,gdb_iovec_opener_ftype open_fn)959 gdb_bfd_openr_iovec (const char *filename, const char *target,
960                          gdb_iovec_opener_ftype open_fn)
961 {
962   auto do_open = [] (bfd *nbfd, void *closure) -> void *
963   {
964     auto real_opener = static_cast<gdb_iovec_opener_ftype *> (closure);
965     /* Prevent exceptions from escaping to C code and triggering an abort.  */
966     auto res = catch_exceptions<gdb_bfd_iovec_base *, nullptr> ([&]
967       {
968           return (*real_opener) (nbfd);
969       });
970     if (res == nullptr)
971       {
972           errno = EIO;
973           bfd_set_error (bfd_error_system_call);
974       }
975       return res;
976   };
977 
978   auto read_trampoline = [] (bfd *nbfd, void *stream, void *buf,
979                                    file_ptr nbytes, file_ptr offset) -> file_ptr
980   {
981     gdb_bfd_iovec_base *obj = static_cast<gdb_bfd_iovec_base *> (stream);
982     /* Prevent exceptions from escaping to C code and triggering an abort.  */
983     auto res = catch_exceptions<long int, -1> ([&]
984       {
985           return obj->read (nbfd, buf, nbytes, offset);
986       });
987     if (res == -1)
988       {
989           errno = EIO;
990           bfd_set_error (bfd_error_system_call);
991       }
992     return res;
993   };
994 
995   auto stat_trampoline = [] (struct bfd *abfd, void *stream,
996                                    struct stat *sb) -> int
997   {
998     gdb_bfd_iovec_base *obj = static_cast<gdb_bfd_iovec_base *> (stream);
999     /* Prevent exceptions from escaping to C code and triggering an abort.  */
1000     auto res = catch_exceptions<int, -1> ([&]
1001       {
1002           return obj->stat (abfd, sb);
1003       });
1004     if (res == -1)
1005       {
1006           errno = EIO;
1007           bfd_set_error (bfd_error_system_call);
1008       }
1009     return res;
1010   };
1011 
1012   auto close_trampoline = [] (struct bfd *nbfd, void *stream) -> int
1013   {
1014     gdb_bfd_iovec_base *obj = static_cast<gdb_bfd_iovec_base *> (stream);
1015     delete obj;
1016     /* Success.  */
1017     return 0;
1018   };
1019 
1020   bfd *result = bfd_openr_iovec (filename, target,
1021                                          do_open, &open_fn,
1022                                          read_trampoline, close_trampoline,
1023                                          stat_trampoline);
1024 
1025   return gdb_bfd_ref_ptr::new_reference (result);
1026 }
1027 
1028 /* See gdb_bfd.h.  */
1029 
1030 void
gdb_bfd_mark_parent(bfd * child,bfd * parent)1031 gdb_bfd_mark_parent (bfd *child, bfd *parent)
1032 {
1033   struct gdb_bfd_data *gdata;
1034 
1035   gdb_bfd_ref (child);
1036   /* No need to stash the filename here, because we also keep a
1037      reference on the parent archive.  */
1038 
1039   gdata = (struct gdb_bfd_data *) bfd_usrdata (child);
1040   if (gdata->archive_bfd == NULL)
1041     {
1042       gdata->archive_bfd = parent;
1043       gdb_bfd_ref (parent);
1044     }
1045   else
1046     gdb_assert (gdata->archive_bfd == parent);
1047 }
1048 
1049 /* See gdb_bfd.h.  */
1050 
1051 gdb_bfd_ref_ptr
gdb_bfd_openr_next_archived_file(bfd * archive,bfd * previous)1052 gdb_bfd_openr_next_archived_file (bfd *archive, bfd *previous)
1053 {
1054   bfd *result = bfd_openr_next_archived_file (archive, previous);
1055 
1056   if (result)
1057     gdb_bfd_mark_parent (result, archive);
1058 
1059   return gdb_bfd_ref_ptr (result);
1060 }
1061 
1062 /* See gdb_bfd.h.  */
1063 
1064 void
gdb_bfd_record_inclusion(bfd * includer,bfd * includee)1065 gdb_bfd_record_inclusion (bfd *includer, bfd *includee)
1066 {
1067   struct gdb_bfd_data *gdata;
1068 
1069   gdata = (struct gdb_bfd_data *) bfd_usrdata (includer);
1070   gdata->included_bfds.push_back (gdb_bfd_ref_ptr::new_reference (includee));
1071 }
1072 
1073 
1074 
1075 static_assert (ARRAY_SIZE (_bfd_std_section) == 4);
1076 
1077 /* See gdb_bfd.h.  */
1078 
1079 int
gdb_bfd_section_index(bfd * abfd,asection * section)1080 gdb_bfd_section_index (bfd *abfd, asection *section)
1081 {
1082   if (section == NULL)
1083     return -1;
1084   else if (section == bfd_com_section_ptr)
1085     return bfd_count_sections (abfd);
1086   else if (section == bfd_und_section_ptr)
1087     return bfd_count_sections (abfd) + 1;
1088   else if (section == bfd_abs_section_ptr)
1089     return bfd_count_sections (abfd) + 2;
1090   else if (section == bfd_ind_section_ptr)
1091     return bfd_count_sections (abfd) + 3;
1092   return section->index;
1093 }
1094 
1095 /* See gdb_bfd.h.  */
1096 
1097 int
gdb_bfd_count_sections(bfd * abfd)1098 gdb_bfd_count_sections (bfd *abfd)
1099 {
1100   return bfd_count_sections (abfd) + 4;
1101 }
1102 
1103 /* See gdb_bfd.h.  */
1104 
1105 int
gdb_bfd_requires_relocations(bfd * abfd)1106 gdb_bfd_requires_relocations (bfd *abfd)
1107 {
1108   struct gdb_bfd_data *gdata = (struct gdb_bfd_data *) bfd_usrdata (abfd);
1109 
1110   if (gdata->relocation_computed == 0)
1111     {
1112       asection *sect;
1113 
1114       for (sect = abfd->sections; sect != NULL; sect = sect->next)
1115           if ((sect->flags & SEC_RELOC) != 0)
1116             {
1117               gdata->needs_relocations = 1;
1118               break;
1119             }
1120 
1121       gdata->relocation_computed = 1;
1122     }
1123 
1124   return gdata->needs_relocations;
1125 }
1126 
1127 /* See gdb_bfd.h.  */
1128 
1129 bool
gdb_bfd_get_full_section_contents(bfd * abfd,asection * section,gdb::byte_vector * contents)1130 gdb_bfd_get_full_section_contents (bfd *abfd, asection *section,
1131                                            gdb::byte_vector *contents)
1132 {
1133   bfd_size_type section_size = bfd_section_size (section);
1134 
1135   contents->resize (section_size);
1136 
1137   return bfd_get_section_contents (abfd, section, contents->data (), 0,
1138                                            section_size);
1139 }
1140 
1141 #define AMBIGUOUS_MESS1       ".\nMatching formats:"
1142 #define AMBIGUOUS_MESS2       \
1143   ".\nUse \"set gnutarget format-name\" to specify the format."
1144 
1145 /* See gdb_bfd.h.  */
1146 
1147 std::string
gdb_bfd_errmsg(bfd_error_type error_tag,char ** matching)1148 gdb_bfd_errmsg (bfd_error_type error_tag, char **matching)
1149 {
1150   char **p;
1151 
1152   /* Check if errmsg just need simple return.  */
1153   if (error_tag != bfd_error_file_ambiguously_recognized || matching == NULL)
1154     return bfd_errmsg (error_tag);
1155 
1156   std::string ret (bfd_errmsg (error_tag));
1157   ret += AMBIGUOUS_MESS1;
1158 
1159   for (p = matching; *p; p++)
1160     {
1161       ret += " ";
1162       ret += *p;
1163     }
1164   ret += AMBIGUOUS_MESS2;
1165 
1166   xfree (matching);
1167 
1168   return ret;
1169 }
1170 
1171 /* A callback for htab_traverse that prints a single BFD.  */
1172 
1173 static int
print_one_bfd(void ** slot,void * data)1174 print_one_bfd (void **slot, void *data)
1175 {
1176   bfd *abfd = (struct bfd *) *slot;
1177   struct gdb_bfd_data *gdata = (struct gdb_bfd_data *) bfd_usrdata (abfd);
1178   struct ui_out *uiout = (struct ui_out *) data;
1179 
1180   ui_out_emit_tuple tuple_emitter (uiout, NULL);
1181   uiout->field_signed ("refcount", gdata->refc);
1182   uiout->field_string ("addr", host_address_to_string (abfd));
1183   uiout->field_string ("filename", bfd_get_filename (abfd),
1184                            file_name_style.style ());
1185   uiout->text ("\n");
1186 
1187   return 1;
1188 }
1189 
1190 /* Implement the 'maint info bfd' command.  */
1191 
1192 static void
maintenance_info_bfds(const char * arg,int from_tty)1193 maintenance_info_bfds (const char *arg, int from_tty)
1194 {
1195   struct ui_out *uiout = current_uiout;
1196 
1197   ui_out_emit_table table_emitter (uiout, 3, -1, "bfds");
1198   uiout->table_header (10, ui_left, "refcount", "Refcount");
1199   uiout->table_header (18, ui_left, "addr", "Address");
1200   uiout->table_header (40, ui_left, "filename", "Filename");
1201 
1202   uiout->table_body ();
1203   htab_traverse (all_bfds, print_one_bfd, uiout);
1204 }
1205 
1206 /* BFD related per-inferior data.  */
1207 
1208 struct bfd_inferior_data
1209 {
1210   std::unordered_map<std::string, unsigned long> bfd_error_string_counts;
1211 };
1212 
1213 /* Per-inferior data key.  */
1214 
1215 static const registry<inferior>::key<bfd_inferior_data> bfd_inferior_data_key;
1216 
1217 /* Fetch per-inferior BFD data.  It always returns a valid pointer to
1218    a bfd_inferior_data struct.  */
1219 
1220 static struct bfd_inferior_data *
get_bfd_inferior_data(struct inferior * inf)1221 get_bfd_inferior_data (struct inferior *inf)
1222 {
1223   struct bfd_inferior_data *data;
1224 
1225   data = bfd_inferior_data_key.get (inf);
1226   if (data == nullptr)
1227     data = bfd_inferior_data_key.emplace (inf);
1228 
1229   return data;
1230 }
1231 
1232 /* Increment the BFD error count for STR and return the updated
1233    count.  */
1234 
1235 static unsigned long
increment_bfd_error_count(const std::string & str)1236 increment_bfd_error_count (const std::string &str)
1237 {
1238 #if CXX_STD_THREAD
1239   std::lock_guard<std::recursive_mutex> guard (gdb_bfd_mutex);
1240 #endif
1241   struct bfd_inferior_data *bid = get_bfd_inferior_data (current_inferior ());
1242 
1243   auto &map = bid->bfd_error_string_counts;
1244   return ++map[str];
1245 }
1246 
1247 /* A print callback for bfd_print_error.  */
1248 
1249 static int ATTRIBUTE_PRINTF (2, 0)
print_error_callback(void * stream,const char * fmt,...)1250 print_error_callback (void *stream, const char *fmt, ...)
1251 {
1252   string_file *file = (string_file *) stream;
1253   size_t in_size = file->size ();
1254   va_list ap;
1255   va_start (ap, fmt);
1256   file->vprintf (fmt, ap);
1257   va_end (ap);
1258   return file->size () - in_size;
1259 }
1260 
1261 /* Define a BFD error handler which will suppress the printing of
1262    messages which have been printed once already.  This is done on a
1263    per-inferior basis.  */
1264 
1265 static void
gdb_bfd_error_handler(const char * fmt,va_list ap)1266 gdb_bfd_error_handler (const char *fmt, va_list ap)
1267 {
1268   string_file output;
1269   bfd_print_error (print_error_callback, &output, fmt, ap);
1270   std::string str = output.release ();
1271 
1272   if (increment_bfd_error_count (str) > 1)
1273     return;
1274 
1275   warning ("%s", str.c_str ());
1276 }
1277 
1278 /* See gdb_bfd.h.  */
1279 
1280 void
gdb_bfd_init()1281 gdb_bfd_init ()
1282 {
1283   if (bfd_init () == BFD_INIT_MAGIC)
1284     {
1285 #if CXX_STD_THREAD
1286       if (bfd_thread_init (gdb_bfd_lock, gdb_bfd_unlock, nullptr))
1287 #endif
1288           return;
1289     }
1290 
1291   error (_("fatal error: libbfd ABI mismatch"));
1292 }
1293 
1294 void _initialize_gdb_bfd ();
1295 void
_initialize_gdb_bfd()1296 _initialize_gdb_bfd ()
1297 {
1298   all_bfds = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
1299                                         NULL, xcalloc, xfree);
1300 
1301   add_cmd ("bfds", class_maintenance, maintenance_info_bfds, _("\
1302 List the BFDs that are currently open."),
1303              &maintenanceinfolist);
1304 
1305   add_setshow_boolean_cmd ("bfd-sharing", no_class,
1306                                  &bfd_sharing, _("\
1307 Set whether gdb will share bfds that appear to be the same file."), _("\
1308 Show whether gdb will share bfds that appear to be the same file."), _("\
1309 When enabled gdb will reuse existing bfds rather than reopening the\n\
1310 same file.  To decide if two files are the same then gdb compares the\n\
1311 filename, file size, file modification time, and file inode."),
1312                                  NULL,
1313                                  &show_bfd_sharing,
1314                                  &maintenance_set_cmdlist,
1315                                  &maintenance_show_cmdlist);
1316 
1317   add_setshow_boolean_cmd ("bfd-cache", class_maintenance,
1318                                  &debug_bfd_cache,
1319                                  _("Set bfd cache debugging."),
1320                                  _("Show bfd cache debugging."),
1321                                  _("\
1322 When non-zero, bfd cache specific debugging is enabled."),
1323                                  NULL,
1324                                  &show_bfd_cache_debug,
1325                                  &setdebuglist, &showdebuglist);
1326 
1327   /* Hook the BFD error/warning handler to limit amount of output.  */
1328   bfd_set_error_handler (gdb_bfd_error_handler);
1329 }
1330