Fix null pointer dereference in process_debug_info()
[binutils-gdb.git] / gdb / gdb_bfd.c
blobffff76e54b720657f83d72287218f8e02b4141fd
1 /* Definitions for BFD wrappers used by GDB.
3 Copyright (C) 2011-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
20 #include "gdb_bfd.h"
21 #include "ui-out.h"
22 #include "gdbcmd.h"
23 #include "hashtab.h"
24 #include "gdbsupport/filestuff.h"
25 #ifdef HAVE_MMAP
26 #include <sys/mman.h>
27 #ifndef MAP_FAILED
28 #define MAP_FAILED ((void *) -1)
29 #endif
30 #endif
31 #include "target.h"
32 #include "gdbsupport/fileio.h"
33 #include "inferior.h"
34 #include "cli/cli-style.h"
35 #include <unordered_map>
37 #if CXX_STD_THREAD
39 #include <mutex>
41 /* Lock held when doing BFD operations. A recursive mutex is used
42 because we use this mutex internally and also for BFD, just to make
43 life a bit simpler, and we may sometimes hold it while calling into
44 BFD. */
45 static std::recursive_mutex gdb_bfd_mutex;
47 /* BFD locking function. */
49 static bool
50 gdb_bfd_lock (void *ignore)
52 gdb_bfd_mutex.lock ();
53 return true;
56 /* BFD unlocking function. */
58 static bool
59 gdb_bfd_unlock (void *ignore)
61 gdb_bfd_mutex.unlock ();
62 return true;
65 #endif /* CXX_STD_THREAD */
67 /* An object of this type is stored in the section's user data when
68 mapping a section. */
70 struct gdb_bfd_section_data
72 /* Size of the data. */
73 size_t size;
74 /* If the data was mmapped, this is the length of the map. */
75 size_t map_len;
76 /* The data. If NULL, the section data has not been read. */
77 void *data;
78 /* If the data was mmapped, this is the map address. */
79 void *map_addr;
82 /* A hash table holding every BFD that gdb knows about. This is not
83 to be confused with 'gdb_bfd_cache', which is used for sharing
84 BFDs; in contrast, this hash is used just to implement
85 "maint info bfd". */
87 static htab_t all_bfds;
89 /* An object of this type is stored in each BFD's user data. */
91 struct gdb_bfd_data
93 /* Note that if ST is nullptr, then we simply fill in zeroes. */
94 gdb_bfd_data (bfd *abfd, struct stat *st)
95 : mtime (st == nullptr ? 0 : st->st_mtime),
96 size (st == nullptr ? 0 : st->st_size),
97 inode (st == nullptr ? 0 : st->st_ino),
98 device_id (st == nullptr ? 0 : st->st_dev),
99 relocation_computed (0),
100 needs_relocations (0),
101 crc_computed (0)
105 ~gdb_bfd_data ()
109 /* The reference count. */
110 int refc = 1;
112 /* The mtime of the BFD at the point the cache entry was made. */
113 time_t mtime;
115 /* The file size (in bytes) at the point the cache entry was made. */
116 off_t size;
118 /* The inode of the file at the point the cache entry was made. */
119 ino_t inode;
121 /* The device id of the file at the point the cache entry was made. */
122 dev_t device_id;
124 /* This is true if we have determined whether this BFD has any
125 sections requiring relocation. */
126 unsigned int relocation_computed : 1;
128 /* This is true if any section needs relocation. */
129 unsigned int needs_relocations : 1;
131 /* This is true if we have successfully computed the file's CRC. */
132 unsigned int crc_computed : 1;
134 /* The file's CRC. */
135 unsigned long crc = 0;
137 /* If the BFD comes from an archive, this points to the archive's
138 BFD. Otherwise, this is NULL. */
139 bfd *archive_bfd = nullptr;
141 /* Table of all the bfds this bfd has included. */
142 std::vector<gdb_bfd_ref_ptr> included_bfds;
144 /* The registry. */
145 registry<bfd> registry_fields;
148 registry<bfd> *
149 registry_accessor<bfd>::get (bfd *abfd)
151 struct gdb_bfd_data *gdata = (struct gdb_bfd_data *) bfd_usrdata (abfd);
152 return &gdata->registry_fields;
155 /* A hash table storing all the BFDs maintained in the cache. */
157 static htab_t gdb_bfd_cache;
159 /* When true gdb will reuse an existing bfd object if the filename,
160 modification time, and file size all match. */
162 static bool bfd_sharing = true;
163 static void
164 show_bfd_sharing (struct ui_file *file, int from_tty,
165 struct cmd_list_element *c, const char *value)
167 gdb_printf (file, _("BFD sharing is %s.\n"), value);
170 /* When true debugging of the bfd caches is enabled. */
172 static bool debug_bfd_cache;
174 /* Print an "bfd-cache" debug statement. */
176 #define bfd_cache_debug_printf(fmt, ...) \
177 debug_prefixed_printf_cond (debug_bfd_cache, "bfd-cache", fmt, ##__VA_ARGS__)
179 static void
180 show_bfd_cache_debug (struct ui_file *file, int from_tty,
181 struct cmd_list_element *c, const char *value)
183 gdb_printf (file, _("BFD cache debugging is %s.\n"), value);
186 /* The type of an object being looked up in gdb_bfd_cache. We use
187 htab's capability of storing one kind of object (BFD in this case)
188 and using a different sort of object for searching. */
190 struct gdb_bfd_cache_search
192 /* The filename. */
193 const char *filename;
194 /* The mtime. */
195 time_t mtime;
196 /* The file size (in bytes). */
197 off_t size;
198 /* The inode of the file. */
199 ino_t inode;
200 /* The device id of the file. */
201 dev_t device_id;
204 /* A hash function for BFDs. */
206 static hashval_t
207 hash_bfd (const void *b)
209 const bfd *abfd = (const struct bfd *) b;
211 /* It is simplest to just hash the filename. */
212 return htab_hash_string (bfd_get_filename (abfd));
215 /* An equality function for BFDs. Note that this expects the caller
216 to search using struct gdb_bfd_cache_search only, not BFDs. */
218 static int
219 eq_bfd (const void *a, const void *b)
221 const bfd *abfd = (const struct bfd *) a;
222 const struct gdb_bfd_cache_search *s
223 = (const struct gdb_bfd_cache_search *) b;
224 struct gdb_bfd_data *gdata = (struct gdb_bfd_data *) bfd_usrdata (abfd);
226 return (gdata->mtime == s->mtime
227 && gdata->size == s->size
228 && gdata->inode == s->inode
229 && gdata->device_id == s->device_id
230 && strcmp (bfd_get_filename (abfd), s->filename) == 0);
233 /* See gdb_bfd.h. */
236 is_target_filename (const char *name)
238 return startswith (name, TARGET_SYSROOT_PREFIX);
241 /* See gdb_bfd.h. */
244 gdb_bfd_has_target_filename (struct bfd *abfd)
246 return is_target_filename (bfd_get_filename (abfd));
249 /* For `gdb_bfd_open_from_target_memory`. An object that manages the
250 details of a BFD in target memory. */
252 struct target_buffer : public gdb_bfd_iovec_base
254 /* Constructor. BASE and SIZE define where the BFD can be found in
255 target memory. */
256 target_buffer (CORE_ADDR base, ULONGEST size)
257 : m_base (base),
258 m_size (size),
259 m_filename (xstrprintf ("<in-memory@%s-%s>",
260 core_addr_to_string_nz (m_base),
261 core_addr_to_string_nz (m_base + m_size)))
265 /* Return the size of the in-memory BFD file. */
266 ULONGEST size () const
267 { return m_size; }
269 /* Return the base address of the in-memory BFD file. */
270 CORE_ADDR base () const
271 { return m_base; }
273 /* Return a generated filename for the in-memory BFD file. The generated
274 name will include the begin and end address of the in-memory file. */
275 const char *filename () const
276 { return m_filename.get (); }
278 file_ptr read (bfd *abfd, void *buffer, file_ptr nbytes,
279 file_ptr offset) override;
281 int stat (struct bfd *abfd, struct stat *sb) override;
283 private:
284 /* The base address of the in-memory BFD file. */
285 CORE_ADDR m_base;
287 /* The size (in-bytes) of the in-memory BFD file. */
288 ULONGEST m_size;
290 /* Holds the generated name of the in-memory BFD file. */
291 gdb::unique_xmalloc_ptr<char> m_filename;
294 /* For `gdb_bfd_open_from_target_memory`. For reading the file, we just need to
295 pass through to target_read_memory and fix up the arguments and return
296 values. */
298 file_ptr
299 target_buffer::read (struct bfd *abfd, void *buf,
300 file_ptr nbytes, file_ptr offset)
302 /* If this read will read all of the file, limit it to just the rest. */
303 if (offset + nbytes > size ())
304 nbytes = size () - offset;
306 /* If there are no more bytes left, we've reached EOF. */
307 if (nbytes == 0)
308 return 0;
310 int err = target_read_memory (base () + offset, (gdb_byte *) buf, nbytes);
311 if (err)
312 return -1;
314 return nbytes;
317 /* For `gdb_bfd_open_from_target_memory`. For statting the file, we only
318 support the st_size attribute. */
321 target_buffer::stat (struct bfd *abfd, struct stat *sb)
323 memset (sb, 0, sizeof (struct stat));
324 sb->st_size = size ();
325 return 0;
328 /* See gdb_bfd.h. */
330 gdb_bfd_ref_ptr
331 gdb_bfd_open_from_target_memory (CORE_ADDR addr, ULONGEST size,
332 const char *target)
334 std::unique_ptr<target_buffer> buffer
335 = std::make_unique<target_buffer> (addr, size);
337 return gdb_bfd_openr_iovec (buffer->filename (), target,
338 [&] (bfd *nbfd)
340 return buffer.release ();
344 /* An object that manages the underlying stream for a BFD, using
345 target file I/O. */
347 struct target_fileio_stream : public gdb_bfd_iovec_base
349 target_fileio_stream (bfd *nbfd, int fd)
350 : m_bfd (nbfd),
351 m_fd (fd)
355 ~target_fileio_stream ();
357 file_ptr read (bfd *abfd, void *buffer, file_ptr nbytes,
358 file_ptr offset) override;
360 int stat (struct bfd *abfd, struct stat *sb) override;
362 private:
364 /* The BFD. Saved for the destructor. */
365 bfd *m_bfd;
367 /* The file descriptor. */
368 int m_fd;
371 /* Wrapper for target_fileio_open suitable for use as a helper
372 function for gdb_bfd_openr_iovec. */
374 static target_fileio_stream *
375 gdb_bfd_iovec_fileio_open (struct bfd *abfd, inferior *inf, bool warn_if_slow)
377 const char *filename = bfd_get_filename (abfd);
378 int fd;
379 fileio_error target_errno;
381 gdb_assert (is_target_filename (filename));
383 fd = target_fileio_open (inf,
384 filename + strlen (TARGET_SYSROOT_PREFIX),
385 FILEIO_O_RDONLY, 0, warn_if_slow,
386 &target_errno);
387 if (fd == -1)
389 errno = fileio_error_to_host (target_errno);
390 bfd_set_error (bfd_error_system_call);
391 return NULL;
394 return new target_fileio_stream (abfd, fd);
397 /* Wrapper for target_fileio_pread. */
399 file_ptr
400 target_fileio_stream::read (struct bfd *abfd, void *buf,
401 file_ptr nbytes, file_ptr offset)
403 fileio_error target_errno;
404 file_ptr pos, bytes;
406 pos = 0;
407 while (nbytes > pos)
409 QUIT;
411 bytes = target_fileio_pread (m_fd, (gdb_byte *) buf + pos,
412 nbytes - pos, offset + pos,
413 &target_errno);
414 if (bytes == 0)
415 /* Success, but no bytes, means end-of-file. */
416 break;
417 if (bytes == -1)
419 errno = fileio_error_to_host (target_errno);
420 bfd_set_error (bfd_error_system_call);
421 return -1;
424 pos += bytes;
427 return pos;
430 /* Warn that it wasn't possible to close a bfd for file NAME, because
431 of REASON. */
433 static void
434 gdb_bfd_close_warning (const char *name, const char *reason)
436 warning (_("cannot close \"%s\": %s"), name, reason);
439 /* Wrapper for target_fileio_close. */
441 target_fileio_stream::~target_fileio_stream ()
443 fileio_error target_errno;
445 /* Ignore errors on close. These may happen with remote
446 targets if the connection has already been torn down. */
449 target_fileio_close (m_fd, &target_errno);
451 catch (const gdb_exception &ex)
453 /* Also avoid crossing exceptions over bfd. */
454 gdb_bfd_close_warning (bfd_get_filename (m_bfd),
455 ex.message->c_str ());
459 /* Wrapper for target_fileio_fstat. */
462 target_fileio_stream::stat (struct bfd *abfd, struct stat *sb)
464 fileio_error target_errno;
465 int result;
467 result = target_fileio_fstat (m_fd, sb, &target_errno);
468 if (result == -1)
470 errno = fileio_error_to_host (target_errno);
471 bfd_set_error (bfd_error_system_call);
474 return result;
477 /* A helper function to initialize the data that gdb attaches to each
478 BFD. */
480 static void
481 gdb_bfd_init_data (struct bfd *abfd, struct stat *st)
483 struct gdb_bfd_data *gdata;
484 void **slot;
486 gdb_assert (bfd_usrdata (abfd) == nullptr);
488 /* Ask BFD to decompress sections in bfd_get_full_section_contents. */
489 abfd->flags |= BFD_DECOMPRESS;
491 gdata = new gdb_bfd_data (abfd, st);
492 bfd_set_usrdata (abfd, gdata);
494 /* This is the first we've seen it, so add it to the hash table. */
495 slot = htab_find_slot (all_bfds, abfd, INSERT);
496 gdb_assert (slot && !*slot);
497 *slot = abfd;
500 /* See gdb_bfd.h. */
502 gdb_bfd_ref_ptr
503 gdb_bfd_open (const char *name, const char *target, int fd,
504 bool warn_if_slow)
506 hashval_t hash;
507 void **slot;
508 bfd *abfd;
509 struct gdb_bfd_cache_search search;
510 struct stat st;
512 if (is_target_filename (name))
514 if (!target_filesystem_is_local ())
516 gdb_assert (fd == -1);
518 auto open = [&] (bfd *nbfd) -> gdb_bfd_iovec_base *
520 return gdb_bfd_iovec_fileio_open (nbfd, current_inferior (),
521 warn_if_slow);
524 return gdb_bfd_openr_iovec (name, target, open);
527 name += strlen (TARGET_SYSROOT_PREFIX);
530 #if CXX_STD_THREAD
531 std::lock_guard<std::recursive_mutex> guard (gdb_bfd_mutex);
532 #endif
534 if (gdb_bfd_cache == NULL)
535 gdb_bfd_cache = htab_create_alloc (1, hash_bfd, eq_bfd, NULL,
536 xcalloc, xfree);
538 if (fd == -1)
540 fd = gdb_open_cloexec (name, O_RDONLY | O_BINARY, 0).release ();
541 if (fd == -1)
543 bfd_set_error (bfd_error_system_call);
544 return NULL;
548 if (fstat (fd, &st) < 0)
550 /* Weird situation here -- don't cache if we can't stat. */
551 bfd_cache_debug_printf ("Could not stat %s - not caching", name);
552 abfd = bfd_fopen (name, target, FOPEN_RB, fd);
553 if (abfd == nullptr)
554 return nullptr;
555 return gdb_bfd_ref_ptr::new_reference (abfd);
558 search.filename = name;
559 search.mtime = st.st_mtime;
560 search.size = st.st_size;
561 search.inode = st.st_ino;
562 search.device_id = st.st_dev;
564 /* Note that this must compute the same result as hash_bfd. */
565 hash = htab_hash_string (name);
566 /* Note that we cannot use htab_find_slot_with_hash here, because
567 opening the BFD may fail; and this would violate hashtab
568 invariants. */
569 abfd = (struct bfd *) htab_find_with_hash (gdb_bfd_cache, &search, hash);
570 if (bfd_sharing && abfd != NULL)
572 bfd_cache_debug_printf ("Reusing cached bfd %s for %s",
573 host_address_to_string (abfd),
574 bfd_get_filename (abfd));
575 close (fd);
576 return gdb_bfd_ref_ptr::new_reference (abfd);
579 abfd = bfd_fopen (name, target, FOPEN_RB, fd);
580 if (abfd == NULL)
581 return NULL;
583 bfd_set_cacheable (abfd, 1);
585 bfd_cache_debug_printf ("Creating new bfd %s for %s",
586 host_address_to_string (abfd),
587 bfd_get_filename (abfd));
589 if (bfd_sharing)
591 slot = htab_find_slot_with_hash (gdb_bfd_cache, &search, hash, INSERT);
592 gdb_assert (!*slot);
593 *slot = abfd;
596 /* It's important to pass the already-computed stat info here,
597 rather than, say, calling gdb_bfd_ref_ptr::new_reference. BFD by
598 default will "stat" the file each time bfd_get_mtime is called --
599 and since we already entered it into the hash table using this
600 mtime, if the file changed at the wrong moment, the race would
601 lead to a hash table corruption. */
602 gdb_bfd_init_data (abfd, &st);
603 return gdb_bfd_ref_ptr (abfd);
606 /* A helper function that releases any section data attached to the
607 BFD. */
609 static void
610 free_one_bfd_section (asection *sectp)
612 struct gdb_bfd_section_data *sect
613 = (struct gdb_bfd_section_data *) bfd_section_userdata (sectp);
615 if (sect != NULL && sect->data != NULL)
617 #ifdef HAVE_MMAP
618 if (sect->map_addr != NULL)
620 int res;
622 res = munmap (sect->map_addr, sect->map_len);
623 gdb_assert (res == 0);
625 else
626 #endif
627 xfree (sect->data);
631 /* Close ABFD, and warn if that fails. */
633 static int
634 gdb_bfd_close_or_warn (struct bfd *abfd)
636 int ret;
637 const char *name = bfd_get_filename (abfd);
639 for (asection *sect : gdb_bfd_sections (abfd))
640 free_one_bfd_section (sect);
642 ret = bfd_close (abfd);
644 if (!ret)
645 gdb_bfd_close_warning (name,
646 bfd_errmsg (bfd_get_error ()));
648 return ret;
651 /* See gdb_bfd.h. */
653 void
654 gdb_bfd_ref (struct bfd *abfd)
656 struct gdb_bfd_data *gdata;
658 if (abfd == NULL)
659 return;
661 #if CXX_STD_THREAD
662 std::lock_guard<std::recursive_mutex> guard (gdb_bfd_mutex);
663 #endif
665 gdata = (struct gdb_bfd_data *) bfd_usrdata (abfd);
667 bfd_cache_debug_printf ("Increase reference count on bfd %s (%s)",
668 host_address_to_string (abfd),
669 bfd_get_filename (abfd));
671 if (gdata != NULL)
673 gdata->refc += 1;
674 return;
677 /* Caching only happens via gdb_bfd_open, so passing nullptr here is
678 fine. */
679 gdb_bfd_init_data (abfd, nullptr);
682 /* See gdb_bfd.h. */
684 void
685 gdb_bfd_unref (struct bfd *abfd)
687 struct gdb_bfd_data *gdata;
688 struct gdb_bfd_cache_search search;
689 bfd *archive_bfd;
691 if (abfd == NULL)
692 return;
694 #if CXX_STD_THREAD
695 std::lock_guard<std::recursive_mutex> guard (gdb_bfd_mutex);
696 #endif
698 gdata = (struct gdb_bfd_data *) bfd_usrdata (abfd);
699 gdb_assert (gdata->refc >= 1);
701 gdata->refc -= 1;
702 if (gdata->refc > 0)
704 bfd_cache_debug_printf ("Decrease reference count on bfd %s (%s)",
705 host_address_to_string (abfd),
706 bfd_get_filename (abfd));
707 return;
710 bfd_cache_debug_printf ("Delete final reference count on bfd %s (%s)",
711 host_address_to_string (abfd),
712 bfd_get_filename (abfd));
714 archive_bfd = gdata->archive_bfd;
715 search.filename = bfd_get_filename (abfd);
717 if (gdb_bfd_cache && search.filename)
719 hashval_t hash = htab_hash_string (search.filename);
720 void **slot;
722 search.mtime = gdata->mtime;
723 search.size = gdata->size;
724 search.inode = gdata->inode;
725 search.device_id = gdata->device_id;
726 slot = htab_find_slot_with_hash (gdb_bfd_cache, &search, hash,
727 NO_INSERT);
729 if (slot && *slot)
730 htab_clear_slot (gdb_bfd_cache, slot);
733 delete gdata;
734 bfd_set_usrdata (abfd, NULL); /* Paranoia. */
736 htab_remove_elt (all_bfds, abfd);
738 gdb_bfd_close_or_warn (abfd);
740 gdb_bfd_unref (archive_bfd);
743 /* A helper function that returns the section data descriptor
744 associated with SECTION. If no such descriptor exists, a new one
745 is allocated and cleared. */
747 static struct gdb_bfd_section_data *
748 get_section_descriptor (asection *section)
750 struct gdb_bfd_section_data *result;
752 result = (struct gdb_bfd_section_data *) bfd_section_userdata (section);
754 if (result == NULL)
756 result = ((struct gdb_bfd_section_data *)
757 bfd_zalloc (section->owner, sizeof (*result)));
758 bfd_set_section_userdata (section, result);
761 return result;
764 /* See gdb_bfd.h. */
766 const gdb_byte *
767 gdb_bfd_map_section (asection *sectp, bfd_size_type *size)
769 bfd *abfd;
770 struct gdb_bfd_section_data *descriptor;
771 bfd_byte *data;
773 gdb_assert ((sectp->flags & SEC_RELOC) == 0);
774 gdb_assert (size != NULL);
776 abfd = sectp->owner;
778 descriptor = get_section_descriptor (sectp);
780 /* If the data was already read for this BFD, just reuse it. */
781 if (descriptor->data != NULL)
782 goto done;
784 #ifdef HAVE_MMAP
785 if (!bfd_is_section_compressed (abfd, sectp))
787 /* The page size, used when mmapping. */
788 static int pagesize;
790 if (pagesize == 0)
791 pagesize = getpagesize ();
793 /* Only try to mmap sections which are large enough: we don't want
794 to waste space due to fragmentation. */
796 if (bfd_section_size (sectp) > 4 * pagesize)
798 descriptor->size = bfd_section_size (sectp);
799 descriptor->data = bfd_mmap (abfd, 0, descriptor->size, PROT_READ,
800 MAP_PRIVATE, sectp->filepos,
801 &descriptor->map_addr,
802 &descriptor->map_len);
804 if ((caddr_t)descriptor->data != MAP_FAILED)
806 #if HAVE_POSIX_MADVISE
807 posix_madvise (descriptor->map_addr, descriptor->map_len,
808 POSIX_MADV_WILLNEED);
809 #endif
810 goto done;
813 /* On failure, clear out the section data and try again. */
814 memset (descriptor, 0, sizeof (*descriptor));
817 #endif /* HAVE_MMAP */
819 /* Handle compressed sections, or ordinary uncompressed sections in
820 the no-mmap case. */
822 descriptor->size = bfd_section_size (sectp);
823 descriptor->data = NULL;
825 data = NULL;
826 if (!bfd_get_full_section_contents (abfd, sectp, &data))
828 warning (_("Can't read data for section '%s' in file '%s'"),
829 bfd_section_name (sectp),
830 bfd_get_filename (abfd));
831 /* Set size to 0 to prevent further attempts to read the invalid
832 section. */
833 *size = 0;
834 return NULL;
836 descriptor->data = data;
838 done:
839 gdb_assert (descriptor->data != NULL);
840 *size = descriptor->size;
841 return (const gdb_byte *) descriptor->data;
844 /* Return 32-bit CRC for ABFD. If successful store it to *FILE_CRC_RETURN and
845 return 1. Otherwise print a warning and return 0. ABFD seek position is
846 not preserved. */
848 static int
849 get_file_crc (bfd *abfd, unsigned long *file_crc_return)
851 uint32_t file_crc = 0;
853 if (bfd_seek (abfd, 0, SEEK_SET) != 0)
855 warning (_("Problem reading \"%s\" for CRC: %s"),
856 bfd_get_filename (abfd), bfd_errmsg (bfd_get_error ()));
857 return 0;
860 for (;;)
862 gdb_byte buffer[8 * 1024];
863 bfd_size_type count;
865 count = bfd_read (buffer, sizeof (buffer), abfd);
866 if (count == (bfd_size_type) -1)
868 warning (_("Problem reading \"%s\" for CRC: %s"),
869 bfd_get_filename (abfd), bfd_errmsg (bfd_get_error ()));
870 return 0;
872 if (count == 0)
873 break;
874 file_crc = bfd_calc_gnu_debuglink_crc32 (file_crc, buffer, count);
877 *file_crc_return = file_crc;
878 return 1;
881 /* See gdb_bfd.h. */
884 gdb_bfd_crc (struct bfd *abfd, unsigned long *crc_out)
886 struct gdb_bfd_data *gdata = (struct gdb_bfd_data *) bfd_usrdata (abfd);
888 if (!gdata->crc_computed)
889 gdata->crc_computed = get_file_crc (abfd, &gdata->crc);
891 if (gdata->crc_computed)
892 *crc_out = gdata->crc;
893 return gdata->crc_computed;
898 /* See gdb_bfd.h. */
900 gdb_bfd_ref_ptr
901 gdb_bfd_fopen (const char *filename, const char *target, const char *mode,
902 int fd)
904 bfd *result = bfd_fopen (filename, target, mode, fd);
906 if (result != nullptr)
907 bfd_set_cacheable (result, 1);
909 return gdb_bfd_ref_ptr::new_reference (result);
912 /* See gdb_bfd.h. */
914 gdb_bfd_ref_ptr
915 gdb_bfd_openr (const char *filename, const char *target)
917 bfd *result = bfd_openr (filename, target);
919 return gdb_bfd_ref_ptr::new_reference (result);
922 /* See gdb_bfd.h. */
924 gdb_bfd_ref_ptr
925 gdb_bfd_openw (const char *filename, const char *target)
927 bfd *result = bfd_openw (filename, target);
929 return gdb_bfd_ref_ptr::new_reference (result);
932 /* See gdb_bfd.h. */
934 gdb_bfd_ref_ptr
935 gdb_bfd_openr_iovec (const char *filename, const char *target,
936 gdb_iovec_opener_ftype open_fn)
938 auto do_open = [] (bfd *nbfd, void *closure) -> void *
940 auto real_opener = static_cast<gdb_iovec_opener_ftype *> (closure);
941 return (*real_opener) (nbfd);
944 auto read_trampoline = [] (bfd *nbfd, void *stream, void *buf,
945 file_ptr nbytes, file_ptr offset) -> file_ptr
947 gdb_bfd_iovec_base *obj = static_cast<gdb_bfd_iovec_base *> (stream);
948 return obj->read (nbfd, buf, nbytes, offset);
951 auto stat_trampoline = [] (struct bfd *abfd, void *stream,
952 struct stat *sb) -> int
954 gdb_bfd_iovec_base *obj = static_cast<gdb_bfd_iovec_base *> (stream);
955 return obj->stat (abfd, sb);
958 auto close_trampoline = [] (struct bfd *nbfd, void *stream) -> int
960 gdb_bfd_iovec_base *obj = static_cast<gdb_bfd_iovec_base *> (stream);
961 delete obj;
962 /* Success. */
963 return 0;
966 bfd *result = bfd_openr_iovec (filename, target,
967 do_open, &open_fn,
968 read_trampoline, close_trampoline,
969 stat_trampoline);
971 return gdb_bfd_ref_ptr::new_reference (result);
974 /* See gdb_bfd.h. */
976 void
977 gdb_bfd_mark_parent (bfd *child, bfd *parent)
979 struct gdb_bfd_data *gdata;
981 gdb_bfd_ref (child);
982 /* No need to stash the filename here, because we also keep a
983 reference on the parent archive. */
985 gdata = (struct gdb_bfd_data *) bfd_usrdata (child);
986 if (gdata->archive_bfd == NULL)
988 gdata->archive_bfd = parent;
989 gdb_bfd_ref (parent);
991 else
992 gdb_assert (gdata->archive_bfd == parent);
995 /* See gdb_bfd.h. */
997 gdb_bfd_ref_ptr
998 gdb_bfd_openr_next_archived_file (bfd *archive, bfd *previous)
1000 bfd *result = bfd_openr_next_archived_file (archive, previous);
1002 if (result)
1003 gdb_bfd_mark_parent (result, archive);
1005 return gdb_bfd_ref_ptr (result);
1008 /* See gdb_bfd.h. */
1010 void
1011 gdb_bfd_record_inclusion (bfd *includer, bfd *includee)
1013 struct gdb_bfd_data *gdata;
1015 gdata = (struct gdb_bfd_data *) bfd_usrdata (includer);
1016 gdata->included_bfds.push_back (gdb_bfd_ref_ptr::new_reference (includee));
1021 static_assert (ARRAY_SIZE (_bfd_std_section) == 4);
1023 /* See gdb_bfd.h. */
1026 gdb_bfd_section_index (bfd *abfd, asection *section)
1028 if (section == NULL)
1029 return -1;
1030 else if (section == bfd_com_section_ptr)
1031 return bfd_count_sections (abfd);
1032 else if (section == bfd_und_section_ptr)
1033 return bfd_count_sections (abfd) + 1;
1034 else if (section == bfd_abs_section_ptr)
1035 return bfd_count_sections (abfd) + 2;
1036 else if (section == bfd_ind_section_ptr)
1037 return bfd_count_sections (abfd) + 3;
1038 return section->index;
1041 /* See gdb_bfd.h. */
1044 gdb_bfd_count_sections (bfd *abfd)
1046 return bfd_count_sections (abfd) + 4;
1049 /* See gdb_bfd.h. */
1052 gdb_bfd_requires_relocations (bfd *abfd)
1054 struct gdb_bfd_data *gdata = (struct gdb_bfd_data *) bfd_usrdata (abfd);
1056 if (gdata->relocation_computed == 0)
1058 asection *sect;
1060 for (sect = abfd->sections; sect != NULL; sect = sect->next)
1061 if ((sect->flags & SEC_RELOC) != 0)
1063 gdata->needs_relocations = 1;
1064 break;
1067 gdata->relocation_computed = 1;
1070 return gdata->needs_relocations;
1073 /* See gdb_bfd.h. */
1075 bool
1076 gdb_bfd_get_full_section_contents (bfd *abfd, asection *section,
1077 gdb::byte_vector *contents)
1079 bfd_size_type section_size = bfd_section_size (section);
1081 contents->resize (section_size);
1083 return bfd_get_section_contents (abfd, section, contents->data (), 0,
1084 section_size);
1087 #define AMBIGUOUS_MESS1 ".\nMatching formats:"
1088 #define AMBIGUOUS_MESS2 \
1089 ".\nUse \"set gnutarget format-name\" to specify the format."
1091 /* See gdb_bfd.h. */
1093 std::string
1094 gdb_bfd_errmsg (bfd_error_type error_tag, char **matching)
1096 char **p;
1098 /* Check if errmsg just need simple return. */
1099 if (error_tag != bfd_error_file_ambiguously_recognized || matching == NULL)
1100 return bfd_errmsg (error_tag);
1102 std::string ret (bfd_errmsg (error_tag));
1103 ret += AMBIGUOUS_MESS1;
1105 for (p = matching; *p; p++)
1107 ret += " ";
1108 ret += *p;
1110 ret += AMBIGUOUS_MESS2;
1112 xfree (matching);
1114 return ret;
1117 /* A callback for htab_traverse that prints a single BFD. */
1119 static int
1120 print_one_bfd (void **slot, void *data)
1122 bfd *abfd = (struct bfd *) *slot;
1123 struct gdb_bfd_data *gdata = (struct gdb_bfd_data *) bfd_usrdata (abfd);
1124 struct ui_out *uiout = (struct ui_out *) data;
1126 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1127 uiout->field_signed ("refcount", gdata->refc);
1128 uiout->field_string ("addr", host_address_to_string (abfd));
1129 uiout->field_string ("filename", bfd_get_filename (abfd),
1130 file_name_style.style ());
1131 uiout->text ("\n");
1133 return 1;
1136 /* Implement the 'maint info bfd' command. */
1138 static void
1139 maintenance_info_bfds (const char *arg, int from_tty)
1141 struct ui_out *uiout = current_uiout;
1143 ui_out_emit_table table_emitter (uiout, 3, -1, "bfds");
1144 uiout->table_header (10, ui_left, "refcount", "Refcount");
1145 uiout->table_header (18, ui_left, "addr", "Address");
1146 uiout->table_header (40, ui_left, "filename", "Filename");
1148 uiout->table_body ();
1149 htab_traverse (all_bfds, print_one_bfd, uiout);
1152 /* BFD related per-inferior data. */
1154 struct bfd_inferior_data
1156 std::unordered_map<std::string, unsigned long> bfd_error_string_counts;
1159 /* Per-inferior data key. */
1161 static const registry<inferior>::key<bfd_inferior_data> bfd_inferior_data_key;
1163 /* Fetch per-inferior BFD data. It always returns a valid pointer to
1164 a bfd_inferior_data struct. */
1166 static struct bfd_inferior_data *
1167 get_bfd_inferior_data (struct inferior *inf)
1169 struct bfd_inferior_data *data;
1171 data = bfd_inferior_data_key.get (inf);
1172 if (data == nullptr)
1173 data = bfd_inferior_data_key.emplace (inf);
1175 return data;
1178 /* Increment the BFD error count for STR and return the updated
1179 count. */
1181 static unsigned long
1182 increment_bfd_error_count (std::string str)
1184 struct bfd_inferior_data *bid = get_bfd_inferior_data (current_inferior ());
1186 auto &map = bid->bfd_error_string_counts;
1187 return ++map[std::move (str)];
1190 static bfd_error_handler_type default_bfd_error_handler;
1192 /* Define a BFD error handler which will suppress the printing of
1193 messages which have been printed once already. This is done on a
1194 per-inferior basis. */
1196 static void ATTRIBUTE_PRINTF (1, 0)
1197 gdb_bfd_error_handler (const char *fmt, va_list ap)
1199 va_list ap_copy;
1201 va_copy(ap_copy, ap);
1202 const std::string str = string_vprintf (fmt, ap_copy);
1203 va_end (ap_copy);
1205 if (increment_bfd_error_count (std::move (str)) > 1)
1206 return;
1208 /* We must call the BFD mechanism for printing format strings since
1209 it supports additional format specifiers that GDB's vwarning() doesn't
1210 recognize. It also outputs additional text, i.e. "BFD: ", which
1211 makes it clear that it's a BFD warning/error. */
1212 (*default_bfd_error_handler) (fmt, ap);
1215 /* See gdb_bfd.h. */
1217 void
1218 gdb_bfd_init ()
1220 if (bfd_init () == BFD_INIT_MAGIC)
1222 #if CXX_STD_THREAD
1223 if (bfd_thread_init (gdb_bfd_lock, gdb_bfd_unlock, nullptr))
1224 #endif
1225 return;
1228 error (_("fatal error: libbfd ABI mismatch"));
1231 void _initialize_gdb_bfd ();
1232 void
1233 _initialize_gdb_bfd ()
1235 all_bfds = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
1236 NULL, xcalloc, xfree);
1238 add_cmd ("bfds", class_maintenance, maintenance_info_bfds, _("\
1239 List the BFDs that are currently open."),
1240 &maintenanceinfolist);
1242 add_setshow_boolean_cmd ("bfd-sharing", no_class,
1243 &bfd_sharing, _("\
1244 Set whether gdb will share bfds that appear to be the same file."), _("\
1245 Show whether gdb will share bfds that appear to be the same file."), _("\
1246 When enabled gdb will reuse existing bfds rather than reopening the\n\
1247 same file. To decide if two files are the same then gdb compares the\n\
1248 filename, file size, file modification time, and file inode."),
1249 NULL,
1250 &show_bfd_sharing,
1251 &maintenance_set_cmdlist,
1252 &maintenance_show_cmdlist);
1254 add_setshow_boolean_cmd ("bfd-cache", class_maintenance,
1255 &debug_bfd_cache,
1256 _("Set bfd cache debugging."),
1257 _("Show bfd cache debugging."),
1258 _("\
1259 When non-zero, bfd cache specific debugging is enabled."),
1260 NULL,
1261 &show_bfd_cache_debug,
1262 &setdebuglist, &showdebuglist);
1264 /* Hook the BFD error/warning handler to limit amount of output. */
1265 default_bfd_error_handler = bfd_set_error_handler (gdb_bfd_error_handler);