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