xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/solib.c (revision 8b657b0747480f8989760d71343d6dd33f8d4cf9)
1 /* Handle shared libraries for GDB, the GNU Debugger.
2 
3    Copyright (C) 1990-2023 Free Software Foundation, Inc.
4 
5    This file is part of GDB.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19 
20 #include "defs.h"
21 
22 #include <sys/types.h>
23 #include <fcntl.h>
24 #include "symtab.h"
25 #include "bfd.h"
26 #include "build-id.h"
27 #include "symfile.h"
28 #include "objfiles.h"
29 #include "gdbcore.h"
30 #include "command.h"
31 #include "target.h"
32 #include "frame.h"
33 #include "gdbsupport/gdb_regex.h"
34 #include "inferior.h"
35 #include "gdbsupport/environ.h"
36 #include "language.h"
37 #include "gdbcmd.h"
38 #include "completer.h"
39 #include "elf/external.h"
40 #include "elf/common.h"
41 #include "filenames.h"		/* for DOSish file names */
42 #include "exec.h"
43 #include "solist.h"
44 #include "observable.h"
45 #include "readline/tilde.h"
46 #include "remote.h"
47 #include "solib.h"
48 #include "interps.h"
49 #include "filesystem.h"
50 #include "gdb_bfd.h"
51 #include "gdbsupport/filestuff.h"
52 #include "gdbsupport/scoped_fd.h"
53 #include "debuginfod-support.h"
54 #include "source.h"
55 #include "cli/cli-style.h"
56 #include "solib-target.h"
57 
58 /* See solib.h.  */
59 
60 bool debug_solib;
61 
62 /* If non-empty, this is a search path for loading non-absolute shared library
63    symbol files.  This takes precedence over the environment variables PATH
64    and LD_LIBRARY_PATH.  */
65 static std::string solib_search_path;
66 static void
67 show_solib_search_path (struct ui_file *file, int from_tty,
68 			struct cmd_list_element *c, const char *value)
69 {
70   gdb_printf (file, _("The search path for loading non-absolute "
71 		      "shared library symbol files is %s.\n"),
72 	      value);
73 }
74 
75 /* Same as HAVE_DOS_BASED_FILE_SYSTEM, but useable as an rvalue.  */
76 #if (HAVE_DOS_BASED_FILE_SYSTEM)
77 #  define DOS_BASED_FILE_SYSTEM 1
78 #else
79 #  define DOS_BASED_FILE_SYSTEM 0
80 #endif
81 
82 /* Return the full pathname of a binary file (the main executable or a
83    shared library file), or NULL if not found.  If FD is non-NULL, *FD
84    is set to either -1 or an open file handle for the binary file.
85 
86    Global variable GDB_SYSROOT is used as a prefix directory
87    to search for binary files if they have an absolute path.
88    If GDB_SYSROOT starts with "target:" and target filesystem
89    is the local filesystem then the "target:" prefix will be
90    stripped before the search starts.  This ensures that the
91    same search algorithm is used for local files regardless of
92    whether a "target:" prefix was used.
93 
94    Global variable SOLIB_SEARCH_PATH is used as a prefix directory
95    (or set of directories, as in LD_LIBRARY_PATH) to search for all
96    shared libraries if not found in either the sysroot (if set) or
97    the local filesystem.  SOLIB_SEARCH_PATH is not used when searching
98    for the main executable.
99 
100    Search algorithm:
101    * If a sysroot is set and path is absolute:
102    *   Search for sysroot/path.
103    * else
104    *   Look for it literally (unmodified).
105    * If IS_SOLIB is non-zero:
106    *   Look in SOLIB_SEARCH_PATH.
107    *   If available, use target defined search function.
108    * If NO sysroot is set, perform the following two searches:
109    *   Look in inferior's $PATH.
110    *   If IS_SOLIB is non-zero:
111    *     Look in inferior's $LD_LIBRARY_PATH.
112    *
113    * The last check avoids doing this search when targeting remote
114    * machines since a sysroot will almost always be set.
115 */
116 
117 static gdb::unique_xmalloc_ptr<char>
118 solib_find_1 (const char *in_pathname, int *fd, bool is_solib)
119 {
120   const struct target_so_ops *ops = gdbarch_so_ops (target_gdbarch ());
121   int found_file = -1;
122   gdb::unique_xmalloc_ptr<char> temp_pathname;
123   const char *fskind = effective_target_file_system_kind ();
124   const char *sysroot = gdb_sysroot.c_str ();
125   int prefix_len, orig_prefix_len;
126 
127   /* If the absolute prefix starts with "target:" but the filesystem
128      accessed by the target_fileio_* methods is the local filesystem
129      then we strip the "target:" prefix now and work with the local
130      filesystem.  This ensures that the same search algorithm is used
131      for all local files regardless of whether a "target:" prefix was
132      used.  */
133   if (is_target_filename (sysroot) && target_filesystem_is_local ())
134     sysroot += strlen (TARGET_SYSROOT_PREFIX);
135 
136   /* Strip any trailing slashes from the absolute prefix.  */
137   prefix_len = orig_prefix_len = strlen (sysroot);
138 
139   while (prefix_len > 0 && IS_DIR_SEPARATOR (sysroot[prefix_len - 1]))
140     prefix_len--;
141 
142   std::string sysroot_holder;
143   if (prefix_len == 0)
144     sysroot = NULL;
145   else if (prefix_len != orig_prefix_len)
146     {
147       sysroot_holder = std::string (sysroot, prefix_len);
148       sysroot = sysroot_holder.c_str ();
149     }
150 
151   /* If we're on a non-DOS-based system, backslashes won't be
152      understood as directory separator, so, convert them to forward
153      slashes, iff we're supposed to handle DOS-based file system
154      semantics for target paths.  */
155   if (!DOS_BASED_FILE_SYSTEM && fskind == file_system_kind_dos_based)
156     {
157       char *p;
158 
159       /* Avoid clobbering our input.  */
160       p = (char *) alloca (strlen (in_pathname) + 1);
161       strcpy (p, in_pathname);
162       in_pathname = p;
163 
164       for (; *p; p++)
165 	{
166 	  if (*p == '\\')
167 	    *p = '/';
168 	}
169     }
170 
171   /* Note, we're interested in IS_TARGET_ABSOLUTE_PATH, not
172      IS_ABSOLUTE_PATH.  The latter is for host paths only, while
173      IN_PATHNAME is a target path.  For example, if we're supposed to
174      be handling DOS-like semantics we want to consider a
175      'c:/foo/bar.dll' path as an absolute path, even on a Unix box.
176      With such a path, before giving up on the sysroot, we'll try:
177 
178        1st attempt, c:/foo/bar.dll ==> /sysroot/c:/foo/bar.dll
179        2nd attempt, c:/foo/bar.dll ==> /sysroot/c/foo/bar.dll
180        3rd attempt, c:/foo/bar.dll ==> /sysroot/foo/bar.dll
181   */
182 
183   if (!IS_TARGET_ABSOLUTE_PATH (fskind, in_pathname) || sysroot == NULL)
184     temp_pathname.reset (xstrdup (in_pathname));
185   else
186     {
187       bool need_dir_separator;
188 
189       /* Concatenate the sysroot and the target reported filename.  We
190 	 may need to glue them with a directory separator.  Cases to
191 	 consider:
192 
193 	| sysroot         | separator | in_pathname    |
194 	|-----------------+-----------+----------------|
195 	| /some/dir       | /         | c:/foo/bar.dll |
196 	| /some/dir       |           | /foo/bar.dll   |
197 	| target:         |           | c:/foo/bar.dll |
198 	| target:         |           | /foo/bar.dll   |
199 	| target:some/dir | /         | c:/foo/bar.dll |
200 	| target:some/dir |           | /foo/bar.dll   |
201 
202 	IOW, we don't need to add a separator if IN_PATHNAME already
203 	has one, or when the sysroot is exactly "target:".
204 	There's no need to check for drive spec explicitly, as we only
205 	get here if IN_PATHNAME is considered an absolute path.  */
206       need_dir_separator = !(IS_DIR_SEPARATOR (in_pathname[0])
207 			     || strcmp (TARGET_SYSROOT_PREFIX, sysroot) == 0);
208 
209       /* Cat the prefixed pathname together.  */
210       temp_pathname.reset (concat (sysroot,
211 				   need_dir_separator ? SLASH_STRING : "",
212 				   in_pathname, (char *) NULL));
213     }
214 
215   /* Handle files to be accessed via the target.  */
216   if (is_target_filename (temp_pathname.get ()))
217     {
218       if (fd != NULL)
219 	*fd = -1;
220       return temp_pathname;
221     }
222 
223   /* Now see if we can open it.  */
224   found_file = gdb_open_cloexec (temp_pathname.get (),
225 				 O_RDONLY | O_BINARY, 0).release ();
226 
227   /* If the search in gdb_sysroot failed, and the path name has a
228      drive spec (e.g, c:/foo), try stripping ':' from the drive spec,
229      and retrying in the sysroot:
230        c:/foo/bar.dll ==> /sysroot/c/foo/bar.dll.  */
231 
232   if (found_file < 0
233       && sysroot != NULL
234       && HAS_TARGET_DRIVE_SPEC (fskind, in_pathname))
235     {
236       bool need_dir_separator = !IS_DIR_SEPARATOR (in_pathname[2]);
237       char drive[2] = { in_pathname[0], '\0' };
238 
239       temp_pathname.reset (concat (sysroot,
240 				   SLASH_STRING,
241 				   drive,
242 				   need_dir_separator ? SLASH_STRING : "",
243 				   in_pathname + 2, (char *) NULL));
244 
245       found_file = gdb_open_cloexec (temp_pathname.get (),
246 				     O_RDONLY | O_BINARY, 0).release ();
247       if (found_file < 0)
248 	{
249 	  /* If the search in gdb_sysroot still failed, try fully
250 	     stripping the drive spec, and trying once more in the
251 	     sysroot before giving up.
252 
253 	     c:/foo/bar.dll ==> /sysroot/foo/bar.dll.  */
254 
255 	  temp_pathname.reset (concat (sysroot,
256 				       need_dir_separator ? SLASH_STRING : "",
257 				       in_pathname + 2, (char *) NULL));
258 
259 	  found_file = gdb_open_cloexec (temp_pathname.get (),
260 					 O_RDONLY | O_BINARY, 0).release ();
261 	}
262     }
263 
264   /* We try to find the library in various ways.  After each attempt,
265      either found_file >= 0 and temp_pathname is a malloc'd string, or
266      found_file < 0 and temp_pathname does not point to storage that
267      needs to be freed.  */
268 
269   if (found_file < 0)
270     temp_pathname.reset (NULL);
271 
272   /* If the search in gdb_sysroot failed, and the path name is
273      absolute at this point, make it relative.  (openp will try and open the
274      file according to its absolute path otherwise, which is not what we want.)
275      Affects subsequent searches for this solib.  */
276   if (found_file < 0 && IS_TARGET_ABSOLUTE_PATH (fskind, in_pathname))
277     {
278       /* First, get rid of any drive letters etc.  */
279       while (!IS_TARGET_DIR_SEPARATOR (fskind, *in_pathname))
280 	in_pathname++;
281 
282       /* Next, get rid of all leading dir separators.  */
283       while (IS_TARGET_DIR_SEPARATOR (fskind, *in_pathname))
284 	in_pathname++;
285     }
286 
287   /* If not found, and we're looking for a solib, search the
288      solib_search_path (if any).  */
289   if (is_solib && found_file < 0 && !solib_search_path.empty ())
290     found_file = openp (solib_search_path.c_str (),
291 			OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH,
292 			in_pathname, O_RDONLY | O_BINARY, &temp_pathname);
293 
294   /* If not found, and we're looking for a solib, next search the
295      solib_search_path (if any) for the basename only (ignoring the
296      path).  This is to allow reading solibs from a path that differs
297      from the opened path.  */
298   if (is_solib && found_file < 0 && !solib_search_path.empty ())
299     found_file = openp (solib_search_path.c_str (),
300 			OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH,
301 			target_lbasename (fskind, in_pathname),
302 			O_RDONLY | O_BINARY, &temp_pathname);
303 
304   /* If not found, and we're looking for a solib, try to use target
305      supplied solib search method.  */
306   if (is_solib && found_file < 0 && ops->find_and_open_solib)
307     found_file = ops->find_and_open_solib (in_pathname, O_RDONLY | O_BINARY,
308 					   &temp_pathname);
309 
310   /* If not found, next search the inferior's $PATH environment variable.  */
311   if (found_file < 0 && sysroot == NULL)
312     found_file = openp (current_inferior ()->environment.get ("PATH"),
313 			OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH, in_pathname,
314 			O_RDONLY | O_BINARY, &temp_pathname);
315 
316   /* If not found, and we're looking for a solib, next search the
317      inferior's $LD_LIBRARY_PATH environment variable.  */
318   if (is_solib && found_file < 0 && sysroot == NULL)
319     found_file = openp (current_inferior ()->environment.get
320 			("LD_LIBRARY_PATH"),
321 			OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH, in_pathname,
322 			O_RDONLY | O_BINARY, &temp_pathname);
323 
324   if (fd == NULL)
325     {
326       if (found_file >= 0)
327 	close (found_file);
328     }
329   else
330     *fd = found_file;
331 
332   return temp_pathname;
333 }
334 
335 /* Return the full pathname of the main executable, or NULL if not
336    found.  If FD is non-NULL, *FD is set to either -1 or an open file
337    handle for the main executable.  */
338 
339 gdb::unique_xmalloc_ptr<char>
340 exec_file_find (const char *in_pathname, int *fd)
341 {
342   gdb::unique_xmalloc_ptr<char> result;
343   const char *fskind = effective_target_file_system_kind ();
344 
345   if (in_pathname == NULL)
346     return NULL;
347 
348   if (!gdb_sysroot.empty () && IS_TARGET_ABSOLUTE_PATH (fskind, in_pathname))
349     {
350       result = solib_find_1 (in_pathname, fd, false);
351 
352       if (result == NULL && fskind == file_system_kind_dos_based)
353 	{
354 	  char *new_pathname;
355 
356 	  new_pathname = (char *) alloca (strlen (in_pathname) + 5);
357 	  strcpy (new_pathname, in_pathname);
358 	  strcat (new_pathname, ".exe");
359 
360 	  result = solib_find_1 (new_pathname, fd, false);
361 	}
362     }
363   else
364     {
365       /* It's possible we don't have a full path, but rather just a
366 	 filename.  Some targets, such as HP-UX, don't provide the
367 	 full path, sigh.
368 
369 	 Attempt to qualify the filename against the source path.
370 	 (If that fails, we'll just fall back on the original
371 	 filename.  Not much more we can do...)  */
372 
373       if (!source_full_path_of (in_pathname, &result))
374 	result.reset (xstrdup (in_pathname));
375       if (fd != NULL)
376 	*fd = -1;
377     }
378 
379   return result;
380 }
381 
382 /* Return the full pathname of a shared library file, or NULL if not
383    found.  If FD is non-NULL, *FD is set to either -1 or an open file
384    handle for the shared library.
385 
386    The search algorithm used is described in solib_find_1's comment
387    above.  */
388 
389 gdb::unique_xmalloc_ptr<char>
390 solib_find (const char *in_pathname, int *fd)
391 {
392   const char *solib_symbols_extension
393     = gdbarch_solib_symbols_extension (target_gdbarch ());
394 
395   /* If solib_symbols_extension is set, replace the file's
396      extension.  */
397   if (solib_symbols_extension != NULL)
398     {
399       const char *p = in_pathname + strlen (in_pathname);
400 
401       while (p > in_pathname && *p != '.')
402 	p--;
403 
404       if (*p == '.')
405 	{
406 	  char *new_pathname;
407 
408 	  new_pathname
409 	    = (char *) alloca (p - in_pathname + 1
410 			       + strlen (solib_symbols_extension) + 1);
411 	  memcpy (new_pathname, in_pathname, p - in_pathname + 1);
412 	  strcpy (new_pathname + (p - in_pathname) + 1,
413 		  solib_symbols_extension);
414 
415 	  in_pathname = new_pathname;
416 	}
417     }
418 
419   return solib_find_1 (in_pathname, fd, true);
420 }
421 
422 /* Open and return a BFD for the shared library PATHNAME.  If FD is not -1,
423    it is used as file handle to open the file.  Throws an error if the file
424    could not be opened.  Handles both local and remote file access.
425 
426    If unsuccessful, the FD will be closed (unless FD was -1).  */
427 
428 gdb_bfd_ref_ptr
429 solib_bfd_fopen (const char *pathname, int fd)
430 {
431   gdb_bfd_ref_ptr abfd (gdb_bfd_open (pathname, gnutarget, fd));
432 
433   if (abfd != NULL && !gdb_bfd_has_target_filename (abfd.get ()))
434     bfd_set_cacheable (abfd.get (), 1);
435 
436   if (abfd == NULL)
437     {
438       /* Arrange to free PATHNAME when the error is thrown.  */
439       error (_("Could not open `%s' as an executable file: %s"),
440 	     pathname, bfd_errmsg (bfd_get_error ()));
441     }
442 
443   return abfd;
444 }
445 
446 /* Find shared library PATHNAME and open a BFD for it.  */
447 
448 gdb_bfd_ref_ptr
449 solib_bfd_open (const char *pathname)
450 {
451   int found_file;
452   const struct bfd_arch_info *b;
453 
454   /* Search for shared library file.  */
455   gdb::unique_xmalloc_ptr<char> found_pathname
456     = solib_find (pathname, &found_file);
457   if (found_pathname == NULL)
458     {
459       /* Return failure if the file could not be found, so that we can
460 	 accumulate messages about missing libraries.  */
461       if (errno == ENOENT)
462 	return NULL;
463 
464       perror_with_name (pathname);
465     }
466 
467   /* Open bfd for shared library.  */
468   gdb_bfd_ref_ptr abfd (solib_bfd_fopen (found_pathname.get (), found_file));
469 
470   /* Check bfd format.  */
471   if (!bfd_check_format (abfd.get (), bfd_object))
472     error (_("`%s': not in executable format: %s"),
473 	   bfd_get_filename (abfd.get ()), bfd_errmsg (bfd_get_error ()));
474 
475   /* Check bfd arch.  */
476   b = gdbarch_bfd_arch_info (target_gdbarch ());
477   if (!b->compatible (b, bfd_get_arch_info (abfd.get ())))
478     {
479       const char *slash = strrchr(pathname, '/');
480       if (slash)
481         {
482 	  char buf[SO_NAME_MAX_PATH_SIZE], arch[128], *colon;
483           struct stat st;
484 
485 	  snprintf(arch, sizeof(arch), "%s", b->printable_name);
486 	  if ((colon = strchr(arch, ':')) != NULL)
487 		*colon = '\0';
488 	  snprintf(buf, sizeof(buf), "%.*s/%s/%s",
489 	    (int)(slash - pathname), pathname, arch, slash + 1);
490 	  if (stat(buf, &st) == 0)
491 	    return solib_bfd_open(buf);
492 	  snprintf(buf, sizeof(buf), "%s-%s", pathname, arch);
493 	  if (stat(buf, &st) == 0)
494 	    return solib_bfd_open(buf);
495 	}
496       error (_("`%s': Shared library architecture %s is not compatible "
497 	       "with target architecture %s."), bfd_get_filename (abfd.get ()),
498 	     bfd_get_arch_info (abfd.get ())->printable_name,
499 	     b->printable_name);
500     }
501 
502   return abfd;
503 }
504 
505 /* Mapping of a core file's shared library sonames to their respective
506    build-ids.  Added to the registries of core file bfds.  */
507 
508 typedef std::unordered_map<std::string, std::string> soname_build_id_map;
509 
510 /* Key used to associate a soname_build_id_map to a core file bfd.  */
511 
512 static const struct registry<bfd>::key<soname_build_id_map>
513      cbfd_soname_build_id_data_key;
514 
515 /* See solib.h.  */
516 
517 void
518 set_cbfd_soname_build_id (gdb_bfd_ref_ptr abfd,
519 			  const char *soname,
520 			  const bfd_build_id *build_id)
521 {
522   gdb_assert (abfd.get () != nullptr);
523   gdb_assert (soname != nullptr);
524   gdb_assert (build_id != nullptr);
525 
526   soname_build_id_map *mapptr = cbfd_soname_build_id_data_key.get (abfd.get ());
527 
528   if (mapptr == nullptr)
529     mapptr = cbfd_soname_build_id_data_key.emplace (abfd.get ());
530 
531   (*mapptr)[soname] = build_id_to_string (build_id);
532 }
533 
534 /* See solib.h.  */
535 
536 gdb::unique_xmalloc_ptr<char>
537 get_cbfd_soname_build_id (gdb_bfd_ref_ptr abfd, const char *soname)
538 {
539   if (abfd.get () == nullptr || soname == nullptr)
540     return {};
541 
542   soname_build_id_map *mapptr
543     = cbfd_soname_build_id_data_key.get (abfd.get ());
544 
545   if (mapptr == nullptr)
546     return {};
547 
548   auto it = mapptr->find (lbasename (soname));
549   if (it == mapptr->end ())
550     return {};
551 
552   return make_unique_xstrdup (it->second.c_str ());
553 }
554 
555 /* Given a pointer to one of the shared objects in our list of mapped
556    objects, use the recorded name to open a bfd descriptor for the
557    object, build a section table, relocate all the section addresses
558    by the base address at which the shared object was mapped, and then
559    add the sections to the target's section table.
560 
561    FIXME: In most (all?) cases the shared object file name recorded in
562    the dynamic linkage tables will be a fully qualified pathname.  For
563    cases where it isn't, do we really mimic the systems search
564    mechanism correctly in the below code (particularly the tilde
565    expansion stuff?).  */
566 
567 static int
568 solib_map_sections (struct so_list *so)
569 {
570   const struct target_so_ops *ops = gdbarch_so_ops (target_gdbarch ());
571 
572   gdb::unique_xmalloc_ptr<char> filename (tilde_expand (so->so_name));
573   gdb_bfd_ref_ptr abfd (ops->bfd_open (filename.get ()));
574   gdb::unique_xmalloc_ptr<char> build_id_hexstr
575     = get_cbfd_soname_build_id (current_program_space->cbfd, so->so_name);
576 
577   /* If we already know the build-id of this solib from a core file, verify
578      it matches ABFD's build-id.  If there is a mismatch or the solib wasn't
579      found, attempt to query debuginfod for the correct solib.  */
580   if (build_id_hexstr.get () != nullptr)
581     {
582       bool mismatch = false;
583 
584       if (abfd != nullptr && abfd->build_id != nullptr)
585 	{
586 	  std::string build_id = build_id_to_string (abfd->build_id);
587 
588 	  if (build_id != build_id_hexstr.get ())
589 	    mismatch = true;
590 	}
591       if (abfd == nullptr || mismatch)
592 	{
593 	  scoped_fd fd = debuginfod_exec_query ((const unsigned char*)
594 						build_id_hexstr.get (),
595 						0, so->so_name, &filename);
596 
597 	  if (fd.get () >= 0)
598 	    abfd = ops->bfd_open (filename.get ());
599 	  else if (mismatch)
600 	    warning (_("Build-id of %ps does not match core file."),
601 		     styled_string (file_name_style.style (), filename.get ()));
602 	}
603     }
604 
605   if (abfd == NULL)
606     return 0;
607 
608   /* Leave bfd open, core_xfer_memory and "info files" need it.  */
609   so->abfd = abfd.release ();
610 
611   /* Copy the full path name into so_name, allowing symbol_file_add
612      to find it later.  This also affects the =library-loaded GDB/MI
613      event, and in particular the part of that notification providing
614      the library's host-side path.  If we let the target dictate
615      that objfile's path, and the target is different from the host,
616      GDB/MI will not provide the correct host-side path.  */
617   if (strlen (bfd_get_filename (so->abfd)) >= SO_NAME_MAX_PATH_SIZE)
618     error (_("Shared library file name is too long."));
619   strcpy (so->so_name, bfd_get_filename (so->abfd));
620 
621   if (so->sections == nullptr)
622     so->sections = new target_section_table;
623   *so->sections = build_section_table (so->abfd);
624 
625   for (target_section &p : *so->sections)
626     {
627       /* Relocate the section binding addresses as recorded in the shared
628 	 object's file by the base address to which the object was actually
629 	 mapped.  */
630       ops->relocate_section_addresses (so, &p);
631 
632       /* If the target didn't provide information about the address
633 	 range of the shared object, assume we want the location of
634 	 the .text section.  */
635       if (so->addr_low == 0 && so->addr_high == 0
636 	  && strcmp (p.the_bfd_section->name, ".text") == 0)
637 	{
638 	  so->addr_low = p.addr;
639 	  so->addr_high = p.endaddr;
640 	}
641     }
642 
643   /* Add the shared object's sections to the current set of file
644      section tables.  Do this immediately after mapping the object so
645      that later nodes in the list can query this object, as is needed
646      in solib-osf.c.  */
647   current_program_space->add_target_sections (so, *so->sections);
648 
649   return 1;
650 }
651 
652 /* Free symbol-file related contents of SO and reset for possible reloading
653    of SO.  If we have opened a BFD for SO, close it.  If we have placed SO's
654    sections in some target's section table, the caller is responsible for
655    removing them.
656 
657    This function doesn't mess with objfiles at all.  If there is an
658    objfile associated with SO that needs to be removed, the caller is
659    responsible for taking care of that.  */
660 
661 static void
662 clear_so (struct so_list *so)
663 {
664   const struct target_so_ops *ops = gdbarch_so_ops (target_gdbarch ());
665 
666   delete so->sections;
667   so->sections = NULL;
668 
669   gdb_bfd_unref (so->abfd);
670   so->abfd = NULL;
671 
672   /* Our caller closed the objfile, possibly via objfile_purge_solibs.  */
673   so->symbols_loaded = 0;
674   so->objfile = NULL;
675 
676   so->addr_low = so->addr_high = 0;
677 
678   /* Restore the target-supplied file name.  SO_NAME may be the path
679      of the symbol file.  */
680   strcpy (so->so_name, so->so_original_name);
681 
682   /* Do the same for target-specific data.  */
683   if (ops->clear_so != NULL)
684     ops->clear_so (so);
685 }
686 
687 /* Free the storage associated with the `struct so_list' object SO.
688    If we have opened a BFD for SO, close it.
689 
690    The caller is responsible for removing SO from whatever list it is
691    a member of.  If we have placed SO's sections in some target's
692    section table, the caller is responsible for removing them.
693 
694    This function doesn't mess with objfiles at all.  If there is an
695    objfile associated with SO that needs to be removed, the caller is
696    responsible for taking care of that.  */
697 
698 void
699 free_so (struct so_list *so)
700 {
701   const struct target_so_ops *ops = gdbarch_so_ops (target_gdbarch ());
702 
703   clear_so (so);
704   ops->free_so (so);
705 
706   xfree (so);
707 }
708 
709 
710 /* Read in symbols for shared object SO.  If SYMFILE_VERBOSE is set in FLAGS,
711    be chatty about it.  Return true if any symbols were actually loaded.  */
712 
713 bool
714 solib_read_symbols (struct so_list *so, symfile_add_flags flags)
715 {
716   if (so->symbols_loaded)
717     {
718       /* If needed, we've already warned in our caller.  */
719     }
720   else if (so->abfd == NULL)
721     {
722       /* We've already warned about this library, when trying to open
723 	 it.  */
724     }
725   else
726     {
727 
728       flags |= current_inferior ()->symfile_flags;
729 
730       try
731 	{
732 	  /* Have we already loaded this shared object?  */
733 	  so->objfile = nullptr;
734 	  for (objfile *objfile : current_program_space->objfiles ())
735 	    {
736 	      if (filename_cmp (objfile_name (objfile), so->so_name) == 0
737 		  && objfile->addr_low == so->addr_low)
738 		{
739 		  so->objfile = objfile;
740 		  break;
741 		}
742 	    }
743 	  if (so->objfile == NULL)
744 	    {
745 	      section_addr_info sap
746 		= build_section_addr_info_from_section_table (*so->sections);
747 	      gdb_bfd_ref_ptr tmp_bfd
748 		(gdb_bfd_ref_ptr::new_reference (so->abfd));
749 	      so->objfile = symbol_file_add_from_bfd (tmp_bfd, so->so_name,
750 						      flags, &sap,
751 						      OBJF_SHARED, NULL);
752 	      so->objfile->addr_low = so->addr_low;
753 	    }
754 
755 	  so->symbols_loaded = 1;
756 	}
757       catch (const gdb_exception_error &e)
758 	{
759 	  exception_fprintf (gdb_stderr, e, _("Error while reading shared"
760 					      " library symbols for %s:\n"),
761 			     so->so_name);
762 	}
763 
764       return true;
765     }
766 
767   return false;
768 }
769 
770 /* Return true if KNOWN->objfile is used by any other so_list object
771    in the list of shared libraries.  Return false otherwise.  */
772 
773 static bool
774 solib_used (const struct so_list *const known)
775 {
776   for (const struct so_list *pivot : current_program_space->solibs ())
777     if (pivot != known && pivot->objfile == known->objfile)
778       return true;
779   return false;
780 }
781 
782 /* See solib.h.  */
783 
784 void
785 update_solib_list (int from_tty)
786 {
787   const struct target_so_ops *ops = gdbarch_so_ops (target_gdbarch ());
788   struct so_list *inferior = ops->current_sos();
789   struct so_list *gdb, **gdb_link;
790 
791   /* We can reach here due to changing solib-search-path or the
792      sysroot, before having any inferior.  */
793   if (target_has_execution () && inferior_ptid != null_ptid)
794     {
795       struct inferior *inf = current_inferior ();
796 
797       /* If we are attaching to a running process for which we
798 	 have not opened a symbol file, we may be able to get its
799 	 symbols now!  */
800       if (inf->attach_flag
801 	  && current_program_space->symfile_object_file == NULL)
802 	{
803 	  try
804 	    {
805 	      ops->open_symbol_file_object (from_tty);
806 	    }
807 	  catch (const gdb_exception &ex)
808 	    {
809 	      exception_fprintf (gdb_stderr, ex,
810 				 "Error reading attached "
811 				 "process's symbol file.\n");
812 	    }
813 	}
814     }
815 
816   /* GDB and the inferior's dynamic linker each maintain their own
817      list of currently loaded shared objects; we want to bring the
818      former in sync with the latter.  Scan both lists, seeing which
819      shared objects appear where.  There are three cases:
820 
821      - A shared object appears on both lists.  This means that GDB
822      knows about it already, and it's still loaded in the inferior.
823      Nothing needs to happen.
824 
825      - A shared object appears only on GDB's list.  This means that
826      the inferior has unloaded it.  We should remove the shared
827      object from GDB's tables.
828 
829      - A shared object appears only on the inferior's list.  This
830      means that it's just been loaded.  We should add it to GDB's
831      tables.
832 
833      So we walk GDB's list, checking each entry to see if it appears
834      in the inferior's list too.  If it does, no action is needed, and
835      we remove it from the inferior's list.  If it doesn't, the
836      inferior has unloaded it, and we remove it from GDB's list.  By
837      the time we're done walking GDB's list, the inferior's list
838      contains only the new shared objects, which we then add.  */
839 
840   gdb = current_program_space->so_list;
841   gdb_link = &current_program_space->so_list;
842   while (gdb)
843     {
844       struct so_list *i = inferior;
845       struct so_list **i_link = &inferior;
846 
847       /* Check to see whether the shared object *gdb also appears in
848 	 the inferior's current list.  */
849       while (i)
850 	{
851 	  if (ops->same)
852 	    {
853 	      if (ops->same (gdb, i))
854 		break;
855 	    }
856 	  else
857 	    {
858 	      if (! filename_cmp (gdb->so_original_name, i->so_original_name))
859 		break;
860 	    }
861 
862 	  i_link = &i->next;
863 	  i = *i_link;
864 	}
865 
866       /* If the shared object appears on the inferior's list too, then
867 	 it's still loaded, so we don't need to do anything.  Delete
868 	 it from the inferior's list, and leave it on GDB's list.  */
869       if (i)
870 	{
871 	  *i_link = i->next;
872 	  free_so (i);
873 	  gdb_link = &gdb->next;
874 	  gdb = *gdb_link;
875 	}
876 
877       /* If it's not on the inferior's list, remove it from GDB's tables.  */
878       else
879 	{
880 	  /* Notify any observer that the shared object has been
881 	     unloaded before we remove it from GDB's tables.  */
882 	  gdb::observers::solib_unloaded.notify (gdb);
883 
884 	  current_program_space->deleted_solibs.push_back (gdb->so_name);
885 
886 	  *gdb_link = gdb->next;
887 
888 	  /* Unless the user loaded it explicitly, free SO's objfile.  */
889 	  if (gdb->objfile && ! (gdb->objfile->flags & OBJF_USERLOADED)
890 	      && !solib_used (gdb))
891 	    gdb->objfile->unlink ();
892 
893 	  /* Some targets' section tables might be referring to
894 	     sections from so->abfd; remove them.  */
895 	  current_program_space->remove_target_sections (gdb);
896 
897 	  free_so (gdb);
898 	  gdb = *gdb_link;
899 	}
900     }
901 
902   /* Now the inferior's list contains only shared objects that don't
903      appear in GDB's list --- those that are newly loaded.  Add them
904      to GDB's shared object list.  */
905   if (inferior)
906     {
907       int not_found = 0;
908       const char *not_found_filename = NULL;
909 
910       struct so_list *i;
911 
912       /* Add the new shared objects to GDB's list.  */
913       *gdb_link = inferior;
914 
915       /* Fill in the rest of each of the `struct so_list' nodes.  */
916       for (i = inferior; i; i = i->next)
917 	{
918 
919 	  i->pspace = current_program_space;
920 	  current_program_space->added_solibs.push_back (i);
921 
922 	  try
923 	    {
924 	      /* Fill in the rest of the `struct so_list' node.  */
925 	      if (!solib_map_sections (i))
926 		{
927 		  not_found++;
928 		  if (not_found_filename == NULL)
929 		    not_found_filename = i->so_original_name;
930 		}
931 	    }
932 
933 	  catch (const gdb_exception_error &e)
934 	    {
935 	      exception_fprintf (gdb_stderr, e,
936 				 _("Error while mapping shared "
937 				   "library sections:\n"));
938 	    }
939 
940 	  /* Notify any observer that the shared object has been
941 	     loaded now that we've added it to GDB's tables.  */
942 	  gdb::observers::solib_loaded.notify (i);
943 	}
944 
945       /* If a library was not found, issue an appropriate warning
946 	 message.  We have to use a single call to warning in case the
947 	 front end does something special with warnings, e.g., pop up
948 	 a dialog box.  It Would Be Nice if we could get a "warning: "
949 	 prefix on each line in the CLI front end, though - it doesn't
950 	 stand out well.  */
951 
952       if (not_found == 1)
953 	warning (_("Could not load shared library symbols for %s.\n"
954 		   "Do you need \"set solib-search-path\" "
955 		   "or \"set sysroot\"?"),
956 		 not_found_filename);
957       else if (not_found > 1)
958 	warning (_("\
959 Could not load shared library symbols for %d libraries, e.g. %s.\n\
960 Use the \"info sharedlibrary\" command to see the complete listing.\n\
961 Do you need \"set solib-search-path\" or \"set sysroot\"?"),
962 		 not_found, not_found_filename);
963     }
964 }
965 
966 
967 /* Return non-zero if NAME is the libpthread shared library.
968 
969    Uses a fairly simplistic heuristic approach where we check
970    the file name against "/libpthread".  This can lead to false
971    positives, but this should be good enough in practice.
972 
973    As of glibc-2.34, functions formerly residing in libpthread have
974    been moved to libc, so "/libc." needs to be checked too.  (Matching
975    the "." will avoid matching libraries such as libcrypt.) */
976 
977 bool
978 libpthread_name_p (const char *name)
979 {
980   return (strstr (name, "/libpthread") != NULL
981           || strstr (name, "/libc.") != NULL );
982 }
983 
984 /* Return non-zero if SO is the libpthread shared library.  */
985 
986 static bool
987 libpthread_solib_p (struct so_list *so)
988 {
989   return libpthread_name_p (so->so_name);
990 }
991 
992 /* Read in symbolic information for any shared objects whose names
993    match PATTERN.  (If we've already read a shared object's symbol
994    info, leave it alone.)  If PATTERN is zero, read them all.
995 
996    If READSYMS is 0, defer reading symbolic information until later
997    but still do any needed low level processing.
998 
999    FROM_TTY is described for update_solib_list, above.  */
1000 
1001 void
1002 solib_add (const char *pattern, int from_tty, int readsyms)
1003 {
1004   if (print_symbol_loading_p (from_tty, 0, 0))
1005     {
1006       if (pattern != NULL)
1007 	{
1008 	  gdb_printf (_("Loading symbols for shared libraries: %s\n"),
1009 		      pattern);
1010 	}
1011       else
1012 	gdb_printf (_("Loading symbols for shared libraries.\n"));
1013     }
1014 
1015   current_program_space->solib_add_generation++;
1016 
1017   if (pattern)
1018     {
1019       char *re_err = re_comp (pattern);
1020 
1021       if (re_err)
1022 	error (_("Invalid regexp: %s"), re_err);
1023     }
1024 
1025   update_solib_list (from_tty);
1026 
1027   /* Walk the list of currently loaded shared libraries, and read
1028      symbols for any that match the pattern --- or any whose symbols
1029      aren't already loaded, if no pattern was given.  */
1030   {
1031     bool any_matches = false;
1032     bool loaded_any_symbols = false;
1033     symfile_add_flags add_flags = SYMFILE_DEFER_BP_RESET;
1034 
1035     if (from_tty)
1036 	add_flags |= SYMFILE_VERBOSE;
1037 
1038     for (struct so_list *gdb : current_program_space->solibs ())
1039       if (! pattern || re_exec (gdb->so_name))
1040 	{
1041 	  /* Normally, we would read the symbols from that library
1042 	     only if READSYMS is set.  However, we're making a small
1043 	     exception for the pthread library, because we sometimes
1044 	     need the library symbols to be loaded in order to provide
1045 	     thread support (x86-linux for instance).  */
1046 	  const int add_this_solib =
1047 	    (readsyms || libpthread_solib_p (gdb));
1048 
1049 	  any_matches = true;
1050 	  if (add_this_solib)
1051 	    {
1052 	      if (gdb->symbols_loaded)
1053 		{
1054 		  /* If no pattern was given, be quiet for shared
1055 		     libraries we have already loaded.  */
1056 		  if (pattern && (from_tty || info_verbose))
1057 		    gdb_printf (_("Symbols already loaded for %s\n"),
1058 				gdb->so_name);
1059 		}
1060 	      else if (solib_read_symbols (gdb, add_flags))
1061 		loaded_any_symbols = true;
1062 	    }
1063 	}
1064 
1065     if (loaded_any_symbols)
1066       breakpoint_re_set ();
1067 
1068     if (from_tty && pattern && ! any_matches)
1069       gdb_printf
1070 	("No loaded shared libraries match the pattern `%s'.\n", pattern);
1071 
1072     if (loaded_any_symbols)
1073       {
1074 	/* Getting new symbols may change our opinion about what is
1075 	   frameless.  */
1076 	reinit_frame_cache ();
1077       }
1078   }
1079 }
1080 
1081 /* Implement the "info sharedlibrary" command.  Walk through the
1082    shared library list and print information about each attached
1083    library matching PATTERN.  If PATTERN is elided, print them
1084    all.  */
1085 
1086 static void
1087 info_sharedlibrary_command (const char *pattern, int from_tty)
1088 {
1089   bool so_missing_debug_info = false;
1090   int addr_width;
1091   int nr_libs;
1092   struct gdbarch *gdbarch = target_gdbarch ();
1093   struct ui_out *uiout = current_uiout;
1094 
1095   if (pattern)
1096     {
1097       char *re_err = re_comp (pattern);
1098 
1099       if (re_err)
1100 	error (_("Invalid regexp: %s"), re_err);
1101     }
1102 
1103   /* "0x", a little whitespace, and two hex digits per byte of pointers.  */
1104   addr_width = 4 + (gdbarch_ptr_bit (gdbarch) / 4);
1105 
1106   update_solib_list (from_tty);
1107 
1108   /* ui_out_emit_table table_emitter needs to know the number of rows,
1109      so we need to make two passes over the libs.  */
1110 
1111   nr_libs = 0;
1112   for (struct so_list *so : current_program_space->solibs ())
1113     {
1114       if (so->so_name[0])
1115 	{
1116 	  if (pattern && ! re_exec (so->so_name))
1117 	    continue;
1118 	  ++nr_libs;
1119 	}
1120     }
1121 
1122   {
1123     ui_out_emit_table table_emitter (uiout, 4, nr_libs, "SharedLibraryTable");
1124 
1125     /* The "- 1" is because ui_out adds one space between columns.  */
1126     uiout->table_header (addr_width - 1, ui_left, "from", "From");
1127     uiout->table_header (addr_width - 1, ui_left, "to", "To");
1128     uiout->table_header (12 - 1, ui_left, "syms-read", "Syms Read");
1129     uiout->table_header (0, ui_noalign, "name", "Shared Object Library");
1130 
1131     uiout->table_body ();
1132 
1133     for (struct so_list *so : current_program_space->solibs ())
1134       {
1135 	if (! so->so_name[0])
1136 	  continue;
1137 	if (pattern && ! re_exec (so->so_name))
1138 	  continue;
1139 
1140 	ui_out_emit_tuple tuple_emitter (uiout, "lib");
1141 
1142 	if (so->addr_high != 0)
1143 	  {
1144 	    uiout->field_core_addr ("from", gdbarch, so->addr_low);
1145 	    uiout->field_core_addr ("to", gdbarch, so->addr_high);
1146 	  }
1147 	else
1148 	  {
1149 	    uiout->field_skip ("from");
1150 	    uiout->field_skip ("to");
1151 	  }
1152 
1153 	if (! top_level_interpreter ()->interp_ui_out ()->is_mi_like_p ()
1154 	    && so->symbols_loaded
1155 	    && !objfile_has_symbols (so->objfile))
1156 	  {
1157 	    so_missing_debug_info = true;
1158 	    uiout->field_string ("syms-read", "Yes (*)");
1159 	  }
1160 	else
1161 	  uiout->field_string ("syms-read", so->symbols_loaded ? "Yes" : "No");
1162 
1163 	uiout->field_string ("name", so->so_name, file_name_style.style ());
1164 
1165 	uiout->text ("\n");
1166       }
1167   }
1168 
1169   if (nr_libs == 0)
1170     {
1171       if (pattern)
1172 	uiout->message (_("No shared libraries matched.\n"));
1173       else
1174 	uiout->message (_("No shared libraries loaded at this time.\n"));
1175     }
1176   else
1177     {
1178       if (so_missing_debug_info)
1179 	uiout->message (_("(*): Shared library is missing "
1180 			  "debugging information.\n"));
1181     }
1182 }
1183 
1184 /* See solib.h.  */
1185 
1186 bool
1187 solib_contains_address_p (const struct so_list *const solib,
1188 			  CORE_ADDR address)
1189 {
1190   if (solib->sections == nullptr)
1191     return false;
1192 
1193   for (target_section &p : *solib->sections)
1194     if (p.addr <= address && address < p.endaddr)
1195       return true;
1196 
1197   return false;
1198 }
1199 
1200 /* If ADDRESS is in a shared lib in program space PSPACE, return its
1201    name.
1202 
1203    Provides a hook for other gdb routines to discover whether or not a
1204    particular address is within the mapped address space of a shared
1205    library.
1206 
1207    For example, this routine is called at one point to disable
1208    breakpoints which are in shared libraries that are not currently
1209    mapped in.  */
1210 
1211 const char *
1212 solib_name_from_address (struct program_space *pspace, CORE_ADDR address)
1213 {
1214   struct so_list *so = NULL;
1215 
1216   for (so = pspace->so_list; so; so = so->next)
1217     if (solib_contains_address_p (so, address))
1218       return (so->so_name);
1219 
1220   return (0);
1221 }
1222 
1223 /* See solib.h.  */
1224 
1225 bool
1226 solib_keep_data_in_core (CORE_ADDR vaddr, unsigned long size)
1227 {
1228   const struct target_so_ops *ops = gdbarch_so_ops (target_gdbarch ());
1229 
1230   if (ops->keep_data_in_core)
1231     return ops->keep_data_in_core (vaddr, size) != 0;
1232   else
1233     return false;
1234 }
1235 
1236 /* Called by free_all_symtabs */
1237 
1238 void
1239 clear_solib (void)
1240 {
1241   const struct target_so_ops *ops = gdbarch_so_ops (target_gdbarch ());
1242 
1243   disable_breakpoints_in_shlibs ();
1244 
1245   while (current_program_space->so_list)
1246     {
1247       struct so_list *so = current_program_space->so_list;
1248 
1249       current_program_space->so_list = so->next;
1250       gdb::observers::solib_unloaded.notify (so);
1251       current_program_space->remove_target_sections (so);
1252       free_so (so);
1253     }
1254 
1255   ops->clear_solib ();
1256 }
1257 
1258 /* Shared library startup support.  When GDB starts up the inferior,
1259    it nurses it along (through the shell) until it is ready to execute
1260    its first instruction.  At this point, this function gets
1261    called.  */
1262 
1263 void
1264 solib_create_inferior_hook (int from_tty)
1265 {
1266   const struct target_so_ops *ops = gdbarch_so_ops (target_gdbarch ());
1267 
1268   ops->solib_create_inferior_hook (from_tty);
1269 }
1270 
1271 /* See solib.h.  */
1272 
1273 bool
1274 in_solib_dynsym_resolve_code (CORE_ADDR pc)
1275 {
1276   const struct target_so_ops *ops = gdbarch_so_ops (target_gdbarch ());
1277 
1278   return ops->in_dynsym_resolve_code (pc) != 0;
1279 }
1280 
1281 /* Implements the "sharedlibrary" command.  */
1282 
1283 static void
1284 sharedlibrary_command (const char *args, int from_tty)
1285 {
1286   dont_repeat ();
1287   solib_add (args, from_tty, 1);
1288 }
1289 
1290 /* Implements the command "nosharedlibrary", which discards symbols
1291    that have been auto-loaded from shared libraries.  Symbols from
1292    shared libraries that were added by explicit request of the user
1293    are not discarded.  Also called from remote.c.  */
1294 
1295 void
1296 no_shared_libraries (const char *ignored, int from_tty)
1297 {
1298   /* The order of the two routines below is important: clear_solib notifies
1299      the solib_unloaded observers, and some of these observers might need
1300      access to their associated objfiles.  Therefore, we can not purge the
1301      solibs' objfiles before clear_solib has been called.  */
1302 
1303   clear_solib ();
1304   objfile_purge_solibs ();
1305 }
1306 
1307 /* See solib.h.  */
1308 
1309 void
1310 update_solib_breakpoints (void)
1311 {
1312   const struct target_so_ops *ops = gdbarch_so_ops (target_gdbarch ());
1313 
1314   if (ops->update_breakpoints != NULL)
1315     ops->update_breakpoints ();
1316 }
1317 
1318 /* See solib.h.  */
1319 
1320 void
1321 handle_solib_event (void)
1322 {
1323   const struct target_so_ops *ops = gdbarch_so_ops (target_gdbarch ());
1324 
1325   if (ops->handle_event != NULL)
1326     ops->handle_event ();
1327 
1328   current_inferior ()->pspace->clear_solib_cache ();
1329 
1330   /* Check for any newly added shared libraries if we're supposed to
1331      be adding them automatically.  Switch terminal for any messages
1332      produced by breakpoint_re_set.  */
1333   target_terminal::ours_for_output ();
1334   solib_add (NULL, 0, auto_solib_add);
1335   target_terminal::inferior ();
1336 }
1337 
1338 /* Reload shared libraries, but avoid reloading the same symbol file
1339    we already have loaded.  */
1340 
1341 static void
1342 reload_shared_libraries_1 (int from_tty)
1343 {
1344   if (print_symbol_loading_p (from_tty, 0, 0))
1345     gdb_printf (_("Loading symbols for shared libraries.\n"));
1346 
1347   for (struct so_list *so : current_program_space->solibs ())
1348     {
1349       const char *found_pathname = NULL;
1350       bool was_loaded = so->symbols_loaded != 0;
1351       symfile_add_flags add_flags = SYMFILE_DEFER_BP_RESET;
1352 
1353       if (from_tty)
1354 	add_flags |= SYMFILE_VERBOSE;
1355 
1356       gdb::unique_xmalloc_ptr<char> filename
1357 	(tilde_expand (so->so_original_name));
1358       gdb_bfd_ref_ptr abfd (solib_bfd_open (filename.get ()));
1359       if (abfd != NULL)
1360 	found_pathname = bfd_get_filename (abfd.get ());
1361 
1362       /* If this shared library is no longer associated with its previous
1363 	 symbol file, close that.  */
1364       if ((found_pathname == NULL && was_loaded)
1365 	  || (found_pathname != NULL
1366 	      && filename_cmp (found_pathname, so->so_name) != 0))
1367 	{
1368 	  if (so->objfile && ! (so->objfile->flags & OBJF_USERLOADED)
1369 	      && !solib_used (so))
1370 	    so->objfile->unlink ();
1371 	  current_program_space->remove_target_sections (so);
1372 	  clear_so (so);
1373 	}
1374 
1375       /* If this shared library is now associated with a new symbol
1376 	 file, open it.  */
1377       if (found_pathname != NULL
1378 	  && (!was_loaded
1379 	      || filename_cmp (found_pathname, so->so_name) != 0))
1380 	{
1381 	  bool got_error = false;
1382 
1383 	  try
1384 	    {
1385 	      solib_map_sections (so);
1386 	    }
1387 
1388 	  catch (const gdb_exception_error &e)
1389 	    {
1390 	      exception_fprintf (gdb_stderr, e,
1391 				 _("Error while mapping "
1392 				   "shared library sections:\n"));
1393 	      got_error = true;
1394 	    }
1395 
1396 	    if (!got_error
1397 		&& (auto_solib_add || was_loaded || libpthread_solib_p (so)))
1398 	      solib_read_symbols (so, add_flags);
1399 	}
1400     }
1401 }
1402 
1403 static void
1404 reload_shared_libraries (const char *ignored, int from_tty,
1405 			 struct cmd_list_element *e)
1406 {
1407   const struct target_so_ops *ops;
1408 
1409   reload_shared_libraries_1 (from_tty);
1410 
1411   ops = gdbarch_so_ops (target_gdbarch ());
1412 
1413   /* Creating inferior hooks here has two purposes.  First, if we reload
1414      shared libraries then the address of solib breakpoint we've computed
1415      previously might be no longer valid.  For example, if we forgot to set
1416      solib-absolute-prefix and are setting it right now, then the previous
1417      breakpoint address is plain wrong.  Second, installing solib hooks
1418      also implicitly figures were ld.so is and loads symbols for it.
1419      Absent this call, if we've just connected to a target and set
1420      solib-absolute-prefix or solib-search-path, we'll lose all information
1421      about ld.so.  */
1422   if (target_has_execution ())
1423     {
1424       /* Reset or free private data structures not associated with
1425 	 so_list entries.  */
1426       ops->clear_solib ();
1427 
1428       /* Remove any previous solib event breakpoint.  This is usually
1429 	 done in common code, at breakpoint_init_inferior time, but
1430 	 we're not really starting up the inferior here.  */
1431       remove_solib_event_breakpoints ();
1432 
1433       solib_create_inferior_hook (from_tty);
1434     }
1435 
1436   /* Sometimes the platform-specific hook loads initial shared
1437      libraries, and sometimes it doesn't.  If it doesn't FROM_TTY will be
1438      incorrectly 0 but such solib targets should be fixed anyway.  If we
1439      made all the inferior hook methods consistent, this call could be
1440      removed.  Call it only after the solib target has been initialized by
1441      solib_create_inferior_hook.  */
1442 
1443   solib_add (NULL, 0, auto_solib_add);
1444 
1445   breakpoint_re_set ();
1446 
1447   /* We may have loaded or unloaded debug info for some (or all)
1448      shared libraries.  However, frames may still reference them.  For
1449      example, a frame's unwinder might still point at DWARF FDE
1450      structures that are now freed.  Also, getting new symbols may
1451      change our opinion about what is frameless.  */
1452   reinit_frame_cache ();
1453 }
1454 
1455 /* Wrapper for reload_shared_libraries that replaces "remote:"
1456    at the start of gdb_sysroot with "target:".  */
1457 
1458 static void
1459 gdb_sysroot_changed (const char *ignored, int from_tty,
1460 		     struct cmd_list_element *e)
1461 {
1462   const char *old_prefix = "remote:";
1463   const char *new_prefix = TARGET_SYSROOT_PREFIX;
1464 
1465   if (startswith (gdb_sysroot.c_str (), old_prefix))
1466     {
1467       static bool warning_issued = false;
1468 
1469       gdb_assert (strlen (old_prefix) == strlen (new_prefix));
1470       gdb_sysroot = new_prefix + gdb_sysroot.substr (strlen (old_prefix));
1471 
1472       if (!warning_issued)
1473 	{
1474 	  warning (_("\"%s\" is deprecated, use \"%s\" instead."),
1475 		   old_prefix, new_prefix);
1476 	  warning (_("sysroot set to \"%s\"."), gdb_sysroot.c_str ());
1477 
1478 	  warning_issued = true;
1479 	}
1480     }
1481 
1482   reload_shared_libraries (ignored, from_tty, e);
1483 }
1484 
1485 static void
1486 show_auto_solib_add (struct ui_file *file, int from_tty,
1487 		     struct cmd_list_element *c, const char *value)
1488 {
1489   gdb_printf (file, _("Autoloading of shared library symbols is %s.\n"),
1490 	      value);
1491 }
1492 
1493 
1494 /* Lookup the value for a specific symbol from dynamic symbol table.  Look
1495    up symbol from ABFD.  MATCH_SYM is a callback function to determine
1496    whether to pick up a symbol.  DATA is the input of this callback
1497    function.  Return NULL if symbol is not found.  */
1498 
1499 CORE_ADDR
1500 gdb_bfd_lookup_symbol_from_symtab (bfd *abfd,
1501 				   int (*match_sym) (const asymbol *,
1502 						     const void *),
1503 				   const void *data)
1504 {
1505   long storage_needed = bfd_get_symtab_upper_bound (abfd);
1506   CORE_ADDR symaddr = 0;
1507 
1508   if (storage_needed > 0)
1509     {
1510       unsigned int i;
1511 
1512       gdb::def_vector<asymbol *> storage (storage_needed / sizeof (asymbol *));
1513       asymbol **symbol_table = storage.data ();
1514       unsigned int number_of_symbols =
1515 	bfd_canonicalize_symtab (abfd, symbol_table);
1516 
1517       for (i = 0; i < number_of_symbols; i++)
1518 	{
1519 	  asymbol *sym  = *symbol_table++;
1520 
1521 	  if (match_sym (sym, data))
1522 	    {
1523 	      struct gdbarch *gdbarch = target_gdbarch ();
1524 	      symaddr = sym->value;
1525 
1526 	      /* Some ELF targets fiddle with addresses of symbols they
1527 		 consider special.  They use minimal symbols to do that
1528 		 and this is needed for correct breakpoint placement,
1529 		 but we do not have full data here to build a complete
1530 		 minimal symbol, so just set the address and let the
1531 		 targets cope with that.  */
1532 	      if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
1533 		  && gdbarch_elf_make_msymbol_special_p (gdbarch))
1534 		{
1535 		  struct minimal_symbol msym {};
1536 
1537 		  msym.set_value_address (symaddr);
1538 		  gdbarch_elf_make_msymbol_special (gdbarch, sym, &msym);
1539 		  symaddr = msym.value_raw_address ();
1540 		}
1541 
1542 	      /* BFD symbols are section relative.  */
1543 	      symaddr += sym->section->vma;
1544 	      break;
1545 	    }
1546 	}
1547     }
1548 
1549   return symaddr;
1550 }
1551 
1552 /* See solib.h.  */
1553 
1554 int
1555 gdb_bfd_scan_elf_dyntag (const int desired_dyntag, bfd *abfd, CORE_ADDR *ptr,
1556 			 CORE_ADDR *ptr_addr)
1557 {
1558   int arch_size, step, sect_size;
1559   long current_dyntag;
1560   CORE_ADDR dyn_ptr, dyn_addr;
1561   gdb_byte *bufend, *bufstart, *buf;
1562   Elf32_External_Dyn *x_dynp_32;
1563   Elf64_External_Dyn *x_dynp_64;
1564   struct bfd_section *sect;
1565 
1566   if (abfd == NULL)
1567     return 0;
1568 
1569   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
1570     return 0;
1571 
1572   arch_size = bfd_get_arch_size (abfd);
1573   if (arch_size == -1)
1574     return 0;
1575 
1576   /* Find the start address of the .dynamic section.  */
1577   sect = bfd_get_section_by_name (abfd, ".dynamic");
1578   if (sect == NULL)
1579     return 0;
1580 
1581   bool found = false;
1582   for (const target_section &target_section
1583 	 : current_program_space->target_sections ())
1584     if (sect == target_section.the_bfd_section)
1585       {
1586 	dyn_addr = target_section.addr;
1587 	found = true;
1588 	break;
1589       }
1590   if (!found)
1591     {
1592       /* ABFD may come from OBJFILE acting only as a symbol file without being
1593 	 loaded into the target (see add_symbol_file_command).  This case is
1594 	 such fallback to the file VMA address without the possibility of
1595 	 having the section relocated to its actual in-memory address.  */
1596 
1597       dyn_addr = bfd_section_vma (sect);
1598     }
1599 
1600   /* Read in .dynamic from the BFD.  We will get the actual value
1601      from memory later.  */
1602   sect_size = bfd_section_size (sect);
1603   buf = bufstart = (gdb_byte *) alloca (sect_size);
1604   if (!bfd_get_section_contents (abfd, sect,
1605 				 buf, 0, sect_size))
1606     return 0;
1607 
1608   /* Iterate over BUF and scan for DYNTAG.  If found, set PTR and return.  */
1609   step = (arch_size == 32) ? sizeof (Elf32_External_Dyn)
1610 			   : sizeof (Elf64_External_Dyn);
1611   for (bufend = buf + sect_size;
1612        buf < bufend;
1613        buf += step)
1614   {
1615     if (arch_size == 32)
1616       {
1617 	x_dynp_32 = (Elf32_External_Dyn *) buf;
1618 	current_dyntag = bfd_h_get_32 (abfd, (bfd_byte *) x_dynp_32->d_tag);
1619 	dyn_ptr = bfd_h_get_32 (abfd, (bfd_byte *) x_dynp_32->d_un.d_ptr);
1620       }
1621     else
1622       {
1623 	x_dynp_64 = (Elf64_External_Dyn *) buf;
1624 	current_dyntag = bfd_h_get_64 (abfd, (bfd_byte *) x_dynp_64->d_tag);
1625 	dyn_ptr = bfd_h_get_64 (abfd, (bfd_byte *) x_dynp_64->d_un.d_ptr);
1626       }
1627     if (current_dyntag == DT_NULL)
1628       return 0;
1629     if (current_dyntag == desired_dyntag)
1630       {
1631 	/* If requested, try to read the runtime value of this .dynamic
1632 	   entry.  */
1633 	if (ptr)
1634 	  {
1635 	    struct type *ptr_type;
1636 	    gdb_byte ptr_buf[8];
1637 	    CORE_ADDR ptr_addr_1;
1638 
1639 	    ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
1640 	    ptr_addr_1 = dyn_addr + (buf - bufstart) + arch_size / 8;
1641 	    if (target_read_memory (ptr_addr_1, ptr_buf, arch_size / 8) == 0)
1642 	      dyn_ptr = extract_typed_address (ptr_buf, ptr_type);
1643 	    *ptr = dyn_ptr;
1644 	    if (ptr_addr)
1645 	      *ptr_addr = dyn_addr + (buf - bufstart);
1646 	  }
1647 	return 1;
1648       }
1649   }
1650 
1651   return 0;
1652 }
1653 
1654 /* See solib.h.  */
1655 
1656 gdb::unique_xmalloc_ptr<char>
1657 gdb_bfd_read_elf_soname (const char *filename)
1658 {
1659   gdb_bfd_ref_ptr abfd = gdb_bfd_open (filename, gnutarget);
1660 
1661   if (abfd == nullptr)
1662     return {};
1663 
1664   /* Check that ABFD is an ET_DYN ELF file.  */
1665   if (!bfd_check_format (abfd.get (), bfd_object)
1666       || !(bfd_get_file_flags (abfd.get ()) & DYNAMIC))
1667     return {};
1668 
1669   CORE_ADDR idx;
1670   if (!gdb_bfd_scan_elf_dyntag (DT_SONAME, abfd.get (), &idx, nullptr))
1671     return {};
1672 
1673   struct bfd_section *dynstr = bfd_get_section_by_name (abfd.get (), ".dynstr");
1674   int sect_size = bfd_section_size (dynstr);
1675   if (dynstr == nullptr || sect_size <= idx)
1676     return {};
1677 
1678   /* Read soname from the string table.  */
1679   gdb::byte_vector dynstr_buf;
1680   if (!gdb_bfd_get_full_section_contents (abfd.get (), dynstr, &dynstr_buf))
1681     return {};
1682 
1683   /* Ensure soname is null-terminated before returning a copy.  */
1684   char *soname = (char *) dynstr_buf.data () + idx;
1685   if (strnlen (soname, sect_size - idx) == sect_size - idx)
1686     return {};
1687 
1688   return make_unique_xstrdup (soname);
1689 }
1690 
1691 /* Lookup the value for a specific symbol from symbol table.  Look up symbol
1692    from ABFD.  MATCH_SYM is a callback function to determine whether to pick
1693    up a symbol.  DATA is the input of this callback function.  Return NULL
1694    if symbol is not found.  */
1695 
1696 static CORE_ADDR
1697 bfd_lookup_symbol_from_dyn_symtab (bfd *abfd,
1698 				   int (*match_sym) (const asymbol *,
1699 						     const void *),
1700 				   const void *data)
1701 {
1702   long storage_needed = bfd_get_dynamic_symtab_upper_bound (abfd);
1703   CORE_ADDR symaddr = 0;
1704 
1705   if (storage_needed > 0)
1706     {
1707       unsigned int i;
1708       gdb::def_vector<asymbol *> storage (storage_needed / sizeof (asymbol *));
1709       asymbol **symbol_table = storage.data ();
1710       unsigned int number_of_symbols =
1711 	bfd_canonicalize_dynamic_symtab (abfd, symbol_table);
1712 
1713       for (i = 0; i < number_of_symbols; i++)
1714 	{
1715 	  asymbol *sym = *symbol_table++;
1716 
1717 	  if (match_sym (sym, data))
1718 	    {
1719 	      /* BFD symbols are section relative.  */
1720 	      symaddr = sym->value + sym->section->vma;
1721 	      break;
1722 	    }
1723 	}
1724     }
1725   return symaddr;
1726 }
1727 
1728 /* Lookup the value for a specific symbol from symbol table and dynamic
1729    symbol table.  Look up symbol from ABFD.  MATCH_SYM is a callback
1730    function to determine whether to pick up a symbol.  DATA is the
1731    input of this callback function.  Return NULL if symbol is not
1732    found.  */
1733 
1734 CORE_ADDR
1735 gdb_bfd_lookup_symbol (bfd *abfd,
1736 		       int (*match_sym) (const asymbol *, const void *),
1737 		       const void *data)
1738 {
1739   CORE_ADDR symaddr = gdb_bfd_lookup_symbol_from_symtab (abfd, match_sym, data);
1740 
1741   /* On FreeBSD, the dynamic linker is stripped by default.  So we'll
1742      have to check the dynamic string table too.  */
1743   if (symaddr == 0)
1744     symaddr = bfd_lookup_symbol_from_dyn_symtab (abfd, match_sym, data);
1745 
1746   return symaddr;
1747 }
1748 
1749 /* The shared library list may contain user-loaded object files that
1750    can be removed out-of-band by the user.  So upon notification of
1751    free_objfile remove all references to any user-loaded file that is
1752    about to be freed.  */
1753 
1754 static void
1755 remove_user_added_objfile (struct objfile *objfile)
1756 {
1757   if (objfile != 0 && objfile->flags & OBJF_USERLOADED)
1758     {
1759       for (struct so_list *so : current_program_space->solibs ())
1760 	if (so->objfile == objfile)
1761 	  so->objfile = NULL;
1762     }
1763 }
1764 
1765 void _initialize_solib ();
1766 void
1767 _initialize_solib ()
1768 {
1769   gdb::observers::free_objfile.attach (remove_user_added_objfile,
1770 				       "solib");
1771   gdb::observers::inferior_execd.attach ([] (inferior *inf)
1772     {
1773       solib_create_inferior_hook (0);
1774     }, "solib");
1775 
1776   add_com ("sharedlibrary", class_files, sharedlibrary_command,
1777 	   _("Load shared object library symbols for files matching REGEXP."));
1778   cmd_list_element *info_sharedlibrary_cmd
1779     = add_info ("sharedlibrary", info_sharedlibrary_command,
1780 		_("Status of loaded shared object libraries."));
1781   add_info_alias ("dll", info_sharedlibrary_cmd, 1);
1782   add_com ("nosharedlibrary", class_files, no_shared_libraries,
1783 	   _("Unload all shared object library symbols."));
1784 
1785   add_setshow_boolean_cmd ("auto-solib-add", class_support,
1786 			   &auto_solib_add, _("\
1787 Set autoloading of shared library symbols."), _("\
1788 Show autoloading of shared library symbols."), _("\
1789 If \"on\", symbols from all shared object libraries will be loaded\n\
1790 automatically when the inferior begins execution, when the dynamic linker\n\
1791 informs gdb that a new library has been loaded, or when attaching to the\n\
1792 inferior.  Otherwise, symbols must be loaded manually, using \
1793 `sharedlibrary'."),
1794 			   NULL,
1795 			   show_auto_solib_add,
1796 			   &setlist, &showlist);
1797 
1798   set_show_commands sysroot_cmds
1799     = add_setshow_optional_filename_cmd ("sysroot", class_support,
1800 					 &gdb_sysroot, _("\
1801 Set an alternate system root."), _("\
1802 Show the current system root."), _("\
1803 The system root is used to load absolute shared library symbol files.\n\
1804 For other (relative) files, you can add directories using\n\
1805 `set solib-search-path'."),
1806 					 gdb_sysroot_changed,
1807 					 NULL,
1808 					 &setlist, &showlist);
1809 
1810   add_alias_cmd ("solib-absolute-prefix", sysroot_cmds.set, class_support, 0,
1811 		 &setlist);
1812   add_alias_cmd ("solib-absolute-prefix", sysroot_cmds.show, class_support, 0,
1813 		 &showlist);
1814 
1815   add_setshow_optional_filename_cmd ("solib-search-path", class_support,
1816 				     &solib_search_path, _("\
1817 Set the search path for loading non-absolute shared library symbol files."),
1818 				     _("\
1819 Show the search path for loading non-absolute shared library symbol files."),
1820 				     _("\
1821 This takes precedence over the environment variables \
1822 PATH and LD_LIBRARY_PATH."),
1823 				     reload_shared_libraries,
1824 				     show_solib_search_path,
1825 				     &setlist, &showlist);
1826 
1827   add_setshow_boolean_cmd ("solib", class_maintenance,
1828 			   &debug_solib, _("\
1829 Set solib debugging."), _("\
1830 Show solib debugging."), _("\
1831 When true, solib-related debugging output is enabled."),
1832 			    nullptr, nullptr,
1833 			    &setdebuglist, &showdebuglist);
1834 }
1835