[gdb/tdep] Fix reverse execution of LDR(immediate) T4
[binutils-gdb.git] / gdb / solib.c
blob952897c37fc95d1abf71b09e938d958b680d700a
1 /* Handle shared libraries for GDB, the GNU Debugger.
3 Copyright (C) 1990-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 "defs.h"
22 #include <fcntl.h>
23 #include "symtab.h"
24 #include "bfd.h"
25 #include "build-id.h"
26 #include "symfile.h"
27 #include "objfiles.h"
28 #include "gdbcore.h"
29 #include "command.h"
30 #include "target.h"
31 #include "frame.h"
32 #include "inferior.h"
33 #include "gdbsupport/environ.h"
34 #include "cli/cli-cmds.h"
35 #include "elf/external.h"
36 #include "elf/common.h"
37 #include "filenames.h"
38 #include "exec.h"
39 #include "solist.h"
40 #include "observable.h"
41 #include "readline/tilde.h"
42 #include "solib.h"
43 #include "interps.h"
44 #include "filesystem.h"
45 #include "gdb_bfd.h"
46 #include "gdbsupport/filestuff.h"
47 #include "gdbsupport/scoped_fd.h"
48 #include "debuginfod-support.h"
49 #include "source.h"
50 #include "cli/cli-style.h"
52 /* See solib.h. */
54 bool debug_solib;
56 /* If non-empty, this is a search path for loading non-absolute shared library
57 symbol files. This takes precedence over the environment variables PATH
58 and LD_LIBRARY_PATH. */
59 static std::string solib_search_path;
61 static void
62 show_solib_search_path (struct ui_file *file, int from_tty,
63 struct cmd_list_element *c, const char *value)
65 gdb_printf (file,
66 _ ("The search path for loading non-absolute "
67 "shared library symbol files is %s.\n"),
68 value);
71 /* Same as HAVE_DOS_BASED_FILE_SYSTEM, but useable as an rvalue. */
72 #if (HAVE_DOS_BASED_FILE_SYSTEM)
73 #define DOS_BASED_FILE_SYSTEM 1
74 #else
75 #define DOS_BASED_FILE_SYSTEM 0
76 #endif
78 /* Return the full pathname of a binary file (the main executable or a
79 shared library file), or NULL if not found. If FD is non-NULL, *FD
80 is set to either -1 or an open file handle for the binary file.
82 Global variable GDB_SYSROOT is used as a prefix directory
83 to search for binary files if they have an absolute path.
84 If GDB_SYSROOT starts with "target:" and target filesystem
85 is the local filesystem then the "target:" prefix will be
86 stripped before the search starts. This ensures that the
87 same search algorithm is used for local files regardless of
88 whether a "target:" prefix was used.
90 Global variable SOLIB_SEARCH_PATH is used as a prefix directory
91 (or set of directories, as in LD_LIBRARY_PATH) to search for all
92 shared libraries if not found in either the sysroot (if set) or
93 the local filesystem. SOLIB_SEARCH_PATH is not used when searching
94 for the main executable.
96 Search algorithm:
97 * If a sysroot is set and path is absolute:
98 * Search for sysroot/path.
99 * else
100 * Look for it literally (unmodified).
101 * If IS_SOLIB is non-zero:
102 * Look in SOLIB_SEARCH_PATH.
103 * If available, use target defined search function.
104 * If NO sysroot is set, perform the following two searches:
105 * Look in inferior's $PATH.
106 * If IS_SOLIB is non-zero:
107 * Look in inferior's $LD_LIBRARY_PATH.
109 * The last check avoids doing this search when targeting remote
110 * machines since a sysroot will almost always be set.
113 static gdb::unique_xmalloc_ptr<char>
114 solib_find_1 (const char *in_pathname, int *fd, bool is_solib)
116 const solib_ops *ops = gdbarch_so_ops (current_inferior ()->arch ());
117 int found_file = -1;
118 gdb::unique_xmalloc_ptr<char> temp_pathname;
119 const char *fskind = effective_target_file_system_kind ();
120 const char *sysroot = gdb_sysroot.c_str ();
121 int prefix_len, orig_prefix_len;
123 /* If the absolute prefix starts with "target:" but the filesystem
124 accessed by the target_fileio_* methods is the local filesystem
125 then we strip the "target:" prefix now and work with the local
126 filesystem. This ensures that the same search algorithm is used
127 for all local files regardless of whether a "target:" prefix was
128 used. */
129 if (is_target_filename (sysroot) && target_filesystem_is_local ())
130 sysroot += strlen (TARGET_SYSROOT_PREFIX);
132 /* Strip any trailing slashes from the absolute prefix. */
133 prefix_len = orig_prefix_len = strlen (sysroot);
135 while (prefix_len > 0 && IS_DIR_SEPARATOR (sysroot[prefix_len - 1]))
136 prefix_len--;
138 std::string sysroot_holder;
139 if (prefix_len == 0)
140 sysroot = NULL;
141 else if (prefix_len != orig_prefix_len)
143 sysroot_holder = std::string (sysroot, prefix_len);
144 sysroot = sysroot_holder.c_str ();
147 /* If we're on a non-DOS-based system, backslashes won't be
148 understood as directory separator, so, convert them to forward
149 slashes, iff we're supposed to handle DOS-based file system
150 semantics for target paths. */
151 if (!DOS_BASED_FILE_SYSTEM && fskind == file_system_kind_dos_based)
153 char *p;
155 /* Avoid clobbering our input. */
156 p = (char *) alloca (strlen (in_pathname) + 1);
157 strcpy (p, in_pathname);
158 in_pathname = p;
160 for (; *p; p++)
162 if (*p == '\\')
163 *p = '/';
167 /* Note, we're interested in IS_TARGET_ABSOLUTE_PATH, not
168 IS_ABSOLUTE_PATH. The latter is for host paths only, while
169 IN_PATHNAME is a target path. For example, if we're supposed to
170 be handling DOS-like semantics we want to consider a
171 'c:/foo/bar.dll' path as an absolute path, even on a Unix box.
172 With such a path, before giving up on the sysroot, we'll try:
174 1st attempt, c:/foo/bar.dll ==> /sysroot/c:/foo/bar.dll
175 2nd attempt, c:/foo/bar.dll ==> /sysroot/c/foo/bar.dll
176 3rd attempt, c:/foo/bar.dll ==> /sysroot/foo/bar.dll
179 if (!IS_TARGET_ABSOLUTE_PATH (fskind, in_pathname) || sysroot == NULL)
180 temp_pathname.reset (xstrdup (in_pathname));
181 else
183 bool need_dir_separator;
185 /* Concatenate the sysroot and the target reported filename. We
186 may need to glue them with a directory separator. Cases to
187 consider:
189 | sysroot | separator | in_pathname |
190 |-----------------+-----------+----------------|
191 | /some/dir | / | c:/foo/bar.dll |
192 | /some/dir | | /foo/bar.dll |
193 | target: | | c:/foo/bar.dll |
194 | target: | | /foo/bar.dll |
195 | target:some/dir | / | c:/foo/bar.dll |
196 | target:some/dir | | /foo/bar.dll |
198 IOW, we don't need to add a separator if IN_PATHNAME already
199 has one, or when the sysroot is exactly "target:".
200 There's no need to check for drive spec explicitly, as we only
201 get here if IN_PATHNAME is considered an absolute path. */
202 need_dir_separator = !(IS_DIR_SEPARATOR (in_pathname[0])
203 || strcmp (TARGET_SYSROOT_PREFIX, sysroot) == 0);
205 /* Cat the prefixed pathname together. */
206 temp_pathname.reset (concat (sysroot,
207 need_dir_separator ? SLASH_STRING : "",
208 in_pathname, (char *) NULL));
211 /* Handle files to be accessed via the target. */
212 if (is_target_filename (temp_pathname.get ()))
214 if (fd != NULL)
215 *fd = -1;
216 return temp_pathname;
219 /* Now see if we can open it. */
220 found_file = gdb_open_cloexec (temp_pathname.get (), O_RDONLY | O_BINARY, 0)
221 .release ();
223 /* If the search in gdb_sysroot failed, and the path name has a
224 drive spec (e.g, c:/foo), try stripping ':' from the drive spec,
225 and retrying in the sysroot:
226 c:/foo/bar.dll ==> /sysroot/c/foo/bar.dll. */
228 if (found_file < 0 && sysroot != NULL
229 && HAS_TARGET_DRIVE_SPEC (fskind, in_pathname))
231 bool need_dir_separator = !IS_DIR_SEPARATOR (in_pathname[2]);
232 char drive[2] = { in_pathname[0], '\0' };
234 temp_pathname.reset (concat (sysroot, SLASH_STRING, drive,
235 need_dir_separator ? SLASH_STRING : "",
236 in_pathname + 2, (char *) NULL));
238 found_file
239 = gdb_open_cloexec (temp_pathname.get (), O_RDONLY | O_BINARY, 0)
240 .release ();
241 if (found_file < 0)
243 /* If the search in gdb_sysroot still failed, try fully
244 stripping the drive spec, and trying once more in the
245 sysroot before giving up.
247 c:/foo/bar.dll ==> /sysroot/foo/bar.dll. */
249 temp_pathname.reset (concat (sysroot,
250 need_dir_separator ? SLASH_STRING : "",
251 in_pathname + 2, (char *) NULL));
253 found_file
254 = gdb_open_cloexec (temp_pathname.get (), O_RDONLY | O_BINARY, 0)
255 .release ();
259 /* We try to find the library in various ways. After each attempt,
260 either found_file >= 0 and temp_pathname is a malloc'd string, or
261 found_file < 0 and temp_pathname does not point to storage that
262 needs to be freed. */
264 if (found_file < 0)
265 temp_pathname.reset (NULL);
267 /* If the search in gdb_sysroot failed, and the path name is
268 absolute at this point, make it relative. (openp will try and open the
269 file according to its absolute path otherwise, which is not what we want.)
270 Affects subsequent searches for this solib. */
271 if (found_file < 0 && IS_TARGET_ABSOLUTE_PATH (fskind, in_pathname))
273 /* First, get rid of any drive letters etc. */
274 while (!IS_TARGET_DIR_SEPARATOR (fskind, *in_pathname))
275 in_pathname++;
277 /* Next, get rid of all leading dir separators. */
278 while (IS_TARGET_DIR_SEPARATOR (fskind, *in_pathname))
279 in_pathname++;
282 /* If not found, and we're looking for a solib, search the
283 solib_search_path (if any). */
284 if (is_solib && found_file < 0 && !solib_search_path.empty ())
285 found_file = openp (solib_search_path.c_str (),
286 OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH, in_pathname,
287 O_RDONLY | O_BINARY, &temp_pathname);
289 /* If not found, and we're looking for a solib, next search the
290 solib_search_path (if any) for the basename only (ignoring the
291 path). This is to allow reading solibs from a path that differs
292 from the opened path. */
293 if (is_solib && found_file < 0 && !solib_search_path.empty ())
294 found_file = openp (solib_search_path.c_str (),
295 OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH,
296 target_lbasename (fskind, in_pathname),
297 O_RDONLY | O_BINARY, &temp_pathname);
299 /* If not found, and we're looking for a solib, try to use target
300 supplied solib search method. */
301 if (is_solib && found_file < 0 && ops->find_and_open_solib)
302 found_file = ops->find_and_open_solib (in_pathname, O_RDONLY | O_BINARY,
303 &temp_pathname);
305 /* If not found, next search the inferior's $PATH environment variable. */
306 if (found_file < 0 && sysroot == NULL)
307 found_file = openp (current_inferior ()->environment.get ("PATH"),
308 OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH, in_pathname,
309 O_RDONLY | O_BINARY, &temp_pathname);
311 /* If not found, and we're looking for a solib, next search the
312 inferior's $LD_LIBRARY_PATH environment variable. */
313 if (is_solib && found_file < 0 && sysroot == NULL)
314 found_file
315 = openp (current_inferior ()->environment.get ("LD_LIBRARY_PATH"),
316 OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH, in_pathname,
317 O_RDONLY | O_BINARY, &temp_pathname);
319 if (fd == NULL)
321 if (found_file >= 0)
322 close (found_file);
324 else
325 *fd = found_file;
327 return temp_pathname;
330 /* Return the full pathname of the main executable, or NULL if not
331 found. If FD is non-NULL, *FD is set to either -1 or an open file
332 handle for the main executable. */
334 gdb::unique_xmalloc_ptr<char>
335 exec_file_find (const char *in_pathname, int *fd)
337 gdb::unique_xmalloc_ptr<char> result;
338 const char *fskind = effective_target_file_system_kind ();
340 if (in_pathname == NULL)
341 return NULL;
343 if (!gdb_sysroot.empty () && IS_TARGET_ABSOLUTE_PATH (fskind, in_pathname))
345 result = solib_find_1 (in_pathname, fd, false);
347 if (result == NULL && fskind == file_system_kind_dos_based)
349 char *new_pathname;
351 new_pathname = (char *) alloca (strlen (in_pathname) + 5);
352 strcpy (new_pathname, in_pathname);
353 strcat (new_pathname, ".exe");
355 result = solib_find_1 (new_pathname, fd, false);
358 else
360 /* It's possible we don't have a full path, but rather just a
361 filename. Some targets, such as HP-UX, don't provide the
362 full path, sigh.
364 Attempt to qualify the filename against the source path.
365 (If that fails, we'll just fall back on the original
366 filename. Not much more we can do...) */
368 if (!source_full_path_of (in_pathname, &result))
369 result.reset (xstrdup (in_pathname));
370 if (fd != NULL)
371 *fd = -1;
374 return result;
377 /* Return the full pathname of a shared library file, or NULL if not
378 found. If FD is non-NULL, *FD is set to either -1 or an open file
379 handle for the shared library.
381 The search algorithm used is described in solib_find_1's comment
382 above. */
384 gdb::unique_xmalloc_ptr<char>
385 solib_find (const char *in_pathname, int *fd)
387 const char *solib_symbols_extension
388 = gdbarch_solib_symbols_extension (current_inferior ()->arch ());
390 /* If solib_symbols_extension is set, replace the file's
391 extension. */
392 if (solib_symbols_extension != NULL)
394 const char *p = in_pathname + strlen (in_pathname);
396 while (p > in_pathname && *p != '.')
397 p--;
399 if (*p == '.')
401 char *new_pathname;
403 new_pathname
404 = (char *) alloca (p - in_pathname + 1
405 + strlen (solib_symbols_extension) + 1);
406 memcpy (new_pathname, in_pathname, p - in_pathname + 1);
407 strcpy (new_pathname + (p - in_pathname) + 1,
408 solib_symbols_extension);
410 in_pathname = new_pathname;
414 return solib_find_1 (in_pathname, fd, true);
417 /* Open and return a BFD for the shared library PATHNAME. If FD is not -1,
418 it is used as file handle to open the file. Throws an error if the file
419 could not be opened. Handles both local and remote file access.
421 If unsuccessful, the FD will be closed (unless FD was -1). */
423 gdb_bfd_ref_ptr
424 solib_bfd_fopen (const char *pathname, int fd)
426 gdb_bfd_ref_ptr abfd (gdb_bfd_open (pathname, gnutarget, fd));
428 if (abfd == NULL)
430 /* Arrange to free PATHNAME when the error is thrown. */
431 error (_ ("Could not open `%s' as an executable file: %s"), pathname,
432 bfd_errmsg (bfd_get_error ()));
435 return abfd;
438 /* Find shared library PATHNAME and open a BFD for it. */
440 gdb_bfd_ref_ptr
441 solib_bfd_open (const char *pathname)
443 int found_file;
444 const struct bfd_arch_info *b;
446 /* Search for shared library file. */
447 gdb::unique_xmalloc_ptr<char> found_pathname
448 = solib_find (pathname, &found_file);
449 if (found_pathname == NULL)
451 /* Return failure if the file could not be found, so that we can
452 accumulate messages about missing libraries. */
453 if (errno == ENOENT)
454 return NULL;
456 perror_with_name (pathname);
459 /* Open bfd for shared library. */
460 gdb_bfd_ref_ptr abfd (solib_bfd_fopen (found_pathname.get (), found_file));
462 /* Check bfd format. */
463 if (!bfd_check_format (abfd.get (), bfd_object))
464 error (_ ("`%s': not in executable format: %s"),
465 bfd_get_filename (abfd.get ()), bfd_errmsg (bfd_get_error ()));
467 /* Check bfd arch. */
468 b = gdbarch_bfd_arch_info (current_inferior ()->arch ());
469 if (!b->compatible (b, bfd_get_arch_info (abfd.get ())))
470 error (_ ("`%s': Shared library architecture %s is not compatible "
471 "with target architecture %s."),
472 bfd_get_filename (abfd.get ()),
473 bfd_get_arch_info (abfd.get ())->printable_name, b->printable_name);
475 return abfd;
478 /* Mapping of a core file's shared library sonames to their respective
479 build-ids. Added to the registries of core file bfds. */
481 typedef std::unordered_map<std::string, std::string> soname_build_id_map;
483 /* Key used to associate a soname_build_id_map to a core file bfd. */
485 static const struct registry<bfd>::key<soname_build_id_map>
486 cbfd_soname_build_id_data_key;
488 /* See solib.h. */
490 void
491 set_cbfd_soname_build_id (gdb_bfd_ref_ptr abfd, const char *soname,
492 const bfd_build_id *build_id)
494 gdb_assert (abfd.get () != nullptr);
495 gdb_assert (soname != nullptr);
496 gdb_assert (build_id != nullptr);
498 soname_build_id_map *mapptr
499 = cbfd_soname_build_id_data_key.get (abfd.get ());
501 if (mapptr == nullptr)
502 mapptr = cbfd_soname_build_id_data_key.emplace (abfd.get ());
504 (*mapptr)[soname] = build_id_to_string (build_id);
507 /* If SONAME had a build-id associated with it in ABFD's registry by a
508 previous call to set_cbfd_soname_build_id then return the build-id
509 as a NULL-terminated hex string. */
511 static gdb::unique_xmalloc_ptr<char>
512 get_cbfd_soname_build_id (gdb_bfd_ref_ptr abfd, const char *soname)
514 if (abfd.get () == nullptr || soname == nullptr)
515 return {};
517 soname_build_id_map *mapptr
518 = cbfd_soname_build_id_data_key.get (abfd.get ());
520 if (mapptr == nullptr)
521 return {};
523 auto it = mapptr->find (lbasename (soname));
524 if (it == mapptr->end ())
525 return {};
527 return make_unique_xstrdup (it->second.c_str ());
530 /* Given a pointer to one of the shared objects in our list of mapped
531 objects, use the recorded name to open a bfd descriptor for the
532 object, build a section table, relocate all the section addresses
533 by the base address at which the shared object was mapped, and then
534 add the sections to the target's section table.
536 FIXME: In most (all?) cases the shared object file name recorded in
537 the dynamic linkage tables will be a fully qualified pathname. For
538 cases where it isn't, do we really mimic the systems search
539 mechanism correctly in the below code (particularly the tilde
540 expansion stuff?). */
542 static int
543 solib_map_sections (solib &so)
545 const solib_ops *ops = gdbarch_so_ops (current_inferior ()->arch ());
547 gdb::unique_xmalloc_ptr<char> filename (tilde_expand (so.so_name.c_str ()));
548 gdb_bfd_ref_ptr abfd (ops->bfd_open (filename.get ()));
549 gdb::unique_xmalloc_ptr<char> build_id_hexstr
550 = get_cbfd_soname_build_id (current_program_space->cbfd,
551 so.so_name.c_str ());
553 /* If we already know the build-id of this solib from a core file, verify
554 it matches ABFD's build-id. If there is a mismatch or the solib wasn't
555 found, attempt to query debuginfod for the correct solib. */
556 if (build_id_hexstr.get () != nullptr)
558 bool mismatch = false;
560 if (abfd != nullptr && abfd->build_id != nullptr)
562 std::string build_id = build_id_to_string (abfd->build_id);
564 if (build_id != build_id_hexstr.get ())
565 mismatch = true;
567 if (abfd == nullptr || mismatch)
569 scoped_fd fd = debuginfod_exec_query (
570 (const unsigned char *) build_id_hexstr.get (), 0,
571 so.so_name.c_str (), &filename);
573 if (fd.get () >= 0)
574 abfd = ops->bfd_open (filename.get ());
575 else if (mismatch)
576 warning (_ ("Build-id of %ps does not match core file."),
577 styled_string (file_name_style.style (),
578 filename.get ()));
582 if (abfd == NULL)
583 return 0;
585 /* Leave bfd open, core_xfer_memory and "info files" need it. */
586 so.abfd = std::move (abfd);
588 /* Copy the full path name into so_name, allowing symbol_file_add
589 to find it later. This also affects the =library-loaded GDB/MI
590 event, and in particular the part of that notification providing
591 the library's host-side path. If we let the target dictate
592 that objfile's path, and the target is different from the host,
593 GDB/MI will not provide the correct host-side path. */
594 if (strlen (bfd_get_filename (so.abfd.get ())) >= SO_NAME_MAX_PATH_SIZE)
595 error (_ ("Shared library file name is too long."));
597 so.so_name = bfd_get_filename (so.abfd.get ());
598 so.sections = build_section_table (so.abfd.get ());
600 for (target_section &p : so.sections)
602 /* Relocate the section binding addresses as recorded in the shared
603 object's file by the base address to which the object was actually
604 mapped. */
605 ops->relocate_section_addresses (so, &p);
607 /* If the target didn't provide information about the address
608 range of the shared object, assume we want the location of
609 the .text section. */
610 if (so.addr_low == 0 && so.addr_high == 0
611 && strcmp (p.the_bfd_section->name, ".text") == 0)
613 so.addr_low = p.addr;
614 so.addr_high = p.endaddr;
618 /* Add the shared object's sections to the current set of file
619 section tables. Do this immediately after mapping the object so
620 that later nodes in the list can query this object, as is needed
621 in solib-osf.c. */
622 current_program_space->add_target_sections (&so, so.sections);
624 return 1;
627 /* See solist.h. */
629 void
630 solib::clear ()
632 const solib_ops *ops = gdbarch_so_ops (current_inferior ()->arch ());
634 this->sections.clear ();
635 this->abfd = nullptr;
637 /* Our caller closed the objfile, possibly via objfile_purge_solibs. */
638 this->symbols_loaded = 0;
639 this->objfile = nullptr;
641 this->addr_low = this->addr_high = 0;
643 /* Restore the target-supplied file name. SO_NAME may be the path
644 of the symbol file. */
645 this->so_name = this->so_original_name;
647 /* Do the same for target-specific data. */
648 if (ops->clear_so != NULL)
649 ops->clear_so (*this);
652 lm_info::~lm_info () = default;
654 /* Read in symbols for shared object SO. If SYMFILE_VERBOSE is set in FLAGS,
655 be chatty about it. Return true if any symbols were actually loaded. */
657 bool
658 solib_read_symbols (solib &so, symfile_add_flags flags)
660 if (so.symbols_loaded)
662 /* If needed, we've already warned in our caller. */
664 else if (so.abfd == NULL)
666 /* We've already warned about this library, when trying to open
667 it. */
669 else
671 flags |= current_inferior ()->symfile_flags;
675 /* Have we already loaded this shared object? */
676 so.objfile = nullptr;
677 for (objfile *objfile : current_program_space->objfiles ())
679 if (filename_cmp (objfile_name (objfile), so.so_name.c_str ())
680 == 0
681 && objfile->addr_low == so.addr_low)
683 so.objfile = objfile;
684 break;
687 if (so.objfile == NULL)
689 section_addr_info sap
690 = build_section_addr_info_from_section_table (so.sections);
691 gdb_bfd_ref_ptr tmp_bfd = so.abfd;
692 so.objfile
693 = symbol_file_add_from_bfd (tmp_bfd, so.so_name.c_str (),
694 flags, &sap, OBJF_SHARED, nullptr);
695 so.objfile->addr_low = so.addr_low;
698 so.symbols_loaded = 1;
700 catch (const gdb_exception_error &e)
702 exception_fprintf (gdb_stderr, e,
703 _ ("Error while reading shared"
704 " library symbols for %s:\n"),
705 so.so_name.c_str ());
708 return true;
711 return false;
714 /* Return true if KNOWN->objfile is used by any other so_list object
715 in the list of shared libraries. Return false otherwise. */
717 static bool
718 solib_used (const solib &known)
720 for (const solib &pivot : current_program_space->solibs ())
721 if (&pivot != &known && pivot.objfile == known.objfile)
722 return true;
723 return false;
726 /* Notify interpreters and observers that solib SO has been loaded. */
728 static void
729 notify_solib_loaded (solib &so)
731 interps_notify_solib_loaded (so);
732 gdb::observers::solib_loaded.notify (so);
735 /* Notify interpreters and observers that solib SO has been unloaded. */
737 static void
738 notify_solib_unloaded (program_space *pspace, const solib &so)
740 interps_notify_solib_unloaded (so);
741 gdb::observers::solib_unloaded.notify (pspace, so);
744 /* See solib.h. */
746 void
747 update_solib_list (int from_tty)
749 const solib_ops *ops = gdbarch_so_ops (current_inferior ()->arch ());
751 /* We can reach here due to changing solib-search-path or the
752 sysroot, before having any inferior. */
753 if (target_has_execution () && inferior_ptid != null_ptid)
755 struct inferior *inf = current_inferior ();
757 /* If we are attaching to a running process for which we
758 have not opened a symbol file, we may be able to get its
759 symbols now! */
760 if (inf->attach_flag
761 && current_program_space->symfile_object_file == NULL)
765 ops->open_symbol_file_object (from_tty);
767 catch (const gdb_exception_error &ex)
769 exception_fprintf (gdb_stderr, ex,
770 "Error reading attached "
771 "process's symbol file.\n");
776 /* GDB and the inferior's dynamic linker each maintain their own
777 list of currently loaded shared objects; we want to bring the
778 former in sync with the latter. Scan both lists, seeing which
779 shared objects appear where. There are three cases:
781 - A shared object appears on both lists. This means that GDB
782 knows about it already, and it's still loaded in the inferior.
783 Nothing needs to happen.
785 - A shared object appears only on GDB's list. This means that
786 the inferior has unloaded it. We should remove the shared
787 object from GDB's tables.
789 - A shared object appears only on the inferior's list. This
790 means that it's just been loaded. We should add it to GDB's
791 tables.
793 So we walk GDB's list, checking each entry to see if it appears
794 in the inferior's list too. If it does, no action is needed, and
795 we remove it from the inferior's list. If it doesn't, the
796 inferior has unloaded it, and we remove it from GDB's list. By
797 the time we're done walking GDB's list, the inferior's list
798 contains only the new shared objects, which we then add. */
800 intrusive_list<solib> inferior = ops->current_sos ();
801 intrusive_list<solib>::iterator gdb_iter
802 = current_program_space->so_list.begin ();
803 while (gdb_iter != current_program_space->so_list.end ())
805 intrusive_list<solib>::iterator inferior_iter = inferior.begin ();
807 /* Check to see whether the shared object *gdb also appears in
808 the inferior's current list. */
809 for (; inferior_iter != inferior.end (); ++inferior_iter)
811 if (ops->same)
813 if (ops->same (*gdb_iter, *inferior_iter))
814 break;
816 else
818 if (!filename_cmp (gdb_iter->so_original_name.c_str (),
819 inferior_iter->so_original_name.c_str ()))
820 break;
824 /* If the shared object appears on the inferior's list too, then
825 it's still loaded, so we don't need to do anything. Delete
826 it from the inferior's list, and leave it on GDB's list. */
827 if (inferior_iter != inferior.end ())
829 inferior.erase (inferior_iter);
830 delete &*inferior_iter;
831 ++gdb_iter;
834 /* If it's not on the inferior's list, remove it from GDB's tables. */
835 else
837 /* Notify any observer that the shared object has been
838 unloaded before we remove it from GDB's tables. */
839 notify_solib_unloaded (current_program_space, *gdb_iter);
841 current_program_space->deleted_solibs.push_back (gdb_iter->so_name);
843 intrusive_list<solib>::iterator gdb_iter_next
844 = current_program_space->so_list.erase (gdb_iter);
846 /* Unless the user loaded it explicitly, free SO's objfile. */
847 if (gdb_iter->objfile != nullptr
848 && !(gdb_iter->objfile->flags & OBJF_USERLOADED)
849 && !solib_used (*gdb_iter))
850 gdb_iter->objfile->unlink ();
852 /* Some targets' section tables might be referring to
853 sections from so.abfd; remove them. */
854 current_program_space->remove_target_sections (&*gdb_iter);
856 delete &*gdb_iter;
857 gdb_iter = gdb_iter_next;
861 /* Now the inferior's list contains only shared objects that don't
862 appear in GDB's list --- those that are newly loaded. Add them
863 to GDB's shared object list. */
864 if (!inferior.empty ())
866 int not_found = 0;
867 const char *not_found_filename = NULL;
869 /* Fill in the rest of each of the `so' nodes. */
870 for (solib &new_so : inferior)
872 current_program_space->added_solibs.push_back (&new_so);
876 /* Fill in the rest of the `struct solib' node. */
877 if (!solib_map_sections (new_so))
879 not_found++;
880 if (not_found_filename == NULL)
881 not_found_filename = new_so.so_original_name.c_str ();
885 catch (const gdb_exception_error &e)
887 exception_fprintf (gdb_stderr, e,
888 _ ("Error while mapping shared "
889 "library sections:\n"));
892 /* Notify any observer that the shared object has been
893 loaded now that we've added it to GDB's tables. */
894 notify_solib_loaded (new_so);
897 /* Add the new shared objects to GDB's list. */
898 current_program_space->so_list.splice (std::move (inferior));
900 /* If a library was not found, issue an appropriate warning
901 message. We have to use a single call to warning in case the
902 front end does something special with warnings, e.g., pop up
903 a dialog box. It Would Be Nice if we could get a "warning: "
904 prefix on each line in the CLI front end, though - it doesn't
905 stand out well. */
907 if (not_found == 1)
908 warning (_ ("Could not load shared library symbols for %s.\n"
909 "Do you need \"set solib-search-path\" "
910 "or \"set sysroot\"?"),
911 not_found_filename);
912 else if (not_found > 1)
913 warning (_ ("\
914 Could not load shared library symbols for %d libraries, e.g. %s.\n\
915 Use the \"info sharedlibrary\" command to see the complete listing.\n\
916 Do you need \"set solib-search-path\" or \"set sysroot\"?"),
917 not_found, not_found_filename);
921 /* Return non-zero if NAME is the libpthread shared library.
923 Uses a fairly simplistic heuristic approach where we check
924 the file name against "/libpthread". This can lead to false
925 positives, but this should be good enough in practice.
927 As of glibc-2.34, functions formerly residing in libpthread have
928 been moved to libc, so "/libc." needs to be checked too. (Matching
929 the "." will avoid matching libraries such as libcrypt.) */
931 bool
932 libpthread_name_p (const char *name)
934 return (strstr (name, "/libpthread") != NULL
935 || strstr (name, "/libc.") != NULL);
938 /* Return non-zero if SO is the libpthread shared library. */
940 static bool
941 libpthread_solib_p (const solib &so)
943 return libpthread_name_p (so.so_name.c_str ());
946 /* Read in symbolic information for any shared objects whose names
947 match PATTERN. (If we've already read a shared object's symbol
948 info, leave it alone.) If PATTERN is zero, read them all.
950 If READSYMS is 0, defer reading symbolic information until later
951 but still do any needed low level processing.
953 FROM_TTY is described for update_solib_list, above. */
955 void
956 solib_add (const char *pattern, int from_tty, int readsyms)
958 if (print_symbol_loading_p (from_tty, 0, 0))
960 if (pattern != NULL)
962 gdb_printf (_ ("Loading symbols for shared libraries: %s\n"),
963 pattern);
965 else
966 gdb_printf (_ ("Loading symbols for shared libraries.\n"));
969 current_program_space->solib_add_generation++;
971 if (pattern)
973 char *re_err = re_comp (pattern);
975 if (re_err)
976 error (_ ("Invalid regexp: %s"), re_err);
979 update_solib_list (from_tty);
981 /* Walk the list of currently loaded shared libraries, and read
982 symbols for any that match the pattern --- or any whose symbols
983 aren't already loaded, if no pattern was given. */
985 bool any_matches = false;
986 bool loaded_any_symbols = false;
987 symfile_add_flags add_flags = SYMFILE_DEFER_BP_RESET;
989 if (from_tty)
990 add_flags |= SYMFILE_VERBOSE;
992 for (solib &gdb : current_program_space->solibs ())
993 if (!pattern || re_exec (gdb.so_name.c_str ()))
995 /* Normally, we would read the symbols from that library
996 only if READSYMS is set. However, we're making a small
997 exception for the pthread library, because we sometimes
998 need the library symbols to be loaded in order to provide
999 thread support (x86-linux for instance). */
1000 const int add_this_solib = (readsyms || libpthread_solib_p (gdb));
1002 any_matches = true;
1003 if (add_this_solib)
1005 if (gdb.symbols_loaded)
1007 /* If no pattern was given, be quiet for shared
1008 libraries we have already loaded. */
1009 if (pattern && (from_tty || info_verbose))
1010 gdb_printf (_ ("Symbols already loaded for %s\n"),
1011 gdb.so_name.c_str ());
1013 else if (solib_read_symbols (gdb, add_flags))
1014 loaded_any_symbols = true;
1018 if (loaded_any_symbols)
1019 breakpoint_re_set ();
1021 if (from_tty && pattern && !any_matches)
1022 gdb_printf ("No loaded shared libraries match the pattern `%s'.\n",
1023 pattern);
1025 if (loaded_any_symbols)
1027 /* Getting new symbols may change our opinion about what is
1028 frameless. */
1029 reinit_frame_cache ();
1034 /* Implement the "info sharedlibrary" command. Walk through the
1035 shared library list and print information about each attached
1036 library matching PATTERN. If PATTERN is elided, print them
1037 all. */
1039 static void
1040 info_sharedlibrary_command (const char *pattern, int from_tty)
1042 bool so_missing_debug_info = false;
1043 int addr_width;
1044 int nr_libs;
1045 gdbarch *gdbarch = current_inferior ()->arch ();
1046 struct ui_out *uiout = current_uiout;
1048 if (pattern)
1050 char *re_err = re_comp (pattern);
1052 if (re_err)
1053 error (_ ("Invalid regexp: %s"), re_err);
1056 /* "0x", a little whitespace, and two hex digits per byte of pointers. */
1057 addr_width = 4 + (gdbarch_ptr_bit (gdbarch) / 4);
1059 update_solib_list (from_tty);
1061 /* ui_out_emit_table table_emitter needs to know the number of rows,
1062 so we need to make two passes over the libs. */
1064 nr_libs = 0;
1065 for (const solib &so : current_program_space->solibs ())
1067 if (!so.so_name.empty ())
1069 if (pattern && !re_exec (so.so_name.c_str ()))
1070 continue;
1071 ++nr_libs;
1076 ui_out_emit_table table_emitter (uiout, 4, nr_libs, "SharedLibraryTable");
1078 /* The "- 1" is because ui_out adds one space between columns. */
1079 uiout->table_header (addr_width - 1, ui_left, "from", "From");
1080 uiout->table_header (addr_width - 1, ui_left, "to", "To");
1081 uiout->table_header (12 - 1, ui_left, "syms-read", "Syms Read");
1082 uiout->table_header (0, ui_noalign, "name", "Shared Object Library");
1084 uiout->table_body ();
1086 for (const solib &so : current_program_space->solibs ())
1088 if (so.so_name.empty ())
1089 continue;
1091 if (pattern && !re_exec (so.so_name.c_str ()))
1092 continue;
1094 ui_out_emit_tuple tuple_emitter (uiout, "lib");
1096 if (so.addr_high != 0)
1098 uiout->field_core_addr ("from", gdbarch, so.addr_low);
1099 uiout->field_core_addr ("to", gdbarch, so.addr_high);
1101 else
1103 uiout->field_skip ("from");
1104 uiout->field_skip ("to");
1107 if (!top_level_interpreter ()->interp_ui_out ()->is_mi_like_p ()
1108 && so.symbols_loaded && !objfile_has_symbols (so.objfile))
1110 so_missing_debug_info = true;
1111 uiout->field_string ("syms-read", "Yes (*)");
1113 else
1114 uiout->field_string ("syms-read", so.symbols_loaded ? "Yes" : "No");
1116 uiout->field_string ("name", so.so_name, file_name_style.style ());
1118 uiout->text ("\n");
1122 if (nr_libs == 0)
1124 if (pattern)
1125 uiout->message (_ ("No shared libraries matched.\n"));
1126 else
1127 uiout->message (_ ("No shared libraries loaded at this time.\n"));
1129 else
1131 if (so_missing_debug_info)
1132 uiout->message (_ ("(*): Shared library is missing "
1133 "debugging information.\n"));
1137 /* See solib.h. */
1139 bool
1140 solib_contains_address_p (const solib &solib, CORE_ADDR address)
1142 for (const target_section &p : solib.sections)
1143 if (p.addr <= address && address < p.endaddr)
1144 return true;
1146 return false;
1149 /* If ADDRESS is in a shared lib in program space PSPACE, return its
1150 name.
1152 Provides a hook for other gdb routines to discover whether or not a
1153 particular address is within the mapped address space of a shared
1154 library.
1156 For example, this routine is called at one point to disable
1157 breakpoints which are in shared libraries that are not currently
1158 mapped in. */
1160 const char *
1161 solib_name_from_address (struct program_space *pspace, CORE_ADDR address)
1163 for (const solib &so : pspace->so_list)
1164 if (solib_contains_address_p (so, address))
1165 return so.so_name.c_str ();
1167 return nullptr;
1170 /* See solib.h. */
1172 bool
1173 solib_keep_data_in_core (CORE_ADDR vaddr, unsigned long size)
1175 const solib_ops *ops = gdbarch_so_ops (current_inferior ()->arch ());
1177 if (ops->keep_data_in_core)
1178 return ops->keep_data_in_core (vaddr, size) != 0;
1179 else
1180 return false;
1183 /* See solib.h. */
1185 void
1186 clear_solib (program_space *pspace)
1188 const solib_ops *ops = gdbarch_so_ops (current_inferior ()->arch ());
1190 disable_breakpoints_in_shlibs (pspace);
1192 pspace->so_list.clear_and_dispose ([pspace] (solib *so) {
1193 notify_solib_unloaded (pspace, *so);
1194 pspace->remove_target_sections (so);
1195 delete so;
1198 if (ops->clear_solib != nullptr)
1199 ops->clear_solib (pspace);
1202 /* Shared library startup support. When GDB starts up the inferior,
1203 it nurses it along (through the shell) until it is ready to execute
1204 its first instruction. At this point, this function gets
1205 called. */
1207 void
1208 solib_create_inferior_hook (int from_tty)
1210 const solib_ops *ops = gdbarch_so_ops (current_inferior ()->arch ());
1212 ops->solib_create_inferior_hook (from_tty);
1215 /* See solib.h. */
1217 bool
1218 in_solib_dynsym_resolve_code (CORE_ADDR pc)
1220 const solib_ops *ops = gdbarch_so_ops (current_inferior ()->arch ());
1222 return ops->in_dynsym_resolve_code (pc) != 0;
1225 /* Implements the "sharedlibrary" command. */
1227 static void
1228 sharedlibrary_command (const char *args, int from_tty)
1230 dont_repeat ();
1231 solib_add (args, from_tty, 1);
1234 /* Implements the command "nosharedlibrary", which discards symbols
1235 that have been auto-loaded from shared libraries. Symbols from
1236 shared libraries that were added by explicit request of the user
1237 are not discarded. Also called from remote.c. */
1239 void
1240 no_shared_libraries (const char *ignored, int from_tty)
1242 /* The order of the two routines below is important: clear_solib notifies
1243 the solib_unloaded observers, and some of these observers might need
1244 access to their associated objfiles. Therefore, we can not purge the
1245 solibs' objfiles before clear_solib has been called. */
1247 clear_solib (current_program_space);
1248 objfile_purge_solibs ();
1251 /* See solib.h. */
1253 void
1254 update_solib_breakpoints (void)
1256 const solib_ops *ops = gdbarch_so_ops (current_inferior ()->arch ());
1258 if (ops->update_breakpoints != NULL)
1259 ops->update_breakpoints ();
1262 /* See solib.h. */
1264 void
1265 handle_solib_event (void)
1267 const solib_ops *ops = gdbarch_so_ops (current_inferior ()->arch ());
1269 if (ops->handle_event != NULL)
1270 ops->handle_event ();
1272 current_inferior ()->pspace->clear_solib_cache ();
1274 /* Check for any newly added shared libraries if we're supposed to
1275 be adding them automatically. Switch terminal for any messages
1276 produced by breakpoint_re_set. */
1277 target_terminal::ours_for_output ();
1278 solib_add (NULL, 0, auto_solib_add);
1279 target_terminal::inferior ();
1282 /* Reload shared libraries, but avoid reloading the same symbol file
1283 we already have loaded. */
1285 static void
1286 reload_shared_libraries_1 (int from_tty)
1288 if (print_symbol_loading_p (from_tty, 0, 0))
1289 gdb_printf (_ ("Loading symbols for shared libraries.\n"));
1291 for (solib &so : current_program_space->solibs ())
1293 const char *found_pathname = NULL;
1294 bool was_loaded = so.symbols_loaded != 0;
1295 symfile_add_flags add_flags = SYMFILE_DEFER_BP_RESET;
1297 if (from_tty)
1298 add_flags |= SYMFILE_VERBOSE;
1300 gdb::unique_xmalloc_ptr<char> filename (
1301 tilde_expand (so.so_original_name.c_str ()));
1302 gdb_bfd_ref_ptr abfd (solib_bfd_open (filename.get ()));
1303 if (abfd != NULL)
1304 found_pathname = bfd_get_filename (abfd.get ());
1306 /* If this shared library is no longer associated with its previous
1307 symbol file, close that. */
1308 if ((found_pathname == NULL && was_loaded)
1309 || (found_pathname != NULL
1310 && filename_cmp (found_pathname, so.so_name.c_str ()) != 0))
1312 if (so.objfile && !(so.objfile->flags & OBJF_USERLOADED)
1313 && !solib_used (so))
1314 so.objfile->unlink ();
1315 current_program_space->remove_target_sections (&so);
1316 so.clear ();
1319 /* If this shared library is now associated with a new symbol
1320 file, open it. */
1321 if (found_pathname != NULL
1322 && (!was_loaded
1323 || filename_cmp (found_pathname, so.so_name.c_str ()) != 0))
1325 bool got_error = false;
1329 solib_map_sections (so);
1332 catch (const gdb_exception_error &e)
1334 exception_fprintf (gdb_stderr, e,
1335 _ ("Error while mapping "
1336 "shared library sections:\n"));
1337 got_error = true;
1340 if (!got_error
1341 && (auto_solib_add || was_loaded || libpthread_solib_p (so)))
1342 solib_read_symbols (so, add_flags);
1347 static void
1348 reload_shared_libraries (const char *ignored, int from_tty,
1349 struct cmd_list_element *e)
1351 reload_shared_libraries_1 (from_tty);
1353 const solib_ops *ops = gdbarch_so_ops (current_inferior ()->arch ());
1355 /* Creating inferior hooks here has two purposes. First, if we reload
1356 shared libraries then the address of solib breakpoint we've computed
1357 previously might be no longer valid. For example, if we forgot to set
1358 solib-absolute-prefix and are setting it right now, then the previous
1359 breakpoint address is plain wrong. Second, installing solib hooks
1360 also implicitly figures were ld.so is and loads symbols for it.
1361 Absent this call, if we've just connected to a target and set
1362 solib-absolute-prefix or solib-search-path, we'll lose all information
1363 about ld.so. */
1364 if (target_has_execution ())
1366 /* Reset or free private data structures not associated with
1367 so_list entries. */
1368 if (ops->clear_solib != nullptr)
1369 ops->clear_solib (current_program_space);
1371 /* Remove any previous solib event breakpoint. This is usually
1372 done in common code, at breakpoint_init_inferior time, but
1373 we're not really starting up the inferior here. */
1374 remove_solib_event_breakpoints ();
1376 solib_create_inferior_hook (from_tty);
1379 /* Sometimes the platform-specific hook loads initial shared
1380 libraries, and sometimes it doesn't. If it doesn't FROM_TTY will be
1381 incorrectly 0 but such solib targets should be fixed anyway. If we
1382 made all the inferior hook methods consistent, this call could be
1383 removed. Call it only after the solib target has been initialized by
1384 solib_create_inferior_hook. */
1386 solib_add (NULL, 0, auto_solib_add);
1388 breakpoint_re_set ();
1390 /* We may have loaded or unloaded debug info for some (or all)
1391 shared libraries. However, frames may still reference them. For
1392 example, a frame's unwinder might still point at DWARF FDE
1393 structures that are now freed. Also, getting new symbols may
1394 change our opinion about what is frameless. */
1395 reinit_frame_cache ();
1398 /* Wrapper for reload_shared_libraries that replaces "remote:"
1399 at the start of gdb_sysroot with "target:". */
1401 static void
1402 gdb_sysroot_changed (const char *ignored, int from_tty,
1403 struct cmd_list_element *e)
1405 const char *old_prefix = "remote:";
1406 const char *new_prefix = TARGET_SYSROOT_PREFIX;
1408 if (startswith (gdb_sysroot.c_str (), old_prefix))
1410 static bool warning_issued = false;
1412 gdb_assert (strlen (old_prefix) == strlen (new_prefix));
1413 gdb_sysroot = new_prefix + gdb_sysroot.substr (strlen (old_prefix));
1415 if (!warning_issued)
1417 warning (_ ("\"%s\" is deprecated, use \"%s\" instead."), old_prefix,
1418 new_prefix);
1419 warning (_ ("sysroot set to \"%s\"."), gdb_sysroot.c_str ());
1421 warning_issued = true;
1425 reload_shared_libraries (ignored, from_tty, e);
1428 static void
1429 show_auto_solib_add (struct ui_file *file, int from_tty,
1430 struct cmd_list_element *c, const char *value)
1432 gdb_printf (file, _ ("Autoloading of shared library symbols is %s.\n"),
1433 value);
1436 /* Lookup the value for a specific symbol from dynamic symbol table. Look
1437 up symbol from ABFD. MATCH_SYM is a callback function to determine
1438 whether to pick up a symbol. DATA is the input of this callback
1439 function. Return 0 if symbol is not found. */
1441 CORE_ADDR
1442 gdb_bfd_lookup_symbol_from_symtab (
1443 bfd *abfd, gdb::function_view<bool (const asymbol *)> match_sym)
1445 long storage_needed = bfd_get_symtab_upper_bound (abfd);
1446 CORE_ADDR symaddr = 0;
1448 if (storage_needed > 0)
1450 unsigned int i;
1452 gdb::def_vector<asymbol *> storage (storage_needed / sizeof (asymbol *));
1453 asymbol **symbol_table = storage.data ();
1454 unsigned int number_of_symbols
1455 = bfd_canonicalize_symtab (abfd, symbol_table);
1457 for (i = 0; i < number_of_symbols; i++)
1459 asymbol *sym = *symbol_table++;
1461 if (match_sym (sym))
1463 gdbarch *gdbarch = current_inferior ()->arch ();
1464 symaddr = sym->value;
1466 /* Some ELF targets fiddle with addresses of symbols they
1467 consider special. They use minimal symbols to do that
1468 and this is needed for correct breakpoint placement,
1469 but we do not have full data here to build a complete
1470 minimal symbol, so just set the address and let the
1471 targets cope with that. */
1472 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
1473 && gdbarch_elf_make_msymbol_special_p (gdbarch))
1475 struct minimal_symbol msym
1479 msym.set_value_address (symaddr);
1480 gdbarch_elf_make_msymbol_special (gdbarch, sym, &msym);
1481 symaddr = CORE_ADDR (msym.unrelocated_address ());
1484 /* BFD symbols are section relative. */
1485 symaddr += sym->section->vma;
1486 break;
1491 return symaddr;
1494 /* See solib.h. */
1497 gdb_bfd_scan_elf_dyntag (const int desired_dyntag, bfd *abfd, CORE_ADDR *ptr,
1498 CORE_ADDR *ptr_addr)
1500 int arch_size, step;
1501 bfd_size_type sect_size;
1502 long current_dyntag;
1503 CORE_ADDR dyn_ptr, dyn_addr;
1504 gdb_byte *bufend, *bufstart, *buf;
1505 Elf32_External_Dyn *x_dynp_32;
1506 Elf64_External_Dyn *x_dynp_64;
1507 struct bfd_section *sect;
1509 if (abfd == NULL)
1510 return 0;
1512 if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
1513 return 0;
1515 arch_size = bfd_get_arch_size (abfd);
1516 if (arch_size == -1)
1517 return 0;
1519 /* Find the start address of the .dynamic section. */
1520 sect = bfd_get_section_by_name (abfd, ".dynamic");
1521 if (sect == NULL)
1522 return 0;
1524 bool found = false;
1525 for (const target_section &target_section :
1526 current_program_space->target_sections ())
1527 if (sect == target_section.the_bfd_section)
1529 dyn_addr = target_section.addr;
1530 found = true;
1531 break;
1533 if (!found)
1535 /* ABFD may come from OBJFILE acting only as a symbol file without being
1536 loaded into the target (see add_symbol_file_command). This case is
1537 such fallback to the file VMA address without the possibility of
1538 having the section relocated to its actual in-memory address. */
1540 dyn_addr = bfd_section_vma (sect);
1543 /* Read in .dynamic from the BFD. We will get the actual value
1544 from memory later. */
1545 sect_size = bfd_section_size (sect);
1546 gdb::byte_vector buffer (sect_size);
1547 buf = bufstart = buffer.data ();
1548 if (!bfd_get_section_contents (abfd, sect,
1549 buf, 0, sect_size))
1550 return 0;
1552 /* Iterate over BUF and scan for DYNTAG. If found, set PTR and return. */
1553 step = (arch_size == 32) ? sizeof (Elf32_External_Dyn)
1554 : sizeof (Elf64_External_Dyn);
1555 for (bufend = buf + sect_size; buf < bufend; buf += step)
1557 if (arch_size == 32)
1559 x_dynp_32 = (Elf32_External_Dyn *) buf;
1560 current_dyntag = bfd_h_get_32 (abfd, (bfd_byte *) x_dynp_32->d_tag);
1561 dyn_ptr = bfd_h_get_32 (abfd, (bfd_byte *) x_dynp_32->d_un.d_ptr);
1563 else
1565 x_dynp_64 = (Elf64_External_Dyn *) buf;
1566 current_dyntag = bfd_h_get_64 (abfd, (bfd_byte *) x_dynp_64->d_tag);
1567 dyn_ptr = bfd_h_get_64 (abfd, (bfd_byte *) x_dynp_64->d_un.d_ptr);
1569 if (current_dyntag == DT_NULL)
1570 return 0;
1571 if (current_dyntag == desired_dyntag)
1573 /* If requested, try to read the runtime value of this .dynamic
1574 entry. */
1575 if (ptr)
1577 struct type *ptr_type;
1578 gdb_byte ptr_buf[8];
1579 CORE_ADDR ptr_addr_1;
1581 ptr_type = builtin_type (current_inferior ()->arch ())
1582 ->builtin_data_ptr;
1583 ptr_addr_1 = dyn_addr + (buf - bufstart) + arch_size / 8;
1584 if (target_read_memory (ptr_addr_1, ptr_buf, arch_size / 8) == 0)
1585 dyn_ptr = extract_typed_address (ptr_buf, ptr_type);
1586 *ptr = dyn_ptr;
1587 if (ptr_addr)
1588 *ptr_addr = dyn_addr + (buf - bufstart);
1590 return 1;
1594 return 0;
1597 /* See solib.h. */
1599 gdb::unique_xmalloc_ptr<char>
1600 gdb_bfd_read_elf_soname (const char *filename)
1602 gdb_bfd_ref_ptr abfd = gdb_bfd_open (filename, gnutarget);
1604 if (abfd == nullptr)
1605 return {};
1607 /* Check that ABFD is an ET_DYN ELF file. */
1608 if (!bfd_check_format (abfd.get (), bfd_object)
1609 || !(bfd_get_file_flags (abfd.get ()) & DYNAMIC))
1610 return {};
1612 CORE_ADDR idx;
1613 if (!gdb_bfd_scan_elf_dyntag (DT_SONAME, abfd.get (), &idx, nullptr))
1614 return {};
1616 struct bfd_section *dynstr
1617 = bfd_get_section_by_name (abfd.get (), ".dynstr");
1618 int sect_size = bfd_section_size (dynstr);
1619 if (dynstr == nullptr || sect_size <= idx)
1620 return {};
1622 /* Read soname from the string table. */
1623 gdb::byte_vector dynstr_buf;
1624 if (!gdb_bfd_get_full_section_contents (abfd.get (), dynstr, &dynstr_buf))
1625 return {};
1627 /* Ensure soname is null-terminated before returning a copy. */
1628 char *soname = (char *) dynstr_buf.data () + idx;
1629 if (strnlen (soname, sect_size - idx) == sect_size - idx)
1630 return {};
1632 return make_unique_xstrdup (soname);
1635 /* Lookup the value for a specific symbol from symbol table. Look up symbol
1636 from ABFD. MATCH_SYM is a callback function to determine whether to pick
1637 up a symbol. DATA is the input of this callback function. Return 0
1638 if symbol is not found. */
1640 static CORE_ADDR
1641 bfd_lookup_symbol_from_dyn_symtab (
1642 bfd *abfd, gdb::function_view<bool (const asymbol *)> match_sym)
1644 long storage_needed = bfd_get_dynamic_symtab_upper_bound (abfd);
1645 CORE_ADDR symaddr = 0;
1647 if (storage_needed > 0)
1649 unsigned int i;
1650 gdb::def_vector<asymbol *> storage (storage_needed / sizeof (asymbol *));
1651 asymbol **symbol_table = storage.data ();
1652 unsigned int number_of_symbols
1653 = bfd_canonicalize_dynamic_symtab (abfd, symbol_table);
1655 for (i = 0; i < number_of_symbols; i++)
1657 asymbol *sym = *symbol_table++;
1659 if (match_sym (sym))
1661 /* BFD symbols are section relative. */
1662 symaddr = sym->value + sym->section->vma;
1663 break;
1667 return symaddr;
1670 /* Lookup the value for a specific symbol from symbol table and dynamic
1671 symbol table. Look up symbol from ABFD. MATCH_SYM is a callback
1672 function to determine whether to pick up a symbol. DATA is the
1673 input of this callback function. Return 0 if symbol is not
1674 found. */
1676 CORE_ADDR
1677 gdb_bfd_lookup_symbol (bfd *abfd,
1678 gdb::function_view<bool (const asymbol *)> match_sym)
1680 CORE_ADDR symaddr = gdb_bfd_lookup_symbol_from_symtab (abfd, match_sym);
1682 /* On FreeBSD, the dynamic linker is stripped by default. So we'll
1683 have to check the dynamic string table too. */
1684 if (symaddr == 0)
1685 symaddr = bfd_lookup_symbol_from_dyn_symtab (abfd, match_sym);
1687 return symaddr;
1690 /* The shared library list may contain user-loaded object files that
1691 can be removed out-of-band by the user. So upon notification of
1692 free_objfile remove all references to any user-loaded file that is
1693 about to be freed. */
1695 static void
1696 remove_user_added_objfile (struct objfile *objfile)
1698 if (objfile->flags & OBJF_USERLOADED)
1700 for (solib &so : objfile->pspace->solibs ())
1701 if (so.objfile == objfile)
1702 so.objfile = nullptr;
1706 void _initialize_solib ();
1708 void
1709 _initialize_solib ()
1711 gdb::observers::free_objfile.attach (remove_user_added_objfile, "solib");
1712 gdb::observers::inferior_execd.attach (
1713 [] (inferior *exec_inf, inferior *follow_inf) {
1714 solib_create_inferior_hook (0);
1716 "solib");
1718 add_com (
1719 "sharedlibrary", class_files, sharedlibrary_command,
1720 _ ("Load shared object library symbols for files matching REGEXP."));
1721 cmd_list_element *info_sharedlibrary_cmd
1722 = add_info ("sharedlibrary", info_sharedlibrary_command,
1723 _ ("Status of loaded shared object libraries."));
1724 add_info_alias ("dll", info_sharedlibrary_cmd, 1);
1725 add_com ("nosharedlibrary", class_files, no_shared_libraries,
1726 _ ("Unload all shared object library symbols."));
1728 add_setshow_boolean_cmd ("auto-solib-add", class_support, &auto_solib_add,
1729 _ ("\
1730 Set autoloading of shared library symbols."),
1731 _ ("\
1732 Show autoloading of shared library symbols."),
1733 _ ("\
1734 If \"on\", symbols from all shared object libraries will be loaded\n\
1735 automatically when the inferior begins execution, when the dynamic linker\n\
1736 informs gdb that a new library has been loaded, or when attaching to the\n\
1737 inferior. Otherwise, symbols must be loaded manually, using \
1738 `sharedlibrary'."),
1739 NULL, show_auto_solib_add, &setlist, &showlist);
1741 set_show_commands sysroot_cmds
1742 = add_setshow_optional_filename_cmd ("sysroot", class_support,
1743 &gdb_sysroot, _ ("\
1744 Set an alternate system root."),
1745 _ ("\
1746 Show the current system root."),
1747 _ ("\
1748 The system root is used to load absolute shared library symbol files.\n\
1749 For other (relative) files, you can add directories using\n\
1750 `set solib-search-path'."),
1751 gdb_sysroot_changed, NULL, &setlist,
1752 &showlist);
1754 add_alias_cmd ("solib-absolute-prefix", sysroot_cmds.set, class_support, 0,
1755 &setlist);
1756 add_alias_cmd ("solib-absolute-prefix", sysroot_cmds.show, class_support, 0,
1757 &showlist);
1759 add_setshow_optional_filename_cmd ("solib-search-path", class_support,
1760 &solib_search_path, _ ("\
1761 Set the search path for loading non-absolute shared library symbol files."),
1762 _ ("\
1763 Show the search path for loading non-absolute shared library symbol files."),
1764 _ ("\
1765 This takes precedence over the environment variables \
1766 PATH and LD_LIBRARY_PATH."),
1767 reload_shared_libraries,
1768 show_solib_search_path, &setlist,
1769 &showlist);
1771 add_setshow_boolean_cmd ("solib", class_maintenance, &debug_solib, _ ("\
1772 Set solib debugging."),
1773 _ ("\
1774 Show solib debugging."),
1775 _ ("\
1776 When true, solib-related debugging output is enabled."),
1777 nullptr, nullptr, &setdebuglist, &showdebuglist);