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