Automatic date update in version.in
[binutils-gdb.git] / gdb / solib-svr4.c
blob1dd04c29c98519cd62988d4e01a8eb5e5c2de913
1 /* Handle SVR4 shared libraries for GDB, the GNU Debugger.
3 Copyright (C) 1990-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 #include "elf/external.h"
22 #include "elf/common.h"
23 #include "elf/mips.h"
25 #include "extract-store-integer.h"
26 #include "symtab.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "objfiles.h"
30 #include "gdbcore.h"
31 #include "target.h"
32 #include "inferior.h"
33 #include "infrun.h"
34 #include "regcache.h"
35 #include "observable.h"
37 #include "solist.h"
38 #include "solib.h"
39 #include "solib-svr4.h"
41 #include "bfd-target.h"
42 #include "elf-bfd.h"
43 #include "exec.h"
44 #include "auxv.h"
45 #include "gdb_bfd.h"
46 #include "probe.h"
48 #include <map>
50 static struct link_map_offsets *svr4_fetch_link_map_offsets (void);
51 static int svr4_have_link_map_offsets (void);
52 static void svr4_relocate_main_executable (void);
53 static void probes_table_remove_objfile_probes (struct objfile *objfile);
54 static void svr4_iterate_over_objfiles_in_search_order
55 (gdbarch *gdbarch, iterate_over_objfiles_in_search_order_cb_ftype cb,
56 objfile *current_objfile);
59 /* On SVR4 systems, a list of symbols in the dynamic linker where
60 GDB can try to place a breakpoint to monitor shared library
61 events.
63 If none of these symbols are found, or other errors occur, then
64 SVR4 systems will fall back to using a symbol as the "startup
65 mapping complete" breakpoint address. */
67 static const char * const solib_break_names[] =
69 "r_debug_state",
70 "_r_debug_state",
71 "_dl_debug_state",
72 "rtld_db_dlactivity",
73 "__dl_rtld_db_dlactivity",
74 "_rtld_debug_state",
76 NULL
79 static const char * const bkpt_names[] =
81 "_start",
82 "__start",
83 "main",
84 NULL
87 static const char * const main_name_list[] =
89 "main_$main",
90 NULL
93 /* What to do when a probe stop occurs. */
95 enum probe_action
97 /* Something went seriously wrong. Stop using probes and
98 revert to using the older interface. */
99 PROBES_INTERFACE_FAILED,
101 /* No action is required. The shared object list is still
102 valid. */
103 DO_NOTHING,
105 /* The shared object list should be reloaded entirely. */
106 FULL_RELOAD,
108 /* Attempt to incrementally update the shared object list. If
109 the update fails or is not possible, fall back to reloading
110 the list in full. */
111 UPDATE_OR_RELOAD,
114 /* A probe's name and its associated action. */
116 struct probe_info
118 /* The name of the probe. */
119 const char *name;
121 /* What to do when a probe stop occurs. */
122 enum probe_action action;
125 /* A list of named probes and their associated actions. If all
126 probes are present in the dynamic linker then the probes-based
127 interface will be used. */
129 static const struct probe_info probe_info[] =
131 { "init_start", DO_NOTHING },
132 { "init_complete", FULL_RELOAD },
133 { "map_start", DO_NOTHING },
134 { "map_failed", DO_NOTHING },
135 { "reloc_complete", UPDATE_OR_RELOAD },
136 { "unmap_start", DO_NOTHING },
137 { "unmap_complete", FULL_RELOAD },
140 #define NUM_PROBES ARRAY_SIZE (probe_info)
142 /* Return non-zero if GDB_SO_NAME and INFERIOR_SO_NAME represent
143 the same shared library. */
145 static int
146 svr4_same_1 (const char *gdb_so_name, const char *inferior_so_name)
148 if (strcmp (gdb_so_name, inferior_so_name) == 0)
149 return 1;
151 /* On Solaris, when starting inferior we think that dynamic linker is
152 /usr/lib/ld.so.1, but later on, the table of loaded shared libraries
153 contains /lib/ld.so.1. Sometimes one file is a link to another, but
154 sometimes they have identical content, but are not linked to each
155 other. We don't restrict this check for Solaris, but the chances
156 of running into this situation elsewhere are very low. */
157 if (strcmp (gdb_so_name, "/usr/lib/ld.so.1") == 0
158 && strcmp (inferior_so_name, "/lib/ld.so.1") == 0)
159 return 1;
161 /* Similarly, we observed the same issue with amd64 and sparcv9, but with
162 different locations. */
163 if (strcmp (gdb_so_name, "/usr/lib/amd64/ld.so.1") == 0
164 && strcmp (inferior_so_name, "/lib/amd64/ld.so.1") == 0)
165 return 1;
167 if (strcmp (gdb_so_name, "/usr/lib/sparcv9/ld.so.1") == 0
168 && strcmp (inferior_so_name, "/lib/sparcv9/ld.so.1") == 0)
169 return 1;
171 return 0;
174 static bool
175 svr4_same (const char *gdb_name, const char *inferior_name,
176 const lm_info_svr4 &gdb_lm_info,
177 const lm_info_svr4 &inferior_lm_info)
179 if (!svr4_same_1 (gdb_name, inferior_name))
180 return false;
182 /* There may be different instances of the same library, in different
183 namespaces. Each instance, however, must have been loaded at a
184 different address so its relocation offset would be different. */
185 return gdb_lm_info.l_addr_inferior == inferior_lm_info.l_addr_inferior;
188 static int
189 svr4_same (const solib &gdb, const solib &inferior)
191 auto *lmg
192 = gdb::checked_static_cast<const lm_info_svr4 *> (gdb.lm_info.get ());
193 auto *lmi
194 = gdb::checked_static_cast<const lm_info_svr4 *> (inferior.lm_info.get ());
196 return svr4_same (gdb.so_original_name.c_str (),
197 inferior.so_original_name.c_str (), *lmg, *lmi);
200 static lm_info_svr4_up
201 lm_info_read (CORE_ADDR lm_addr)
203 struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
204 lm_info_svr4_up lm_info;
206 gdb::byte_vector lm (lmo->link_map_size);
208 if (target_read_memory (lm_addr, lm.data (), lmo->link_map_size) != 0)
209 warning (_("Error reading shared library list entry at %s"),
210 paddress (current_inferior ()->arch (), lm_addr));
211 else
213 type *ptr_type
214 = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
216 lm_info = std::make_unique<lm_info_svr4> ();
217 lm_info->lm_addr = lm_addr;
219 lm_info->l_addr_inferior = extract_typed_address (&lm[lmo->l_addr_offset],
220 ptr_type);
221 lm_info->l_ld = extract_typed_address (&lm[lmo->l_ld_offset], ptr_type);
222 lm_info->l_next = extract_typed_address (&lm[lmo->l_next_offset],
223 ptr_type);
224 lm_info->l_prev = extract_typed_address (&lm[lmo->l_prev_offset],
225 ptr_type);
226 lm_info->l_name = extract_typed_address (&lm[lmo->l_name_offset],
227 ptr_type);
230 return lm_info;
233 static int
234 has_lm_dynamic_from_link_map (void)
236 struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
238 return lmo->l_ld_offset >= 0;
241 static CORE_ADDR
242 lm_addr_check (const solib &so, bfd *abfd)
244 auto *li = gdb::checked_static_cast<lm_info_svr4 *> (so.lm_info.get ());
246 if (!li->l_addr_p)
248 struct bfd_section *dyninfo_sect;
249 CORE_ADDR l_addr, l_dynaddr, dynaddr;
251 l_addr = li->l_addr_inferior;
253 if (! abfd || ! has_lm_dynamic_from_link_map ())
254 goto set_addr;
256 l_dynaddr = li->l_ld;
258 dyninfo_sect = bfd_get_section_by_name (abfd, ".dynamic");
259 if (dyninfo_sect == NULL)
260 goto set_addr;
262 dynaddr = bfd_section_vma (dyninfo_sect);
264 if (dynaddr + l_addr != l_dynaddr)
266 CORE_ADDR align = 0x1000;
267 CORE_ADDR minpagesize = align;
269 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
271 Elf_Internal_Ehdr *ehdr = elf_tdata (abfd)->elf_header;
272 Elf_Internal_Phdr *phdr = elf_tdata (abfd)->phdr;
273 int i;
275 align = 1;
277 for (i = 0; i < ehdr->e_phnum; i++)
278 if (phdr[i].p_type == PT_LOAD && phdr[i].p_align > align)
279 align = phdr[i].p_align;
281 minpagesize = get_elf_backend_data (abfd)->minpagesize;
284 /* Turn it into a mask. */
285 align--;
287 /* If the changes match the alignment requirements, we
288 assume we're using a core file that was generated by the
289 same binary, just prelinked with a different base offset.
290 If it doesn't match, we may have a different binary, the
291 same binary with the dynamic table loaded at an unrelated
292 location, or anything, really. To avoid regressions,
293 don't adjust the base offset in the latter case, although
294 odds are that, if things really changed, debugging won't
295 quite work.
297 One could expect more the condition
298 ((l_addr & align) == 0 && ((l_dynaddr - dynaddr) & align) == 0)
299 but the one below is relaxed for PPC. The PPC kernel supports
300 either 4k or 64k page sizes. To be prepared for 64k pages,
301 PPC ELF files are built using an alignment requirement of 64k.
302 However, when running on a kernel supporting 4k pages, the memory
303 mapping of the library may not actually happen on a 64k boundary!
305 (In the usual case where (l_addr & align) == 0, this check is
306 equivalent to the possibly expected check above.)
308 Even on PPC it must be zero-aligned at least for MINPAGESIZE. */
310 l_addr = l_dynaddr - dynaddr;
312 if ((l_addr & (minpagesize - 1)) == 0
313 && (l_addr & align) == ((l_dynaddr - dynaddr) & align))
315 if (info_verbose)
316 gdb_printf (_("Using PIC (Position Independent Code) "
317 "prelink displacement %s for \"%s\".\n"),
318 paddress (current_inferior ()->arch (), l_addr),
319 so.so_name.c_str ());
321 else
323 /* There is no way to verify the library file matches. prelink
324 can during prelinking of an unprelinked file (or unprelinking
325 of a prelinked file) shift the DYNAMIC segment by arbitrary
326 offset without any page size alignment. There is no way to
327 find out the ELF header and/or Program Headers for a limited
328 verification if it they match. One could do a verification
329 of the DYNAMIC segment. Still the found address is the best
330 one GDB could find. */
332 warning (_(".dynamic section for \"%s\" "
333 "is not at the expected address "
334 "(wrong library or version mismatch?)"),
335 so.so_name.c_str ());
339 set_addr:
340 li->l_addr = l_addr;
341 li->l_addr_p = 1;
344 return li->l_addr;
347 struct svr4_so
349 svr4_so (const char *name, lm_info_svr4_up lm_info)
350 : name (name), lm_info (std::move (lm_info))
353 std::string name;
354 lm_info_svr4_up lm_info;
357 /* Per pspace SVR4 specific data. */
359 struct svr4_info
361 /* Base of dynamic linker structures in default namespace. */
362 CORE_ADDR debug_base = 0;
364 /* Validity flag for debug_loader_offset. */
365 int debug_loader_offset_p = 0;
367 /* Load address for the dynamic linker, inferred. */
368 CORE_ADDR debug_loader_offset = 0;
370 /* Name of the dynamic linker, valid if debug_loader_offset_p. */
371 char *debug_loader_name = nullptr;
373 /* Load map address for the main executable in default namespace. */
374 CORE_ADDR main_lm_addr = 0;
376 CORE_ADDR interp_text_sect_low = 0;
377 CORE_ADDR interp_text_sect_high = 0;
378 CORE_ADDR interp_plt_sect_low = 0;
379 CORE_ADDR interp_plt_sect_high = 0;
381 /* True if the list of objects was last obtained from the target
382 via qXfer:libraries-svr4:read. */
383 bool using_xfer = false;
385 /* Table of struct probe_and_action instances, used by the
386 probes-based interface to map breakpoint addresses to probes
387 and their associated actions. Lookup is performed using
388 probe_and_action->prob->address. */
389 htab_up probes_table;
391 /* List of objects loaded into the inferior per namespace, used by the
392 probes-based interface.
394 The namespace is represented by the address of its corresponding
395 r_debug[_ext] object. We get the namespace id as argument to the
396 'reloc_complete' probe but we don't get it when scanning the load map
397 on attach.
399 The r_debug[_ext] objects may move when ld.so itself moves. In that
400 case, we expect also the global _r_debug to move so we can detect
401 this and reload everything. The r_debug[_ext] objects are not
402 expected to move individually.
404 The special entry zero is reserved for a linear list to support
405 gdbstubs that do not support namespaces. */
406 std::map<CORE_ADDR, std::vector<svr4_so>> solib_lists;
409 /* Per-program-space data key. */
410 static const registry<program_space>::key<svr4_info> solib_svr4_pspace_data;
412 /* Return whether DEBUG_BASE is the default namespace of INFO. */
414 static bool
415 svr4_is_default_namespace (const svr4_info *info, CORE_ADDR debug_base)
417 return (debug_base == info->debug_base);
420 /* Free the probes table. */
422 static void
423 free_probes_table (struct svr4_info *info)
425 info->probes_table.reset (nullptr);
428 /* Get the svr4 data for program space PSPACE. If none is found yet, add it now.
429 This function always returns a valid object. */
431 static struct svr4_info *
432 get_svr4_info (program_space *pspace)
434 struct svr4_info *info = solib_svr4_pspace_data.get (pspace);
436 if (info == NULL)
437 info = solib_svr4_pspace_data.emplace (pspace);
439 return info;
442 /* Local function prototypes */
444 static int match_main (const char *);
446 /* Read program header TYPE from inferior memory. The header is found
447 by scanning the OS auxiliary vector.
449 If TYPE == -1, return the program headers instead of the contents of
450 one program header.
452 Return vector of bytes holding the program header contents, or an empty
453 optional on failure. If successful and P_ARCH_SIZE is non-NULL, the target
454 architecture size (32-bit or 64-bit) is returned to *P_ARCH_SIZE. Likewise,
455 the base address of the section is returned in *BASE_ADDR. */
457 static std::optional<gdb::byte_vector>
458 read_program_header (int type, int *p_arch_size, CORE_ADDR *base_addr)
460 bfd_endian byte_order = gdbarch_byte_order (current_inferior ()->arch ());
461 CORE_ADDR at_phdr, at_phent, at_phnum, pt_phdr = 0;
462 int arch_size, sect_size;
463 CORE_ADDR sect_addr;
464 int pt_phdr_p = 0;
466 /* Get required auxv elements from target. */
467 if (target_auxv_search (AT_PHDR, &at_phdr) <= 0)
468 return {};
469 if (target_auxv_search (AT_PHENT, &at_phent) <= 0)
470 return {};
471 if (target_auxv_search (AT_PHNUM, &at_phnum) <= 0)
472 return {};
473 if (!at_phdr || !at_phnum)
474 return {};
476 /* Determine ELF architecture type. */
477 if (at_phent == sizeof (Elf32_External_Phdr))
478 arch_size = 32;
479 else if (at_phent == sizeof (Elf64_External_Phdr))
480 arch_size = 64;
481 else
482 return {};
484 /* Find the requested segment. */
485 if (type == -1)
487 sect_addr = at_phdr;
488 sect_size = at_phent * at_phnum;
490 else if (arch_size == 32)
492 Elf32_External_Phdr phdr;
493 int i;
495 /* Search for requested PHDR. */
496 for (i = 0; i < at_phnum; i++)
498 int p_type;
500 if (target_read_memory (at_phdr + i * sizeof (phdr),
501 (gdb_byte *)&phdr, sizeof (phdr)))
502 return {};
504 p_type = extract_unsigned_integer ((gdb_byte *) phdr.p_type,
505 4, byte_order);
507 if (p_type == PT_PHDR)
509 pt_phdr_p = 1;
510 pt_phdr = extract_unsigned_integer ((gdb_byte *) phdr.p_vaddr,
511 4, byte_order);
514 if (p_type == type)
515 break;
518 if (i == at_phnum)
519 return {};
521 /* Retrieve address and size. */
522 sect_addr = extract_unsigned_integer ((gdb_byte *)phdr.p_vaddr,
523 4, byte_order);
524 sect_size = extract_unsigned_integer ((gdb_byte *)phdr.p_memsz,
525 4, byte_order);
527 else
529 Elf64_External_Phdr phdr;
530 int i;
532 /* Search for requested PHDR. */
533 for (i = 0; i < at_phnum; i++)
535 int p_type;
537 if (target_read_memory (at_phdr + i * sizeof (phdr),
538 (gdb_byte *)&phdr, sizeof (phdr)))
539 return {};
541 p_type = extract_unsigned_integer ((gdb_byte *) phdr.p_type,
542 4, byte_order);
544 if (p_type == PT_PHDR)
546 pt_phdr_p = 1;
547 pt_phdr = extract_unsigned_integer ((gdb_byte *) phdr.p_vaddr,
548 8, byte_order);
551 if (p_type == type)
552 break;
555 if (i == at_phnum)
556 return {};
558 /* Retrieve address and size. */
559 sect_addr = extract_unsigned_integer ((gdb_byte *)phdr.p_vaddr,
560 8, byte_order);
561 sect_size = extract_unsigned_integer ((gdb_byte *)phdr.p_memsz,
562 8, byte_order);
565 /* PT_PHDR is optional, but we really need it
566 for PIE to make this work in general. */
568 if (pt_phdr_p)
570 /* at_phdr is real address in memory. pt_phdr is what pheader says it is.
571 Relocation offset is the difference between the two. */
572 sect_addr = sect_addr + (at_phdr - pt_phdr);
575 /* Read in requested program header. */
576 gdb::byte_vector buf (sect_size);
577 if (target_read_memory (sect_addr, buf.data (), sect_size))
578 return {};
580 if (p_arch_size)
581 *p_arch_size = arch_size;
582 if (base_addr)
583 *base_addr = sect_addr;
585 return buf;
589 /* Return program interpreter string. */
590 static std::optional<gdb::byte_vector>
591 find_program_interpreter (void)
593 /* If we have a current exec_bfd, use its section table. */
594 if (current_program_space->exec_bfd ()
595 && (bfd_get_flavour (current_program_space->exec_bfd ())
596 == bfd_target_elf_flavour))
598 struct bfd_section *interp_sect;
600 interp_sect = bfd_get_section_by_name (current_program_space->exec_bfd (),
601 ".interp");
602 if (interp_sect != NULL)
604 int sect_size = bfd_section_size (interp_sect);
606 gdb::byte_vector buf (sect_size);
607 bool res
608 = bfd_get_section_contents (current_program_space->exec_bfd (),
609 interp_sect, buf.data (), 0, sect_size);
610 if (res)
611 return buf;
615 /* If we didn't find it, use the target auxiliary vector. */
616 return read_program_header (PT_INTERP, NULL, NULL);
620 /* Scan for DESIRED_DYNTAG in .dynamic section of the target's main executable,
621 found by consulting the OS auxillary vector. If DESIRED_DYNTAG is found, 1
622 is returned and the corresponding PTR is set. */
624 static int
625 scan_dyntag_auxv (const int desired_dyntag, CORE_ADDR *ptr,
626 CORE_ADDR *ptr_addr)
628 bfd_endian byte_order = gdbarch_byte_order (current_inferior ()->arch ());
629 int arch_size, step;
630 long current_dyntag;
631 CORE_ADDR dyn_ptr;
632 CORE_ADDR base_addr;
634 /* Read in .dynamic section. */
635 std::optional<gdb::byte_vector> ph_data
636 = read_program_header (PT_DYNAMIC, &arch_size, &base_addr);
637 if (!ph_data)
638 return 0;
640 /* Iterate over BUF and scan for DYNTAG. If found, set PTR and return. */
641 step = (arch_size == 32) ? sizeof (Elf32_External_Dyn)
642 : sizeof (Elf64_External_Dyn);
643 for (gdb_byte *buf = ph_data->data (), *bufend = buf + ph_data->size ();
644 buf < bufend; buf += step)
646 if (arch_size == 32)
648 Elf32_External_Dyn *dynp = (Elf32_External_Dyn *) buf;
650 current_dyntag = extract_unsigned_integer ((gdb_byte *) dynp->d_tag,
651 4, byte_order);
652 dyn_ptr = extract_unsigned_integer ((gdb_byte *) dynp->d_un.d_ptr,
653 4, byte_order);
655 else
657 Elf64_External_Dyn *dynp = (Elf64_External_Dyn *) buf;
659 current_dyntag = extract_unsigned_integer ((gdb_byte *) dynp->d_tag,
660 8, byte_order);
661 dyn_ptr = extract_unsigned_integer ((gdb_byte *) dynp->d_un.d_ptr,
662 8, byte_order);
664 if (current_dyntag == DT_NULL)
665 break;
667 if (current_dyntag == desired_dyntag)
669 if (ptr)
670 *ptr = dyn_ptr;
672 if (ptr_addr)
673 *ptr_addr = base_addr + buf - ph_data->data ();
675 return 1;
679 return 0;
682 /* Locate the base address of dynamic linker structs for SVR4 elf
683 targets.
685 For SVR4 elf targets the address of the dynamic linker's runtime
686 structure is contained within the dynamic info section in the
687 executable file. The dynamic section is also mapped into the
688 inferior address space. Because the runtime loader fills in the
689 real address before starting the inferior, we have to read in the
690 dynamic info section from the inferior address space.
691 If there are any errors while trying to find the address, we
692 silently return 0, otherwise the found address is returned. */
694 static CORE_ADDR
695 elf_locate_base (void)
697 struct bound_minimal_symbol msymbol;
698 CORE_ADDR dyn_ptr, dyn_ptr_addr;
700 if (!svr4_have_link_map_offsets ())
701 return 0;
703 /* Look for DT_MIPS_RLD_MAP first. MIPS executables use this
704 instead of DT_DEBUG, although they sometimes contain an unused
705 DT_DEBUG. */
706 if (gdb_bfd_scan_elf_dyntag (DT_MIPS_RLD_MAP,
707 current_program_space->exec_bfd (),
708 &dyn_ptr, NULL)
709 || scan_dyntag_auxv (DT_MIPS_RLD_MAP, &dyn_ptr, NULL))
711 type *ptr_type
712 = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
713 gdb_byte *pbuf;
714 int pbuf_size = ptr_type->length ();
716 pbuf = (gdb_byte *) alloca (pbuf_size);
717 /* DT_MIPS_RLD_MAP contains a pointer to the address
718 of the dynamic link structure. */
719 if (target_read_memory (dyn_ptr, pbuf, pbuf_size))
720 return 0;
721 return extract_typed_address (pbuf, ptr_type);
724 /* Then check DT_MIPS_RLD_MAP_REL. MIPS executables now use this form
725 because of needing to support PIE. DT_MIPS_RLD_MAP will also exist
726 in non-PIE. */
727 if (gdb_bfd_scan_elf_dyntag (DT_MIPS_RLD_MAP_REL,
728 current_program_space->exec_bfd (),
729 &dyn_ptr, &dyn_ptr_addr)
730 || scan_dyntag_auxv (DT_MIPS_RLD_MAP_REL, &dyn_ptr, &dyn_ptr_addr))
732 type *ptr_type
733 = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
734 gdb_byte *pbuf;
735 int pbuf_size = ptr_type->length ();
737 pbuf = (gdb_byte *) alloca (pbuf_size);
738 /* DT_MIPS_RLD_MAP_REL contains an offset from the address of the
739 DT slot to the address of the dynamic link structure. */
740 if (target_read_memory (dyn_ptr + dyn_ptr_addr, pbuf, pbuf_size))
741 return 0;
742 return extract_typed_address (pbuf, ptr_type);
745 /* Find DT_DEBUG. */
746 if (gdb_bfd_scan_elf_dyntag (DT_DEBUG, current_program_space->exec_bfd (),
747 &dyn_ptr, NULL)
748 || scan_dyntag_auxv (DT_DEBUG, &dyn_ptr, NULL))
749 return dyn_ptr;
751 /* This may be a static executable. Look for the symbol
752 conventionally named _r_debug, as a last resort. */
753 msymbol = lookup_minimal_symbol ("_r_debug", NULL,
754 current_program_space->symfile_object_file);
755 if (msymbol.minsym != NULL)
756 return msymbol.value_address ();
758 /* DT_DEBUG entry not found. */
759 return 0;
762 /* Find the first element in the inferior's dynamic link map, and
763 return its address in the inferior. Return zero if the address
764 could not be determined.
766 FIXME: Perhaps we should validate the info somehow, perhaps by
767 checking r_version for a known version number, or r_state for
768 RT_CONSISTENT. */
770 static CORE_ADDR
771 solib_svr4_r_map (CORE_ADDR debug_base)
773 struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
774 type *ptr_type
775 = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
776 CORE_ADDR addr = 0;
780 addr = read_memory_typed_address (debug_base + lmo->r_map_offset,
781 ptr_type);
783 catch (const gdb_exception_error &ex)
785 exception_print (gdb_stderr, ex);
788 return addr;
791 /* Find r_brk from the inferior's debug base. */
793 static CORE_ADDR
794 solib_svr4_r_brk (struct svr4_info *info)
796 struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
797 type *ptr_type
798 = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
800 return read_memory_typed_address (info->debug_base + lmo->r_brk_offset,
801 ptr_type);
804 /* Find the link map for the dynamic linker (if it is not in the
805 normal list of loaded shared objects). */
807 static CORE_ADDR
808 solib_svr4_r_ldsomap (struct svr4_info *info)
810 struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
811 type *ptr_type
812 = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
813 enum bfd_endian byte_order = type_byte_order (ptr_type);
814 ULONGEST version = 0;
818 /* Check version, and return zero if `struct r_debug' doesn't have
819 the r_ldsomap member. */
820 version
821 = read_memory_unsigned_integer (info->debug_base + lmo->r_version_offset,
822 lmo->r_version_size, byte_order);
824 catch (const gdb_exception_error &ex)
826 exception_print (gdb_stderr, ex);
829 if (version < 2 || lmo->r_ldsomap_offset == -1)
830 return 0;
832 return read_memory_typed_address (info->debug_base + lmo->r_ldsomap_offset,
833 ptr_type);
836 /* Find the next namespace from the r_next field. */
838 static CORE_ADDR
839 solib_svr4_r_next (CORE_ADDR debug_base)
841 link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
842 type *ptr_type
843 = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
844 bfd_endian byte_order = type_byte_order (ptr_type);
845 ULONGEST version = 0;
849 version
850 = read_memory_unsigned_integer (debug_base + lmo->r_version_offset,
851 lmo->r_version_size, byte_order);
853 catch (const gdb_exception_error &ex)
855 exception_print (gdb_stderr, ex);
858 /* The r_next field is added with r_version == 2. */
859 if (version < 2 || lmo->r_next_offset == -1)
860 return 0;
862 return read_memory_typed_address (debug_base + lmo->r_next_offset,
863 ptr_type);
866 /* On Solaris systems with some versions of the dynamic linker,
867 ld.so's l_name pointer points to the SONAME in the string table
868 rather than into writable memory. So that GDB can find shared
869 libraries when loading a core file generated by gcore, ensure that
870 memory areas containing the l_name string are saved in the core
871 file. */
873 static int
874 svr4_keep_data_in_core (CORE_ADDR vaddr, unsigned long size)
876 struct svr4_info *info;
877 CORE_ADDR ldsomap;
878 CORE_ADDR name_lm;
880 info = get_svr4_info (current_program_space);
882 info->debug_base = elf_locate_base ();
883 if (info->debug_base == 0)
884 return 0;
886 ldsomap = solib_svr4_r_ldsomap (info);
887 if (!ldsomap)
888 return 0;
890 std::unique_ptr<lm_info_svr4> li = lm_info_read (ldsomap);
891 name_lm = li != NULL ? li->l_name : 0;
893 return (name_lm >= vaddr && name_lm < vaddr + size);
896 /* See solist.h. */
898 static int
899 open_symbol_file_object (int from_tty)
901 CORE_ADDR lm, l_name;
902 struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
903 type *ptr_type
904 = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
905 int l_name_size = ptr_type->length ();
906 gdb::byte_vector l_name_buf (l_name_size);
907 struct svr4_info *info = get_svr4_info (current_program_space);
908 symfile_add_flags add_flags = 0;
910 if (from_tty)
911 add_flags |= SYMFILE_VERBOSE;
913 if (current_program_space->symfile_object_file)
914 if (!query (_("Attempt to reload symbols from process? ")))
915 return 0;
917 /* Always locate the debug struct, in case it has moved. */
918 info->debug_base = elf_locate_base ();
919 if (info->debug_base == 0)
920 return 0; /* failed somehow... */
922 /* First link map member should be the executable. */
923 lm = solib_svr4_r_map (info->debug_base);
924 if (lm == 0)
925 return 0; /* failed somehow... */
927 /* Read address of name from target memory to GDB. */
928 read_memory (lm + lmo->l_name_offset, l_name_buf.data (), l_name_size);
930 /* Convert the address to host format. */
931 l_name = extract_typed_address (l_name_buf.data (), ptr_type);
933 if (l_name == 0)
934 return 0; /* No filename. */
936 /* Now fetch the filename from target memory. */
937 gdb::unique_xmalloc_ptr<char> filename
938 = target_read_string (l_name, SO_NAME_MAX_PATH_SIZE - 1);
940 if (filename == nullptr)
942 warning (_("failed to read exec filename from attached file"));
943 return 0;
946 /* Have a pathname: read the symbol file. */
947 symbol_file_add_main (filename.get (), add_flags);
949 return 1;
952 /* Data exchange structure for the XML parser as returned by
953 svr4_current_sos_via_xfer_libraries. */
955 struct svr4_library_list
957 /* The so list for the current namespace. This is internal to XML
958 parsing. */
959 std::vector<svr4_so> *cur_list;
961 /* Inferior address of struct link_map used for the main executable. It is
962 NULL if not known. */
963 CORE_ADDR main_lm;
965 /* List of objects loaded into the inferior per namespace. This does
966 not include any default sos.
968 See comment on struct svr4_info.solib_lists. */
969 std::map<CORE_ADDR, std::vector<svr4_so>> solib_lists;
972 /* This module's 'free_objfile' observer. */
974 static void
975 svr4_free_objfile_observer (struct objfile *objfile)
977 probes_table_remove_objfile_probes (objfile);
980 /* Implement solib_ops.clear_so. */
982 static void
983 svr4_clear_so (const solib &so)
985 auto *li = gdb::checked_static_cast<lm_info_svr4 *> (so.lm_info.get ());
987 if (li != NULL)
988 li->l_addr_p = 0;
991 /* Create the so_list objects equivalent to the svr4_sos in SOS. */
993 static intrusive_list<solib>
994 so_list_from_svr4_sos (const std::vector<svr4_so> &sos)
996 intrusive_list<solib> dst;
998 for (const svr4_so &so : sos)
1000 struct solib *newobj = new struct solib;
1002 newobj->so_name = so.name;
1003 newobj->so_original_name = so.name;
1004 newobj->lm_info = std::make_unique<lm_info_svr4> (*so.lm_info);
1006 dst.push_back (*newobj);
1009 return dst;
1012 #ifdef HAVE_LIBEXPAT
1014 #include "xml-support.h"
1016 /* Handle the start of a <library> element. Note: new elements are added
1017 at the tail of the list, keeping the list in order. */
1019 static void
1020 library_list_start_library (struct gdb_xml_parser *parser,
1021 const struct gdb_xml_element *element,
1022 void *user_data,
1023 std::vector<gdb_xml_value> &attributes)
1025 struct svr4_library_list *list = (struct svr4_library_list *) user_data;
1026 const char *name
1027 = (const char *) xml_find_attribute (attributes, "name")->value.get ();
1028 ULONGEST *lmp
1029 = (ULONGEST *) xml_find_attribute (attributes, "lm")->value.get ();
1030 ULONGEST *l_addrp
1031 = (ULONGEST *) xml_find_attribute (attributes, "l_addr")->value.get ();
1032 ULONGEST *l_ldp
1033 = (ULONGEST *) xml_find_attribute (attributes, "l_ld")->value.get ();
1035 lm_info_svr4_up li = std::make_unique<lm_info_svr4> ();
1036 li->lm_addr = *lmp;
1037 li->l_addr_inferior = *l_addrp;
1038 li->l_ld = *l_ldp;
1040 std::vector<svr4_so> *solist;
1042 /* Older versions did not supply lmid. Put the element into the flat
1043 list of the special namespace zero in that case. */
1044 gdb_xml_value *at_lmid = xml_find_attribute (attributes, "lmid");
1045 if (at_lmid == nullptr)
1046 solist = list->cur_list;
1047 else
1049 ULONGEST lmid = *(ULONGEST *) at_lmid->value.get ();
1050 solist = &list->solib_lists[lmid];
1053 solist->emplace_back (name, std::move (li));
1056 /* Handle the start of a <library-list-svr4> element. */
1058 static void
1059 svr4_library_list_start_list (struct gdb_xml_parser *parser,
1060 const struct gdb_xml_element *element,
1061 void *user_data,
1062 std::vector<gdb_xml_value> &attributes)
1064 struct svr4_library_list *list = (struct svr4_library_list *) user_data;
1065 const char *version
1066 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
1067 struct gdb_xml_value *main_lm = xml_find_attribute (attributes, "main-lm");
1069 if (strcmp (version, "1.0") != 0)
1070 gdb_xml_error (parser,
1071 _("SVR4 Library list has unsupported version \"%s\""),
1072 version);
1074 if (main_lm)
1075 list->main_lm = *(ULONGEST *) main_lm->value.get ();
1077 /* Older gdbserver do not support namespaces. We use the special
1078 namespace zero for a linear list of libraries. */
1079 list->cur_list = &list->solib_lists[0];
1082 /* The allowed elements and attributes for an XML library list.
1083 The root element is a <library-list>. */
1085 static const struct gdb_xml_attribute svr4_library_attributes[] =
1087 { "name", GDB_XML_AF_NONE, NULL, NULL },
1088 { "lm", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
1089 { "l_addr", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
1090 { "l_ld", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
1091 { "lmid", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
1092 { NULL, GDB_XML_AF_NONE, NULL, NULL }
1095 static const struct gdb_xml_element svr4_library_list_children[] =
1098 "library", svr4_library_attributes, NULL,
1099 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
1100 library_list_start_library, NULL
1102 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
1105 static const struct gdb_xml_attribute svr4_library_list_attributes[] =
1107 { "version", GDB_XML_AF_NONE, NULL, NULL },
1108 { "main-lm", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
1109 { NULL, GDB_XML_AF_NONE, NULL, NULL }
1112 static const struct gdb_xml_element svr4_library_list_elements[] =
1114 { "library-list-svr4", svr4_library_list_attributes, svr4_library_list_children,
1115 GDB_XML_EF_NONE, svr4_library_list_start_list, NULL },
1116 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
1119 /* Parse qXfer:libraries:read packet into *SO_LIST_RETURN. Return 1 if
1121 Return 0 if packet not supported, *SO_LIST_RETURN is not modified in such
1122 case. Return 1 if *SO_LIST_RETURN contains the library list, it may be
1123 empty, caller is responsible for freeing all its entries. */
1125 static int
1126 svr4_parse_libraries (const char *document, struct svr4_library_list *list)
1128 auto cleanup = make_scope_exit ([list] ()
1129 { list->solib_lists.clear (); });
1131 list->cur_list = nullptr;
1132 list->main_lm = 0;
1133 list->solib_lists.clear ();
1134 if (gdb_xml_parse_quick (_("target library list"), "library-list-svr4.dtd",
1135 svr4_library_list_elements, document, list) == 0)
1137 /* Parsed successfully, keep the result. */
1138 cleanup.release ();
1139 return 1;
1142 return 0;
1145 /* Attempt to get so_list from target via qXfer:libraries-svr4:read packet.
1147 Return 0 if packet not supported, *SO_LIST_RETURN is not modified in such
1148 case. Return 1 if *SO_LIST_RETURN contains the library list, it may be
1149 empty, caller is responsible for freeing all its entries.
1151 Note that ANNEX must be NULL if the remote does not explicitly allow
1152 qXfer:libraries-svr4:read packets with non-empty annexes. Support for
1153 this can be checked using target_augmented_libraries_svr4_read (). */
1155 static int
1156 svr4_current_sos_via_xfer_libraries (struct svr4_library_list *list,
1157 const char *annex)
1159 gdb_assert (annex == NULL || target_augmented_libraries_svr4_read ());
1161 /* Fetch the list of shared libraries. */
1162 std::optional<gdb::char_vector> svr4_library_document
1163 = target_read_stralloc (current_inferior ()->top_target (),
1164 TARGET_OBJECT_LIBRARIES_SVR4,
1165 annex);
1166 if (!svr4_library_document)
1167 return 0;
1169 return svr4_parse_libraries (svr4_library_document->data (), list);
1172 #else
1174 static int
1175 svr4_current_sos_via_xfer_libraries (struct svr4_library_list *list,
1176 const char *annex)
1178 return 0;
1181 #endif
1183 /* If no shared library information is available from the dynamic
1184 linker, build a fallback list from other sources. */
1186 static intrusive_list<solib>
1187 svr4_default_sos (svr4_info *info)
1189 if (!info->debug_loader_offset_p)
1190 return {};
1192 solib *newobj = new solib;
1193 auto li = std::make_unique<lm_info_svr4> ();
1195 /* Nothing will ever check the other fields if we set l_addr_p. */
1196 li->l_addr = li->l_addr_inferior = info->debug_loader_offset;
1197 li->l_addr_p = 1;
1199 newobj->lm_info = std::move (li);
1200 newobj->so_name = info->debug_loader_name;
1201 newobj->so_original_name = newobj->so_name;
1203 intrusive_list<solib> sos;
1204 sos.push_back (*newobj);
1206 return sos;
1209 /* Read the whole inferior libraries chain starting at address LM.
1210 Expect the first entry in the chain's previous entry to be PREV_LM.
1211 Add the entries to SOS. Ignore the first entry if IGNORE_FIRST and set
1212 global MAIN_LM_ADDR according to it. Returns nonzero upon success. If zero
1213 is returned the entries stored to LINK_PTR_PTR are still valid although they may
1214 represent only part of the inferior library list. */
1216 static int
1217 svr4_read_so_list (svr4_info *info, CORE_ADDR lm, CORE_ADDR prev_lm,
1218 std::vector<svr4_so> &sos, int ignore_first)
1220 CORE_ADDR first_l_name = 0;
1221 CORE_ADDR next_lm;
1223 for (; lm != 0; prev_lm = lm, lm = next_lm)
1225 lm_info_svr4_up li = lm_info_read (lm);
1226 if (li == NULL)
1227 return 0;
1229 next_lm = li->l_next;
1231 if (li->l_prev != prev_lm)
1233 warning (_("Corrupted shared library list: %s != %s"),
1234 paddress (current_inferior ()->arch (), prev_lm),
1235 paddress (current_inferior ()->arch (), li->l_prev));
1236 return 0;
1239 /* For SVR4 versions, the first entry in the link map is for the
1240 inferior executable, so we must ignore it. For some versions of
1241 SVR4, it has no name. For others (Solaris 2.3 for example), it
1242 does have a name, so we can no longer use a missing name to
1243 decide when to ignore it. */
1244 if (ignore_first && li->l_prev == 0)
1246 first_l_name = li->l_name;
1247 info->main_lm_addr = li->lm_addr;
1248 continue;
1251 /* Extract this shared object's name. */
1252 gdb::unique_xmalloc_ptr<char> name
1253 = target_read_string (li->l_name, SO_NAME_MAX_PATH_SIZE - 1);
1254 if (name == nullptr)
1256 /* If this entry's l_name address matches that of the
1257 inferior executable, then this is not a normal shared
1258 object, but (most likely) a vDSO. In this case, silently
1259 skip it; otherwise emit a warning. */
1260 if (first_l_name == 0 || li->l_name != first_l_name)
1261 warning (_("Can't read pathname for load map."));
1262 continue;
1265 /* If this entry has no name, or its name matches the name
1266 for the main executable, don't include it in the list. */
1267 if (*name == '\0' || match_main (name.get ()))
1268 continue;
1270 sos.emplace_back (name.get (), std::move (li));
1273 return 1;
1276 /* Read the full list of currently loaded shared objects directly
1277 from the inferior, without referring to any libraries read and
1278 stored by the probes interface. Handle special cases relating
1279 to the first elements of the list in default namespace. */
1281 static void
1282 svr4_current_sos_direct (struct svr4_info *info)
1284 CORE_ADDR lm;
1285 bool ignore_first;
1286 struct svr4_library_list library_list;
1288 /* Remove any old libraries. We're going to read them back in again. */
1289 info->solib_lists.clear ();
1291 /* Fall back to manual examination of the target if the packet is not
1292 supported or gdbserver failed to find DT_DEBUG. gdb.server/solib-list.exp
1293 tests a case where gdbserver cannot find the shared libraries list while
1294 GDB itself is able to find it via SYMFILE_OBJFILE.
1296 Unfortunately statically linked inferiors will also fall back through this
1297 suboptimal code path. */
1299 info->using_xfer = svr4_current_sos_via_xfer_libraries (&library_list,
1300 NULL);
1301 if (info->using_xfer)
1303 if (library_list.main_lm)
1304 info->main_lm_addr = library_list.main_lm;
1306 /* Remove an empty special zero namespace so we know that when there
1307 is one, it is actually used, and we have a flat list without
1308 namespace information. */
1309 auto it_0 = library_list.solib_lists.find (0);
1310 if (it_0 != library_list.solib_lists.end ()
1311 && it_0->second.empty ())
1312 library_list.solib_lists.erase (it_0);
1314 /* Replace the (empty) solib_lists in INFO with the one generated
1315 from the target. We don't want to copy it on assignment and then
1316 delete the original afterwards, so let's just swap the
1317 internals. */
1318 std::swap (info->solib_lists, library_list.solib_lists);
1319 return;
1322 /* If we can't find the dynamic linker's base structure, this
1323 must not be a dynamically linked executable. Hmm. */
1324 info->debug_base = elf_locate_base ();
1325 if (info->debug_base == 0)
1326 return;
1328 /* Assume that everything is a library if the dynamic loader was loaded
1329 late by a static executable. */
1330 if (current_program_space->exec_bfd ()
1331 && bfd_get_section_by_name (current_program_space->exec_bfd (),
1332 ".dynamic") == NULL)
1333 ignore_first = false;
1334 else
1335 ignore_first = true;
1337 auto cleanup = make_scope_exit ([info] ()
1338 { info->solib_lists.clear (); });
1340 /* Collect the sos in each namespace. */
1341 CORE_ADDR debug_base = info->debug_base;
1342 for (; debug_base != 0;
1343 ignore_first = false, debug_base = solib_svr4_r_next (debug_base))
1345 /* Walk the inferior's link map list, and build our so_list list. */
1346 lm = solib_svr4_r_map (debug_base);
1347 if (lm != 0)
1348 svr4_read_so_list (info, lm, 0, info->solib_lists[debug_base],
1349 ignore_first);
1352 /* On Solaris, the dynamic linker is not in the normal list of
1353 shared objects, so make sure we pick it up too. Having
1354 symbol information for the dynamic linker is quite crucial
1355 for skipping dynamic linker resolver code.
1357 Note that we interpret the ldsomap load map address as 'virtual'
1358 r_debug object. If we added it to the default namespace (as it was),
1359 we would probably run into inconsistencies with the load map's
1360 prev/next links (I wonder if we did). */
1361 debug_base = solib_svr4_r_ldsomap (info);
1362 if (debug_base != 0)
1364 /* Add the dynamic linker's namespace unless we already did. */
1365 if (info->solib_lists.find (debug_base) == info->solib_lists.end ())
1366 svr4_read_so_list (info, debug_base, 0, info->solib_lists[debug_base],
1370 cleanup.release ();
1373 /* Collect sos read and stored by the probes interface. */
1375 static intrusive_list<solib>
1376 svr4_collect_probes_sos (svr4_info *info)
1378 intrusive_list<solib> res;
1380 for (const auto &tuple : info->solib_lists)
1382 const std::vector<svr4_so> &sos = tuple.second;
1383 res.splice (so_list_from_svr4_sos (sos));
1386 return res;
1389 /* Implement the main part of the "current_sos" solib_ops
1390 method. */
1392 static intrusive_list<solib>
1393 svr4_current_sos_1 (svr4_info *info)
1395 intrusive_list<solib> sos;
1397 /* If we're using the probes interface, we can use the cache as it will
1398 be maintained by probe update/reload actions. */
1399 if (info->probes_table != nullptr)
1400 sos = svr4_collect_probes_sos (info);
1402 /* If we're not using the probes interface or if we didn't cache
1403 anything, read the sos to fill the cache, then collect them from the
1404 cache. */
1405 if (sos.empty ())
1407 svr4_current_sos_direct (info);
1409 sos = svr4_collect_probes_sos (info);
1410 if (sos.empty ())
1411 sos = svr4_default_sos (info);
1414 return sos;
1417 /* Implement the "current_sos" solib_ops method. */
1419 static intrusive_list<solib>
1420 svr4_current_sos ()
1422 svr4_info *info = get_svr4_info (current_program_space);
1423 intrusive_list<solib> sos = svr4_current_sos_1 (info);
1424 struct mem_range vsyscall_range;
1426 /* Filter out the vDSO module, if present. Its symbol file would
1427 not be found on disk. The vDSO/vsyscall's OBJFILE is instead
1428 managed by symfile-mem.c:add_vsyscall_page. */
1429 if (gdbarch_vsyscall_range (current_inferior ()->arch (), &vsyscall_range)
1430 && vsyscall_range.length != 0)
1432 for (auto so = sos.begin (); so != sos.end (); )
1434 /* We can't simply match the vDSO by starting address alone,
1435 because lm_info->l_addr_inferior (and also l_addr) do not
1436 necessarily represent the real starting address of the
1437 ELF if the vDSO's ELF itself is "prelinked". The l_ld
1438 field (the ".dynamic" section of the shared object)
1439 always points at the absolute/resolved address though.
1440 So check whether that address is inside the vDSO's
1441 mapping instead.
1443 E.g., on Linux 3.16 (x86_64) the vDSO is a regular
1444 0-based ELF, and we see:
1446 (gdb) info auxv
1447 33 AT_SYSINFO_EHDR System-supplied DSO's ELF header 0x7ffff7ffb000
1448 (gdb) p/x *_r_debug.r_map.l_next
1449 $1 = {l_addr = 0x7ffff7ffb000, ..., l_ld = 0x7ffff7ffb318, ...}
1451 And on Linux 2.6.32 (x86_64) we see:
1453 (gdb) info auxv
1454 33 AT_SYSINFO_EHDR System-supplied DSO's ELF header 0x7ffff7ffe000
1455 (gdb) p/x *_r_debug.r_map.l_next
1456 $5 = {l_addr = 0x7ffff88fe000, ..., l_ld = 0x7ffff7ffe580, ... }
1458 Dumping that vDSO shows:
1460 (gdb) info proc mappings
1461 0x7ffff7ffe000 0x7ffff7fff000 0x1000 0 [vdso]
1462 (gdb) dump memory vdso.bin 0x7ffff7ffe000 0x7ffff7fff000
1463 # readelf -Wa vdso.bin
1464 [...]
1465 Entry point address: 0xffffffffff700700
1466 [...]
1467 Section Headers:
1468 [Nr] Name Type Address Off Size
1469 [ 0] NULL 0000000000000000 000000 000000
1470 [ 1] .hash HASH ffffffffff700120 000120 000038
1471 [ 2] .dynsym DYNSYM ffffffffff700158 000158 0000d8
1472 [...]
1473 [ 9] .dynamic DYNAMIC ffffffffff700580 000580 0000f0
1476 auto *li = gdb::checked_static_cast<lm_info_svr4 *> (so->lm_info.get ());
1478 if (address_in_mem_range (li->l_ld, &vsyscall_range))
1480 auto next = sos.erase (so);
1481 delete &*so;
1482 so = next;
1483 break;
1486 ++so;
1490 return sos;
1493 /* Get the address of the link_map for a given OBJFILE. */
1495 CORE_ADDR
1496 svr4_fetch_objfile_link_map (struct objfile *objfile)
1498 struct svr4_info *info = get_svr4_info (objfile->pspace);
1500 /* Cause svr4_current_sos() to be run if it hasn't been already. */
1501 if (info->main_lm_addr == 0)
1502 solib_add (NULL, 0, auto_solib_add);
1504 /* svr4_current_sos() will set main_lm_addr for the main executable. */
1505 if (objfile == current_program_space->symfile_object_file)
1506 return info->main_lm_addr;
1508 /* The other link map addresses may be found by examining the list
1509 of shared libraries. */
1510 for (const solib &so : current_program_space->solibs ())
1511 if (so.objfile == objfile)
1513 auto *li
1514 = gdb::checked_static_cast<lm_info_svr4 *> (so.lm_info.get ());
1516 return li->lm_addr;
1519 /* Not found! */
1520 return 0;
1523 /* On some systems, the only way to recognize the link map entry for
1524 the main executable file is by looking at its name. Return
1525 non-zero iff SONAME matches one of the known main executable names. */
1527 static int
1528 match_main (const char *soname)
1530 const char * const *mainp;
1532 for (mainp = main_name_list; *mainp != NULL; mainp++)
1534 if (strcmp (soname, *mainp) == 0)
1535 return (1);
1538 return (0);
1541 /* Return 1 if PC lies in the dynamic symbol resolution code of the
1542 SVR4 run time loader. */
1545 svr4_in_dynsym_resolve_code (CORE_ADDR pc)
1547 struct svr4_info *info = get_svr4_info (current_program_space);
1549 return ((pc >= info->interp_text_sect_low
1550 && pc < info->interp_text_sect_high)
1551 || (pc >= info->interp_plt_sect_low
1552 && pc < info->interp_plt_sect_high)
1553 || in_plt_section (pc)
1554 || in_gnu_ifunc_stub (pc));
1557 /* Given an executable's ABFD and target, compute the entry-point
1558 address. */
1560 static CORE_ADDR
1561 exec_entry_point (struct bfd *abfd, struct target_ops *targ)
1563 CORE_ADDR addr;
1565 /* KevinB wrote ... for most targets, the address returned by
1566 bfd_get_start_address() is the entry point for the start
1567 function. But, for some targets, bfd_get_start_address() returns
1568 the address of a function descriptor from which the entry point
1569 address may be extracted. This address is extracted by
1570 gdbarch_convert_from_func_ptr_addr(). The method
1571 gdbarch_convert_from_func_ptr_addr() is the merely the identify
1572 function for targets which don't use function descriptors. */
1573 addr = gdbarch_convert_from_func_ptr_addr (current_inferior ()->arch (),
1574 bfd_get_start_address (abfd),
1575 targ);
1576 return gdbarch_addr_bits_remove (current_inferior ()->arch (), addr);
1579 /* A probe and its associated action. */
1581 struct probe_and_action
1583 /* The probe. */
1584 probe *prob;
1586 /* The relocated address of the probe. */
1587 CORE_ADDR address;
1589 /* The action. */
1590 enum probe_action action;
1592 /* The objfile where this probe was found. */
1593 struct objfile *objfile;
1596 /* Returns a hash code for the probe_and_action referenced by p. */
1598 static hashval_t
1599 hash_probe_and_action (const void *p)
1601 const struct probe_and_action *pa = (const struct probe_and_action *) p;
1603 return (hashval_t) pa->address;
1606 /* Returns non-zero if the probe_and_actions referenced by p1 and p2
1607 are equal. */
1609 static int
1610 equal_probe_and_action (const void *p1, const void *p2)
1612 const struct probe_and_action *pa1 = (const struct probe_and_action *) p1;
1613 const struct probe_and_action *pa2 = (const struct probe_and_action *) p2;
1615 return pa1->address == pa2->address;
1618 /* Traversal function for probes_table_remove_objfile_probes. */
1620 static int
1621 probes_table_htab_remove_objfile_probes (void **slot, void *info)
1623 probe_and_action *pa = (probe_and_action *) *slot;
1624 struct objfile *objfile = (struct objfile *) info;
1626 if (pa->objfile == objfile)
1627 htab_clear_slot (get_svr4_info (objfile->pspace)->probes_table.get (),
1628 slot);
1630 return 1;
1633 /* Remove all probes that belong to OBJFILE from the probes table. */
1635 static void
1636 probes_table_remove_objfile_probes (struct objfile *objfile)
1638 svr4_info *info = get_svr4_info (objfile->pspace);
1639 if (info->probes_table != nullptr)
1640 htab_traverse_noresize (info->probes_table.get (),
1641 probes_table_htab_remove_objfile_probes, objfile);
1644 /* Register a solib event probe and its associated action in the
1645 probes table. */
1647 static void
1648 register_solib_event_probe (svr4_info *info, struct objfile *objfile,
1649 probe *prob, CORE_ADDR address,
1650 enum probe_action action)
1652 struct probe_and_action lookup, *pa;
1653 void **slot;
1655 /* Create the probes table, if necessary. */
1656 if (info->probes_table == NULL)
1657 info->probes_table.reset (htab_create_alloc (1, hash_probe_and_action,
1658 equal_probe_and_action,
1659 xfree, xcalloc, xfree));
1661 lookup.address = address;
1662 slot = htab_find_slot (info->probes_table.get (), &lookup, INSERT);
1663 gdb_assert (*slot == HTAB_EMPTY_ENTRY);
1665 pa = XCNEW (struct probe_and_action);
1666 pa->prob = prob;
1667 pa->address = address;
1668 pa->action = action;
1669 pa->objfile = objfile;
1671 *slot = pa;
1674 /* Get the solib event probe at the specified location, and the
1675 action associated with it. Returns NULL if no solib event probe
1676 was found. */
1678 static struct probe_and_action *
1679 solib_event_probe_at (struct svr4_info *info, CORE_ADDR address)
1681 struct probe_and_action lookup;
1682 void **slot;
1684 lookup.address = address;
1685 slot = htab_find_slot (info->probes_table.get (), &lookup, NO_INSERT);
1687 if (slot == NULL)
1688 return NULL;
1690 return (struct probe_and_action *) *slot;
1693 /* Decide what action to take when the specified solib event probe is
1694 hit. */
1696 static enum probe_action
1697 solib_event_probe_action (struct probe_and_action *pa)
1699 enum probe_action action;
1700 unsigned probe_argc = 0;
1701 frame_info_ptr frame = get_current_frame ();
1703 action = pa->action;
1704 if (action == DO_NOTHING || action == PROBES_INTERFACE_FAILED)
1705 return action;
1707 gdb_assert (action == FULL_RELOAD || action == UPDATE_OR_RELOAD);
1709 /* Check that an appropriate number of arguments has been supplied.
1710 We expect:
1711 arg0: Lmid_t lmid (mandatory)
1712 arg1: struct r_debug *debug_base (mandatory)
1713 arg2: struct link_map *new (optional, for incremental updates) */
1716 probe_argc = pa->prob->get_argument_count (get_frame_arch (frame));
1718 catch (const gdb_exception_error &ex)
1720 exception_print (gdb_stderr, ex);
1721 probe_argc = 0;
1724 /* If get_argument_count throws an exception, probe_argc will be set
1725 to zero. However, if pa->prob does not have arguments, then
1726 get_argument_count will succeed but probe_argc will also be zero.
1727 Both cases happen because of different things, but they are
1728 treated equally here: action will be set to
1729 PROBES_INTERFACE_FAILED. */
1730 if (probe_argc == 2)
1731 action = FULL_RELOAD;
1732 else if (probe_argc < 2)
1733 action = PROBES_INTERFACE_FAILED;
1735 return action;
1738 /* Populate the shared object list by reading the entire list of
1739 shared objects from the inferior. Handle special cases relating
1740 to the first elements of the list. Returns nonzero on success. */
1742 static int
1743 solist_update_full (struct svr4_info *info)
1745 svr4_current_sos_direct (info);
1747 return 1;
1750 /* Update the shared object list starting from the link-map entry
1751 passed by the linker in the probe's third argument. Returns
1752 nonzero if the list was successfully updated, or zero to indicate
1753 failure. */
1755 static int
1756 solist_update_incremental (svr4_info *info, CORE_ADDR debug_base,
1757 CORE_ADDR lm)
1759 /* Fall back to a full update if we are using a remote target
1760 that does not support incremental transfers. */
1761 if (info->using_xfer && !target_augmented_libraries_svr4_read ())
1762 return 0;
1764 /* Fall back to a full update if we used the special namespace zero. We
1765 wouldn't be able to find the last item in the DEBUG_BASE namespace
1766 and hence get the prev link wrong. */
1767 if (info->solib_lists.find (0) != info->solib_lists.end ())
1768 return 0;
1770 std::vector<svr4_so> &solist = info->solib_lists[debug_base];
1771 CORE_ADDR prev_lm;
1773 if (solist.empty ())
1775 /* svr4_current_sos_direct contains logic to handle a number of
1776 special cases relating to the first elements of the list in
1777 default namespace. To avoid duplicating this logic we defer to
1778 solist_update_full in this case. */
1779 if (svr4_is_default_namespace (info, debug_base))
1780 return 0;
1782 prev_lm = 0;
1784 else
1785 prev_lm = solist.back ().lm_info->lm_addr;
1787 /* Read the new objects. */
1788 if (info->using_xfer)
1790 struct svr4_library_list library_list;
1791 char annex[64];
1793 /* Unknown key=value pairs are ignored by the gdbstub. */
1794 xsnprintf (annex, sizeof (annex), "lmid=%s;start=%s;prev=%s",
1795 phex_nz (debug_base, sizeof (debug_base)),
1796 phex_nz (lm, sizeof (lm)),
1797 phex_nz (prev_lm, sizeof (prev_lm)));
1798 if (!svr4_current_sos_via_xfer_libraries (&library_list, annex))
1799 return 0;
1801 /* Get the so list from the target. We replace the list in the
1802 target response so we can easily check that the response only
1803 covers one namespace.
1805 We expect gdbserver to provide updates for the namespace that
1806 contains LM, which would be this namespace... */
1807 std::vector<svr4_so> sos;
1808 auto it_debug_base = library_list.solib_lists.find (debug_base);
1809 if (it_debug_base != library_list.solib_lists.end ())
1810 std::swap (sos, it_debug_base->second);
1811 else
1813 /* ...or for the special zero namespace for earlier versions... */
1814 auto it_0 = library_list.solib_lists.find (0);
1815 if (it_0 != library_list.solib_lists.end ())
1816 std::swap (sos, it_0->second);
1819 /* ...but nothing else. */
1820 for (const auto &tuple : library_list.solib_lists)
1821 gdb_assert (tuple.second.empty ());
1823 std::move (sos.begin (), sos.end (), std::back_inserter (solist));
1825 else
1827 /* IGNORE_FIRST may safely be set to zero here because the
1828 above check and deferral to solist_update_full ensures
1829 that this call to svr4_read_so_list will never see the
1830 first element. */
1831 if (!svr4_read_so_list (info, lm, prev_lm, solist, 0))
1832 return 0;
1835 return 1;
1838 /* Disable the probes-based linker interface and revert to the
1839 original interface. We don't reset the breakpoints as the
1840 ones set up for the probes-based interface are adequate. */
1842 static void
1843 disable_probes_interface (svr4_info *info)
1845 warning (_("Probes-based dynamic linker interface failed.\n"
1846 "Reverting to original interface."));
1848 free_probes_table (info);
1849 info->solib_lists.clear ();
1852 /* Update the solib list as appropriate when using the
1853 probes-based linker interface. Do nothing if using the
1854 standard interface. */
1856 static void
1857 svr4_handle_solib_event (void)
1859 struct svr4_info *info = get_svr4_info (current_program_space);
1860 struct probe_and_action *pa;
1861 enum probe_action action;
1862 struct value *val = NULL;
1863 CORE_ADDR pc, debug_base, lm = 0;
1864 frame_info_ptr frame = get_current_frame ();
1866 /* Do nothing if not using the probes interface. */
1867 if (info->probes_table == NULL)
1868 return;
1870 pc = regcache_read_pc (get_thread_regcache (inferior_thread ()));
1871 pa = solib_event_probe_at (info, pc);
1872 if (pa == nullptr)
1874 /* When some solib ops sits above us, it can respond to a solib event
1875 by calling in here. This is done assuming that if the current event
1876 is not an SVR4 solib event, calling here should be a no-op. */
1877 return;
1880 /* If anything goes wrong we revert to the original linker
1881 interface. */
1882 auto cleanup = make_scope_exit ([info] ()
1884 disable_probes_interface (info);
1887 action = solib_event_probe_action (pa);
1888 if (action == PROBES_INTERFACE_FAILED)
1889 return;
1891 if (action == DO_NOTHING)
1893 cleanup.release ();
1894 return;
1897 /* evaluate_argument looks up symbols in the dynamic linker
1898 using find_pc_section. find_pc_section is accelerated by a cache
1899 called the section map. The section map is invalidated every
1900 time a shared library is loaded or unloaded, and if the inferior
1901 is generating a lot of shared library events then the section map
1902 will be updated every time svr4_handle_solib_event is called.
1903 We called find_pc_section in svr4_create_solib_event_breakpoints,
1904 so we can guarantee that the dynamic linker's sections are in the
1905 section map. We can therefore inhibit section map updates across
1906 these calls to evaluate_argument and save a lot of time. */
1908 scoped_restore inhibit_updates
1909 = inhibit_section_map_updates (current_program_space);
1913 val = pa->prob->evaluate_argument (1, frame);
1915 catch (const gdb_exception_error &ex)
1917 exception_print (gdb_stderr, ex);
1918 val = NULL;
1921 if (val == NULL)
1922 return;
1924 debug_base = value_as_address (val);
1925 if (debug_base == 0)
1926 return;
1928 /* If the global _r_debug object moved, we need to reload everything
1929 since we cannot identify namespaces (by the location of their
1930 r_debug_ext object) anymore. */
1931 CORE_ADDR global_debug_base = elf_locate_base ();
1932 if (global_debug_base != info->debug_base)
1934 info->debug_base = global_debug_base;
1935 action = FULL_RELOAD;
1938 if (info->debug_base == 0)
1940 /* It's possible for the reloc_complete probe to be triggered before
1941 the linker has set the DT_DEBUG pointer (for example, when the
1942 linker has finished relocating an LD_AUDIT library or its
1943 dependencies). Since we can't yet handle libraries from other link
1944 namespaces, we don't lose anything by ignoring them here. */
1945 struct value *link_map_id_val;
1948 link_map_id_val = pa->prob->evaluate_argument (0, frame);
1950 catch (const gdb_exception_error)
1952 link_map_id_val = NULL;
1954 /* glibc and illumos' libc both define LM_ID_BASE as zero. */
1955 if (link_map_id_val != NULL && value_as_long (link_map_id_val) != 0)
1956 action = DO_NOTHING;
1957 else
1958 return;
1961 if (action == UPDATE_OR_RELOAD)
1965 val = pa->prob->evaluate_argument (2, frame);
1967 catch (const gdb_exception_error &ex)
1969 exception_print (gdb_stderr, ex);
1970 return;
1973 if (val != NULL)
1974 lm = value_as_address (val);
1976 if (lm == 0)
1977 action = FULL_RELOAD;
1980 /* Resume section map updates. Closing the scope is
1981 sufficient. */
1984 if (action == UPDATE_OR_RELOAD)
1986 if (!solist_update_incremental (info, debug_base, lm))
1987 action = FULL_RELOAD;
1990 if (action == FULL_RELOAD)
1992 if (!solist_update_full (info))
1993 return;
1996 cleanup.release ();
1999 /* Helper function for svr4_update_solib_event_breakpoints. */
2001 static bool
2002 svr4_update_solib_event_breakpoint (struct breakpoint *b)
2004 if (b->type != bp_shlib_event)
2006 /* Continue iterating. */
2007 return false;
2010 for (bp_location &loc : b->locations ())
2012 struct svr4_info *info;
2013 struct probe_and_action *pa;
2015 info = solib_svr4_pspace_data.get (loc.pspace);
2016 if (info == NULL || info->probes_table == NULL)
2017 continue;
2019 pa = solib_event_probe_at (info, loc.address);
2020 if (pa == NULL)
2021 continue;
2023 if (pa->action == DO_NOTHING)
2025 if (b->enable_state == bp_disabled && stop_on_solib_events)
2026 enable_breakpoint (b);
2027 else if (b->enable_state == bp_enabled && !stop_on_solib_events)
2028 disable_breakpoint (b);
2031 break;
2034 /* Continue iterating. */
2035 return false;
2038 /* Enable or disable optional solib event breakpoints as appropriate.
2039 Called whenever stop_on_solib_events is changed. */
2041 static void
2042 svr4_update_solib_event_breakpoints (void)
2044 for (breakpoint &bp : all_breakpoints_safe ())
2045 svr4_update_solib_event_breakpoint (&bp);
2048 /* Create and register solib event breakpoints. PROBES is an array
2049 of NUM_PROBES elements, each of which is vector of probes. A
2050 solib event breakpoint will be created and registered for each
2051 probe. */
2053 static void
2054 svr4_create_probe_breakpoints (svr4_info *info, struct gdbarch *gdbarch,
2055 const std::vector<probe *> *probes,
2056 struct objfile *objfile)
2058 for (int i = 0; i < NUM_PROBES; i++)
2060 enum probe_action action = probe_info[i].action;
2062 for (probe *p : probes[i])
2064 CORE_ADDR address = p->get_relocated_address (objfile);
2066 solib_debug_printf ("name=%s, addr=%s", probe_info[i].name,
2067 paddress (gdbarch, address));
2069 create_solib_event_breakpoint (gdbarch, address);
2070 register_solib_event_probe (info, objfile, p, address, action);
2074 svr4_update_solib_event_breakpoints ();
2077 /* Find all the glibc named probes. Only if all of the probes are found, then
2078 create them and return true. Otherwise return false. If WITH_PREFIX is set
2079 then add "rtld" to the front of the probe names. */
2080 static bool
2081 svr4_find_and_create_probe_breakpoints (svr4_info *info,
2082 struct gdbarch *gdbarch,
2083 struct obj_section *os,
2084 bool with_prefix)
2086 SOLIB_SCOPED_DEBUG_START_END ("objfile=%s, with_prefix=%d",
2087 os->objfile->original_name, with_prefix);
2089 std::vector<probe *> probes[NUM_PROBES];
2091 for (int i = 0; i < NUM_PROBES; i++)
2093 const char *name = probe_info[i].name;
2094 char buf[32];
2096 /* Fedora 17 and Red Hat Enterprise Linux 6.2-6.4 shipped with an early
2097 version of the probes code in which the probes' names were prefixed
2098 with "rtld_" and the "map_failed" probe did not exist. The locations
2099 of the probes are otherwise the same, so we check for probes with
2100 prefixed names if probes with unprefixed names are not present. */
2101 if (with_prefix)
2103 xsnprintf (buf, sizeof (buf), "rtld_%s", name);
2104 name = buf;
2107 probes[i] = find_probes_in_objfile (os->objfile, "rtld", name);
2108 solib_debug_printf ("probe=%s, num found=%zu", name, probes[i].size ());
2110 /* Ensure at least one probe for the current name was found. */
2111 if (probes[i].empty ())
2113 /* The "map_failed" probe did not exist in early versions of the
2114 probes code in which the probes' names were prefixed with
2115 "rtld_".
2117 Additionally, the "map_failed" probe was accidentally removed
2118 from glibc 2.35 and 2.36, when changes in glibc meant the
2119 probe could no longer be reached, and the compiler optimized
2120 the probe away. In this case the probe name doesn't have the
2121 "rtld_" prefix.
2123 To handle this, and give GDB as much flexibility as possible,
2124 we make the rule that, if a probe isn't required for the
2125 correct operation of GDB (i.e. its action is DO_NOTHING), then
2126 we will still use the probes interface, even if that probe is
2127 missing.
2129 The only (possible) downside of this is that, if the user has
2130 'set stop-on-solib-events on' in effect, then they might get
2131 fewer events using the probes interface than with the classic
2132 non-probes interface. */
2133 if (probe_info[i].action == DO_NOTHING)
2134 continue;
2135 else
2136 return false;
2139 /* Ensure probe arguments can be evaluated. */
2140 for (probe *p : probes[i])
2142 if (!p->can_evaluate_arguments ())
2143 return false;
2144 /* This will fail if the probe is invalid. This has been seen on Arm
2145 due to references to symbols that have been resolved away. */
2148 p->get_argument_count (gdbarch);
2150 catch (const gdb_exception_error &ex)
2152 exception_print (gdb_stderr, ex);
2153 warning (_("Initializing probes-based dynamic linker interface "
2154 "failed.\nReverting to original interface."));
2155 return false;
2160 /* All probes found. Now create them. */
2161 solib_debug_printf ("using probes interface");
2162 svr4_create_probe_breakpoints (info, gdbarch, probes, os->objfile);
2163 return true;
2166 /* Both the SunOS and the SVR4 dynamic linkers call a marker function
2167 before and after mapping and unmapping shared libraries. The sole
2168 purpose of this method is to allow debuggers to set a breakpoint so
2169 they can track these changes.
2171 Some versions of the glibc dynamic linker contain named probes
2172 to allow more fine grained stopping. Given the address of the
2173 original marker function, this function attempts to find these
2174 probes, and if found, sets breakpoints on those instead. If the
2175 probes aren't found, a single breakpoint is set on the original
2176 marker function. */
2178 static void
2179 svr4_create_solib_event_breakpoints (svr4_info *info, struct gdbarch *gdbarch,
2180 CORE_ADDR address)
2182 struct obj_section *os = find_pc_section (address);
2184 if (os == nullptr
2185 || (!svr4_find_and_create_probe_breakpoints (info, gdbarch, os, false)
2186 && !svr4_find_and_create_probe_breakpoints (info, gdbarch, os, true)))
2188 solib_debug_printf ("falling back to r_brk breakpoint: addr=%s",
2189 paddress (gdbarch, address));
2190 create_solib_event_breakpoint (gdbarch, address);
2194 /* Arrange for dynamic linker to hit breakpoint.
2196 Both the SunOS and the SVR4 dynamic linkers have, as part of their
2197 debugger interface, support for arranging for the inferior to hit
2198 a breakpoint after mapping in the shared libraries. This function
2199 enables that breakpoint.
2201 For SunOS, there is a special flag location (in_debugger) which we
2202 set to 1. When the dynamic linker sees this flag set, it will set
2203 a breakpoint at a location known only to itself, after saving the
2204 original contents of that place and the breakpoint address itself,
2205 in its own internal structures. When we resume the inferior, it
2206 will eventually take a SIGTRAP when it runs into the breakpoint.
2207 We handle this (in a different place) by restoring the contents of
2208 the breakpointed location (which is only known after it stops),
2209 chasing around to locate the shared libraries that have been
2210 loaded, then resuming.
2212 For SVR4, the debugger interface structure contains a member (r_brk)
2213 which is statically initialized at the time the shared library is
2214 built, to the offset of a function (_r_debug_state) which is guaran-
2215 teed to be called once before mapping in a library, and again when
2216 the mapping is complete. At the time we are examining this member,
2217 it contains only the unrelocated offset of the function, so we have
2218 to do our own relocation. Later, when the dynamic linker actually
2219 runs, it relocates r_brk to be the actual address of _r_debug_state().
2221 The debugger interface structure also contains an enumeration which
2222 is set to either RT_ADD or RT_DELETE prior to changing the mapping,
2223 depending upon whether or not the library is being mapped or unmapped,
2224 and then set to RT_CONSISTENT after the library is mapped/unmapped. */
2226 static int
2227 enable_break (struct svr4_info *info, int from_tty)
2229 struct bound_minimal_symbol msymbol;
2230 const char * const *bkpt_namep;
2231 asection *interp_sect;
2232 CORE_ADDR sym_addr;
2234 info->interp_text_sect_low = info->interp_text_sect_high = 0;
2235 info->interp_plt_sect_low = info->interp_plt_sect_high = 0;
2237 /* If we already have a shared library list in the target, and
2238 r_debug contains r_brk, set the breakpoint there - this should
2239 mean r_brk has already been relocated. Assume the dynamic linker
2240 is the object containing r_brk. */
2242 solib_add (NULL, from_tty, auto_solib_add);
2243 sym_addr = 0;
2244 if (info->debug_base && solib_svr4_r_map (info->debug_base) != 0)
2245 sym_addr = solib_svr4_r_brk (info);
2247 if (sym_addr != 0)
2249 struct obj_section *os;
2251 sym_addr = gdbarch_addr_bits_remove
2252 (current_inferior ()->arch (),
2253 gdbarch_convert_from_func_ptr_addr
2254 (current_inferior ()->arch (), sym_addr,
2255 current_inferior ()->top_target ()));
2257 /* On at least some versions of Solaris there's a dynamic relocation
2258 on _r_debug.r_brk and SYM_ADDR may not be relocated yet, e.g., if
2259 we get control before the dynamic linker has self-relocated.
2260 Check if SYM_ADDR is in a known section, if it is assume we can
2261 trust its value. This is just a heuristic though, it could go away
2262 or be replaced if it's getting in the way.
2264 On ARM we need to know whether the ISA of rtld_db_dlactivity (or
2265 however it's spelled in your particular system) is ARM or Thumb.
2266 That knowledge is encoded in the address, if it's Thumb the low bit
2267 is 1. However, we've stripped that info above and it's not clear
2268 what all the consequences are of passing a non-addr_bits_remove'd
2269 address to svr4_create_solib_event_breakpoints. The call to
2270 find_pc_section verifies we know about the address and have some
2271 hope of computing the right kind of breakpoint to use (via
2272 symbol info). It does mean that GDB needs to be pointed at a
2273 non-stripped version of the dynamic linker in order to obtain
2274 information it already knows about. Sigh. */
2276 os = find_pc_section (sym_addr);
2277 if (os != NULL)
2279 /* Record the relocated start and end address of the dynamic linker
2280 text and plt section for svr4_in_dynsym_resolve_code. */
2281 bfd *tmp_bfd;
2282 CORE_ADDR load_addr;
2284 tmp_bfd = os->objfile->obfd.get ();
2285 load_addr = os->objfile->text_section_offset ();
2287 interp_sect = bfd_get_section_by_name (tmp_bfd, ".text");
2288 if (interp_sect)
2290 info->interp_text_sect_low
2291 = bfd_section_vma (interp_sect) + load_addr;
2292 info->interp_text_sect_high
2293 = info->interp_text_sect_low + bfd_section_size (interp_sect);
2295 interp_sect = bfd_get_section_by_name (tmp_bfd, ".plt");
2296 if (interp_sect)
2298 info->interp_plt_sect_low
2299 = bfd_section_vma (interp_sect) + load_addr;
2300 info->interp_plt_sect_high
2301 = info->interp_plt_sect_low + bfd_section_size (interp_sect);
2304 svr4_create_solib_event_breakpoints
2305 (info, current_inferior ()->arch (), sym_addr);
2306 return 1;
2310 /* Find the program interpreter; if not found, warn the user and drop
2311 into the old breakpoint at symbol code. */
2312 std::optional<gdb::byte_vector> interp_name_holder
2313 = find_program_interpreter ();
2314 if (interp_name_holder)
2316 const char *interp_name = (const char *) interp_name_holder->data ();
2317 CORE_ADDR load_addr = 0;
2318 int load_addr_found = 0;
2319 int loader_found_in_list = 0;
2320 target_ops_up tmp_bfd_target;
2322 sym_addr = 0;
2324 /* Now we need to figure out where the dynamic linker was
2325 loaded so that we can load its symbols and place a breakpoint
2326 in the dynamic linker itself.
2328 This address is stored on the stack. However, I've been unable
2329 to find any magic formula to find it for Solaris (appears to
2330 be trivial on GNU/Linux). Therefore, we have to try an alternate
2331 mechanism to find the dynamic linker's base address. */
2333 gdb_bfd_ref_ptr tmp_bfd;
2336 tmp_bfd = solib_bfd_open (interp_name);
2338 catch (const gdb_exception &ex)
2342 if (tmp_bfd == NULL)
2343 goto bkpt_at_symbol;
2345 /* Now convert the TMP_BFD into a target. That way target, as
2346 well as BFD operations can be used. */
2347 tmp_bfd_target = target_bfd_reopen (tmp_bfd);
2349 /* On a running target, we can get the dynamic linker's base
2350 address from the shared library table. */
2351 for (const solib &so : current_program_space->solibs ())
2353 if (svr4_same_1 (interp_name, so.so_original_name.c_str ()))
2355 load_addr_found = 1;
2356 loader_found_in_list = 1;
2357 load_addr = lm_addr_check (so, tmp_bfd.get ());
2358 break;
2362 /* If we were not able to find the base address of the loader
2363 from our so_list, then try using the AT_BASE auxilliary entry. */
2364 if (!load_addr_found)
2365 if (target_auxv_search (AT_BASE, &load_addr) > 0)
2367 int addr_bit = gdbarch_addr_bit (current_inferior ()->arch ());
2369 /* Ensure LOAD_ADDR has proper sign in its possible upper bits so
2370 that `+ load_addr' will overflow CORE_ADDR width not creating
2371 invalid addresses like 0x101234567 for 32bit inferiors on 64bit
2372 GDB. */
2374 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
2376 CORE_ADDR space_size = (CORE_ADDR) 1 << addr_bit;
2377 CORE_ADDR tmp_entry_point
2378 = exec_entry_point (tmp_bfd.get (), tmp_bfd_target.get ());
2380 gdb_assert (load_addr < space_size);
2382 /* TMP_ENTRY_POINT exceeding SPACE_SIZE would be for prelinked
2383 64bit ld.so with 32bit executable, it should not happen. */
2385 if (tmp_entry_point < space_size
2386 && tmp_entry_point + load_addr >= space_size)
2387 load_addr -= space_size;
2390 load_addr_found = 1;
2393 /* Otherwise we find the dynamic linker's base address by examining
2394 the current pc (which should point at the entry point for the
2395 dynamic linker) and subtracting the offset of the entry point.
2397 This is more fragile than the previous approaches, but is a good
2398 fallback method because it has actually been working well in
2399 most cases. */
2400 if (!load_addr_found)
2402 regcache *regcache
2403 = get_thread_arch_regcache (current_inferior (), inferior_ptid,
2404 current_inferior ()->arch ());
2406 load_addr = (regcache_read_pc (regcache)
2407 - exec_entry_point (tmp_bfd.get (),
2408 tmp_bfd_target.get ()));
2411 if (!loader_found_in_list)
2413 info->debug_loader_name = xstrdup (interp_name);
2414 info->debug_loader_offset_p = 1;
2415 info->debug_loader_offset = load_addr;
2416 solib_add (NULL, from_tty, auto_solib_add);
2419 /* Record the relocated start and end address of the dynamic linker
2420 text and plt section for svr4_in_dynsym_resolve_code. */
2421 interp_sect = bfd_get_section_by_name (tmp_bfd.get (), ".text");
2422 if (interp_sect)
2424 info->interp_text_sect_low
2425 = bfd_section_vma (interp_sect) + load_addr;
2426 info->interp_text_sect_high
2427 = info->interp_text_sect_low + bfd_section_size (interp_sect);
2429 interp_sect = bfd_get_section_by_name (tmp_bfd.get (), ".plt");
2430 if (interp_sect)
2432 info->interp_plt_sect_low
2433 = bfd_section_vma (interp_sect) + load_addr;
2434 info->interp_plt_sect_high
2435 = info->interp_plt_sect_low + bfd_section_size (interp_sect);
2438 /* Now try to set a breakpoint in the dynamic linker. */
2439 for (bkpt_namep = solib_break_names; *bkpt_namep != NULL; bkpt_namep++)
2441 sym_addr
2442 = (gdb_bfd_lookup_symbol
2443 (tmp_bfd.get (),
2444 [=] (const asymbol *sym)
2446 return (strcmp (sym->name, *bkpt_namep) == 0
2447 && ((sym->section->flags & (SEC_CODE | SEC_DATA))
2448 != 0));
2449 }));
2450 if (sym_addr != 0)
2451 break;
2454 if (sym_addr != 0)
2455 /* Convert 'sym_addr' from a function pointer to an address.
2456 Because we pass tmp_bfd_target instead of the current
2457 target, this will always produce an unrelocated value. */
2458 sym_addr = gdbarch_convert_from_func_ptr_addr
2459 (current_inferior ()->arch (), sym_addr,
2460 tmp_bfd_target.get ());
2462 if (sym_addr != 0)
2464 svr4_create_solib_event_breakpoints (info,
2465 current_inferior ()->arch (),
2466 load_addr + sym_addr);
2467 return 1;
2470 /* For whatever reason we couldn't set a breakpoint in the dynamic
2471 linker. Warn and drop into the old code. */
2472 bkpt_at_symbol:
2473 warning (_("Unable to find dynamic linker breakpoint function.\n"
2474 "GDB will be unable to debug shared library initializers\n"
2475 "and track explicitly loaded dynamic code."));
2478 /* Scan through the lists of symbols, trying to look up the symbol and
2479 set a breakpoint there. Terminate loop when we/if we succeed. */
2481 objfile *objf = current_program_space->symfile_object_file;
2482 for (bkpt_namep = solib_break_names; *bkpt_namep != NULL; bkpt_namep++)
2484 msymbol = lookup_minimal_symbol (*bkpt_namep, NULL, objf);
2485 if ((msymbol.minsym != NULL)
2486 && (msymbol.value_address () != 0))
2488 sym_addr = msymbol.value_address ();
2489 sym_addr = gdbarch_convert_from_func_ptr_addr
2490 (current_inferior ()->arch (), sym_addr,
2491 current_inferior ()->top_target ());
2492 svr4_create_solib_event_breakpoints (info,
2493 current_inferior ()->arch (),
2494 sym_addr);
2495 return 1;
2499 if (interp_name_holder && !current_inferior ()->attach_flag)
2501 for (bkpt_namep = bkpt_names; *bkpt_namep != NULL; bkpt_namep++)
2503 msymbol = lookup_minimal_symbol (*bkpt_namep, NULL, objf);
2504 if ((msymbol.minsym != NULL)
2505 && (msymbol.value_address () != 0))
2507 sym_addr = msymbol.value_address ();
2508 sym_addr = gdbarch_convert_from_func_ptr_addr
2509 (current_inferior ()->arch (), sym_addr,
2510 current_inferior ()->top_target ());
2511 svr4_create_solib_event_breakpoints
2512 (info, current_inferior ()->arch (), sym_addr);
2513 return 1;
2517 return 0;
2520 /* Read the ELF program headers from ABFD. */
2522 static std::optional<gdb::byte_vector>
2523 read_program_headers_from_bfd (bfd *abfd)
2525 Elf_Internal_Ehdr *ehdr = elf_elfheader (abfd);
2526 int phdrs_size = ehdr->e_phnum * ehdr->e_phentsize;
2527 if (phdrs_size == 0)
2528 return {};
2530 gdb::byte_vector buf (phdrs_size);
2531 if (bfd_seek (abfd, ehdr->e_phoff, SEEK_SET) != 0
2532 || bfd_read (buf.data (), phdrs_size, abfd) != phdrs_size)
2533 return {};
2535 return buf;
2538 /* Return 1 and fill *DISPLACEMENTP with detected PIE offset of inferior
2539 exec_bfd. Otherwise return 0.
2541 We relocate all of the sections by the same amount. This
2542 behavior is mandated by recent editions of the System V ABI.
2543 According to the System V Application Binary Interface,
2544 Edition 4.1, page 5-5:
2546 ... Though the system chooses virtual addresses for
2547 individual processes, it maintains the segments' relative
2548 positions. Because position-independent code uses relative
2549 addressing between segments, the difference between
2550 virtual addresses in memory must match the difference
2551 between virtual addresses in the file. The difference
2552 between the virtual address of any segment in memory and
2553 the corresponding virtual address in the file is thus a
2554 single constant value for any one executable or shared
2555 object in a given process. This difference is the base
2556 address. One use of the base address is to relocate the
2557 memory image of the program during dynamic linking.
2559 The same language also appears in Edition 4.0 of the System V
2560 ABI and is left unspecified in some of the earlier editions.
2562 Decide if the objfile needs to be relocated. As indicated above, we will
2563 only be here when execution is stopped. But during attachment PC can be at
2564 arbitrary address therefore regcache_read_pc can be misleading (contrary to
2565 the auxv AT_ENTRY value). Moreover for executable with interpreter section
2566 regcache_read_pc would point to the interpreter and not the main executable.
2568 So, to summarize, relocations are necessary when the start address obtained
2569 from the executable is different from the address in auxv AT_ENTRY entry.
2571 [ The astute reader will note that we also test to make sure that
2572 the executable in question has the DYNAMIC flag set. It is my
2573 opinion that this test is unnecessary (undesirable even). It
2574 was added to avoid inadvertent relocation of an executable
2575 whose e_type member in the ELF header is not ET_DYN. There may
2576 be a time in the future when it is desirable to do relocations
2577 on other types of files as well in which case this condition
2578 should either be removed or modified to accommodate the new file
2579 type. - Kevin, Nov 2000. ] */
2581 static int
2582 svr4_exec_displacement (CORE_ADDR *displacementp)
2584 /* ENTRY_POINT is a possible function descriptor - before
2585 a call to gdbarch_convert_from_func_ptr_addr. */
2586 CORE_ADDR entry_point, exec_displacement;
2588 if (current_program_space->exec_bfd () == NULL)
2589 return 0;
2591 /* Therefore for ELF it is ET_EXEC and not ET_DYN. Both shared libraries
2592 being executed themselves and PIE (Position Independent Executable)
2593 executables are ET_DYN. */
2595 if ((bfd_get_file_flags (current_program_space->exec_bfd ()) & DYNAMIC) == 0)
2596 return 0;
2598 if (target_auxv_search (AT_ENTRY, &entry_point) <= 0)
2599 return 0;
2601 exec_displacement
2602 = entry_point - bfd_get_start_address (current_program_space->exec_bfd ());
2604 /* Verify the EXEC_DISPLACEMENT candidate complies with the required page
2605 alignment. It is cheaper than the program headers comparison below. */
2607 if (bfd_get_flavour (current_program_space->exec_bfd ())
2608 == bfd_target_elf_flavour)
2610 const struct elf_backend_data *elf
2611 = get_elf_backend_data (current_program_space->exec_bfd ());
2613 /* p_align of PT_LOAD segments does not specify any alignment but
2614 only congruency of addresses:
2615 p_offset % p_align == p_vaddr % p_align
2616 Kernel is free to load the executable with lower alignment. */
2618 if ((exec_displacement & (elf->minpagesize - 1)) != 0)
2619 return 0;
2622 /* Verify that the auxilliary vector describes the same file as exec_bfd, by
2623 comparing their program headers. If the program headers in the auxilliary
2624 vector do not match the program headers in the executable, then we are
2625 looking at a different file than the one used by the kernel - for
2626 instance, "gdb program" connected to "gdbserver :PORT ld.so program". */
2628 if (bfd_get_flavour (current_program_space->exec_bfd ())
2629 == bfd_target_elf_flavour)
2631 /* Be optimistic and return 0 only if GDB was able to verify the headers
2632 really do not match. */
2633 int arch_size;
2635 std::optional<gdb::byte_vector> phdrs_target
2636 = read_program_header (-1, &arch_size, NULL);
2637 std::optional<gdb::byte_vector> phdrs_binary
2638 = read_program_headers_from_bfd (current_program_space->exec_bfd ());
2639 if (phdrs_target && phdrs_binary)
2641 bfd_endian byte_order = gdbarch_byte_order (current_inferior ()->arch ());
2643 /* We are dealing with three different addresses. EXEC_BFD
2644 represents current address in on-disk file. target memory content
2645 may be different from EXEC_BFD as the file may have been prelinked
2646 to a different address after the executable has been loaded.
2647 Moreover the address of placement in target memory can be
2648 different from what the program headers in target memory say -
2649 this is the goal of PIE.
2651 Detected DISPLACEMENT covers both the offsets of PIE placement and
2652 possible new prelink performed after start of the program. Here
2653 relocate BUF and BUF2 just by the EXEC_BFD vs. target memory
2654 content offset for the verification purpose. */
2656 if (phdrs_target->size () != phdrs_binary->size ()
2657 || bfd_get_arch_size (current_program_space->exec_bfd ()) != arch_size)
2658 return 0;
2659 else if (arch_size == 32
2660 && phdrs_target->size () >= sizeof (Elf32_External_Phdr)
2661 && phdrs_target->size () % sizeof (Elf32_External_Phdr) == 0)
2663 Elf_Internal_Ehdr *ehdr2
2664 = elf_tdata (current_program_space->exec_bfd ())->elf_header;
2665 Elf_Internal_Phdr *phdr2
2666 = elf_tdata (current_program_space->exec_bfd ())->phdr;
2667 CORE_ADDR displacement = 0;
2668 int i;
2670 /* DISPLACEMENT could be found more easily by the difference of
2671 ehdr2->e_entry. But we haven't read the ehdr yet, and we
2672 already have enough information to compute that displacement
2673 with what we've read. */
2675 for (i = 0; i < ehdr2->e_phnum; i++)
2676 if (phdr2[i].p_type == PT_LOAD)
2678 Elf32_External_Phdr *phdrp;
2679 gdb_byte *buf_vaddr_p, *buf_paddr_p;
2680 CORE_ADDR vaddr, paddr;
2681 CORE_ADDR displacement_vaddr = 0;
2682 CORE_ADDR displacement_paddr = 0;
2684 phdrp = &((Elf32_External_Phdr *) phdrs_target->data ())[i];
2685 buf_vaddr_p = (gdb_byte *) &phdrp->p_vaddr;
2686 buf_paddr_p = (gdb_byte *) &phdrp->p_paddr;
2688 vaddr = extract_unsigned_integer (buf_vaddr_p, 4,
2689 byte_order);
2690 displacement_vaddr = vaddr - phdr2[i].p_vaddr;
2692 paddr = extract_unsigned_integer (buf_paddr_p, 4,
2693 byte_order);
2694 displacement_paddr = paddr - phdr2[i].p_paddr;
2696 if (displacement_vaddr == displacement_paddr)
2697 displacement = displacement_vaddr;
2699 break;
2702 /* Now compare program headers from the target and the binary
2703 with optional DISPLACEMENT. */
2705 for (i = 0;
2706 i < phdrs_target->size () / sizeof (Elf32_External_Phdr);
2707 i++)
2709 Elf32_External_Phdr *phdrp;
2710 Elf32_External_Phdr *phdr2p;
2711 gdb_byte *buf_vaddr_p, *buf_paddr_p;
2712 CORE_ADDR vaddr, paddr;
2713 asection *plt2_asect;
2715 phdrp = &((Elf32_External_Phdr *) phdrs_target->data ())[i];
2716 buf_vaddr_p = (gdb_byte *) &phdrp->p_vaddr;
2717 buf_paddr_p = (gdb_byte *) &phdrp->p_paddr;
2718 phdr2p = &((Elf32_External_Phdr *) phdrs_binary->data ())[i];
2720 /* PT_GNU_STACK is an exception by being never relocated by
2721 prelink as its addresses are always zero. */
2723 if (memcmp (phdrp, phdr2p, sizeof (*phdrp)) == 0)
2724 continue;
2726 /* Check also other adjustment combinations - PR 11786. */
2728 vaddr = extract_unsigned_integer (buf_vaddr_p, 4,
2729 byte_order);
2730 vaddr -= displacement;
2731 store_unsigned_integer (buf_vaddr_p, 4, byte_order, vaddr);
2733 paddr = extract_unsigned_integer (buf_paddr_p, 4,
2734 byte_order);
2735 paddr -= displacement;
2736 store_unsigned_integer (buf_paddr_p, 4, byte_order, paddr);
2738 if (memcmp (phdrp, phdr2p, sizeof (*phdrp)) == 0)
2739 continue;
2741 /* Strip modifies the flags and alignment of PT_GNU_RELRO.
2742 CentOS-5 has problems with filesz, memsz as well.
2743 Strip also modifies memsz of PT_TLS.
2744 See PR 11786. */
2745 if (phdr2[i].p_type == PT_GNU_RELRO
2746 || phdr2[i].p_type == PT_TLS)
2748 Elf32_External_Phdr tmp_phdr = *phdrp;
2749 Elf32_External_Phdr tmp_phdr2 = *phdr2p;
2751 memset (tmp_phdr.p_filesz, 0, 4);
2752 memset (tmp_phdr.p_memsz, 0, 4);
2753 memset (tmp_phdr.p_flags, 0, 4);
2754 memset (tmp_phdr.p_align, 0, 4);
2755 memset (tmp_phdr2.p_filesz, 0, 4);
2756 memset (tmp_phdr2.p_memsz, 0, 4);
2757 memset (tmp_phdr2.p_flags, 0, 4);
2758 memset (tmp_phdr2.p_align, 0, 4);
2760 if (memcmp (&tmp_phdr, &tmp_phdr2, sizeof (tmp_phdr))
2761 == 0)
2762 continue;
2765 /* prelink can convert .plt SHT_NOBITS to SHT_PROGBITS. */
2766 bfd *exec_bfd = current_program_space->exec_bfd ();
2767 plt2_asect = bfd_get_section_by_name (exec_bfd, ".plt");
2768 if (plt2_asect)
2770 int content2;
2771 gdb_byte *buf_filesz_p = (gdb_byte *) &phdrp->p_filesz;
2772 CORE_ADDR filesz;
2774 content2 = (bfd_section_flags (plt2_asect)
2775 & SEC_HAS_CONTENTS) != 0;
2777 filesz = extract_unsigned_integer (buf_filesz_p, 4,
2778 byte_order);
2780 /* PLT2_ASECT is from on-disk file (exec_bfd) while
2781 FILESZ is from the in-memory image. */
2782 if (content2)
2783 filesz += bfd_section_size (plt2_asect);
2784 else
2785 filesz -= bfd_section_size (plt2_asect);
2787 store_unsigned_integer (buf_filesz_p, 4, byte_order,
2788 filesz);
2790 if (memcmp (phdrp, phdr2p, sizeof (*phdrp)) == 0)
2791 continue;
2794 return 0;
2797 else if (arch_size == 64
2798 && phdrs_target->size () >= sizeof (Elf64_External_Phdr)
2799 && phdrs_target->size () % sizeof (Elf64_External_Phdr) == 0)
2801 Elf_Internal_Ehdr *ehdr2
2802 = elf_tdata (current_program_space->exec_bfd ())->elf_header;
2803 Elf_Internal_Phdr *phdr2
2804 = elf_tdata (current_program_space->exec_bfd ())->phdr;
2805 CORE_ADDR displacement = 0;
2806 int i;
2808 /* DISPLACEMENT could be found more easily by the difference of
2809 ehdr2->e_entry. But we haven't read the ehdr yet, and we
2810 already have enough information to compute that displacement
2811 with what we've read. */
2813 for (i = 0; i < ehdr2->e_phnum; i++)
2814 if (phdr2[i].p_type == PT_LOAD)
2816 Elf64_External_Phdr *phdrp;
2817 gdb_byte *buf_vaddr_p, *buf_paddr_p;
2818 CORE_ADDR vaddr, paddr;
2819 CORE_ADDR displacement_vaddr = 0;
2820 CORE_ADDR displacement_paddr = 0;
2822 phdrp = &((Elf64_External_Phdr *) phdrs_target->data ())[i];
2823 buf_vaddr_p = (gdb_byte *) &phdrp->p_vaddr;
2824 buf_paddr_p = (gdb_byte *) &phdrp->p_paddr;
2826 vaddr = extract_unsigned_integer (buf_vaddr_p, 8,
2827 byte_order);
2828 displacement_vaddr = vaddr - phdr2[i].p_vaddr;
2830 paddr = extract_unsigned_integer (buf_paddr_p, 8,
2831 byte_order);
2832 displacement_paddr = paddr - phdr2[i].p_paddr;
2834 if (displacement_vaddr == displacement_paddr)
2835 displacement = displacement_vaddr;
2837 break;
2840 /* Now compare BUF and BUF2 with optional DISPLACEMENT. */
2842 for (i = 0;
2843 i < phdrs_target->size () / sizeof (Elf64_External_Phdr);
2844 i++)
2846 Elf64_External_Phdr *phdrp;
2847 Elf64_External_Phdr *phdr2p;
2848 gdb_byte *buf_vaddr_p, *buf_paddr_p;
2849 CORE_ADDR vaddr, paddr;
2850 asection *plt2_asect;
2852 phdrp = &((Elf64_External_Phdr *) phdrs_target->data ())[i];
2853 buf_vaddr_p = (gdb_byte *) &phdrp->p_vaddr;
2854 buf_paddr_p = (gdb_byte *) &phdrp->p_paddr;
2855 phdr2p = &((Elf64_External_Phdr *) phdrs_binary->data ())[i];
2857 /* PT_GNU_STACK is an exception by being never relocated by
2858 prelink as its addresses are always zero. */
2860 if (memcmp (phdrp, phdr2p, sizeof (*phdrp)) == 0)
2861 continue;
2863 /* Check also other adjustment combinations - PR 11786. */
2865 vaddr = extract_unsigned_integer (buf_vaddr_p, 8,
2866 byte_order);
2867 vaddr -= displacement;
2868 store_unsigned_integer (buf_vaddr_p, 8, byte_order, vaddr);
2870 paddr = extract_unsigned_integer (buf_paddr_p, 8,
2871 byte_order);
2872 paddr -= displacement;
2873 store_unsigned_integer (buf_paddr_p, 8, byte_order, paddr);
2875 if (memcmp (phdrp, phdr2p, sizeof (*phdrp)) == 0)
2876 continue;
2878 /* Strip modifies the flags and alignment of PT_GNU_RELRO.
2879 CentOS-5 has problems with filesz, memsz as well.
2880 Strip also modifies memsz of PT_TLS.
2881 See PR 11786. */
2882 if (phdr2[i].p_type == PT_GNU_RELRO
2883 || phdr2[i].p_type == PT_TLS)
2885 Elf64_External_Phdr tmp_phdr = *phdrp;
2886 Elf64_External_Phdr tmp_phdr2 = *phdr2p;
2888 memset (tmp_phdr.p_filesz, 0, 8);
2889 memset (tmp_phdr.p_memsz, 0, 8);
2890 memset (tmp_phdr.p_flags, 0, 4);
2891 memset (tmp_phdr.p_align, 0, 8);
2892 memset (tmp_phdr2.p_filesz, 0, 8);
2893 memset (tmp_phdr2.p_memsz, 0, 8);
2894 memset (tmp_phdr2.p_flags, 0, 4);
2895 memset (tmp_phdr2.p_align, 0, 8);
2897 if (memcmp (&tmp_phdr, &tmp_phdr2, sizeof (tmp_phdr))
2898 == 0)
2899 continue;
2902 /* prelink can convert .plt SHT_NOBITS to SHT_PROGBITS. */
2903 plt2_asect
2904 = bfd_get_section_by_name (current_program_space->exec_bfd (),
2905 ".plt");
2906 if (plt2_asect)
2908 int content2;
2909 gdb_byte *buf_filesz_p = (gdb_byte *) &phdrp->p_filesz;
2910 CORE_ADDR filesz;
2912 content2 = (bfd_section_flags (plt2_asect)
2913 & SEC_HAS_CONTENTS) != 0;
2915 filesz = extract_unsigned_integer (buf_filesz_p, 8,
2916 byte_order);
2918 /* PLT2_ASECT is from on-disk file (current
2919 exec_bfd) while FILESZ is from the in-memory
2920 image. */
2921 if (content2)
2922 filesz += bfd_section_size (plt2_asect);
2923 else
2924 filesz -= bfd_section_size (plt2_asect);
2926 store_unsigned_integer (buf_filesz_p, 8, byte_order,
2927 filesz);
2929 if (memcmp (phdrp, phdr2p, sizeof (*phdrp)) == 0)
2930 continue;
2933 return 0;
2936 else
2937 return 0;
2941 if (info_verbose)
2943 /* It can be printed repeatedly as there is no easy way to check
2944 the executable symbols/file has been already relocated to
2945 displacement. */
2947 gdb_printf (_("Using PIE (Position Independent Executable) "
2948 "displacement %s for \"%s\".\n"),
2949 paddress (current_inferior ()->arch (), exec_displacement),
2950 bfd_get_filename (current_program_space->exec_bfd ()));
2953 *displacementp = exec_displacement;
2954 return 1;
2957 /* Relocate the main executable. This function should be called upon
2958 stopping the inferior process at the entry point to the program.
2959 The entry point from BFD is compared to the AT_ENTRY of AUXV and if they are
2960 different, the main executable is relocated by the proper amount. */
2962 static void
2963 svr4_relocate_main_executable (void)
2965 CORE_ADDR displacement;
2967 /* If we are re-running this executable, SYMFILE_OBJFILE->SECTION_OFFSETS
2968 probably contains the offsets computed using the PIE displacement
2969 from the previous run, which of course are irrelevant for this run.
2970 So we need to determine the new PIE displacement and recompute the
2971 section offsets accordingly, even if SYMFILE_OBJFILE->SECTION_OFFSETS
2972 already contains pre-computed offsets.
2974 If we cannot compute the PIE displacement, either:
2976 - The executable is not PIE.
2978 - SYMFILE_OBJFILE does not match the executable started in the target.
2979 This can happen for main executable symbols loaded at the host while
2980 `ld.so --ld-args main-executable' is loaded in the target.
2982 Then we leave the section offsets untouched and use them as is for
2983 this run. Either:
2985 - These section offsets were properly reset earlier, and thus
2986 already contain the correct values. This can happen for instance
2987 when reconnecting via the remote protocol to a target that supports
2988 the `qOffsets' packet.
2990 - The section offsets were not reset earlier, and the best we can
2991 hope is that the old offsets are still applicable to the new run. */
2993 if (! svr4_exec_displacement (&displacement))
2994 return;
2996 /* Even DISPLACEMENT 0 is a valid new difference of in-memory vs. in-file
2997 addresses. */
2999 objfile *objf = current_program_space->symfile_object_file;
3000 if (objf)
3002 section_offsets new_offsets (objf->section_offsets.size (),
3003 displacement);
3004 objfile_relocate (objf, new_offsets);
3006 else if (current_program_space->exec_bfd ())
3008 asection *asect;
3010 bfd *exec_bfd = current_program_space->exec_bfd ();
3011 for (asect = exec_bfd->sections; asect != NULL; asect = asect->next)
3012 exec_set_section_address (bfd_get_filename (exec_bfd), asect->index,
3013 bfd_section_vma (asect) + displacement);
3017 /* Implement the "create_inferior_hook" target_solib_ops method.
3019 For SVR4 executables, this first instruction is either the first
3020 instruction in the dynamic linker (for dynamically linked
3021 executables) or the instruction at "start" for statically linked
3022 executables. For dynamically linked executables, the system
3023 first exec's /lib/libc.so.N, which contains the dynamic linker,
3024 and starts it running. The dynamic linker maps in any needed
3025 shared libraries, maps in the actual user executable, and then
3026 jumps to "start" in the user executable.
3028 We can arrange to cooperate with the dynamic linker to discover the
3029 names of shared libraries that are dynamically linked, and the base
3030 addresses to which they are linked.
3032 This function is responsible for discovering those names and
3033 addresses, and saving sufficient information about them to allow
3034 their symbols to be read at a later time. */
3036 static void
3037 svr4_solib_create_inferior_hook (int from_tty)
3039 struct svr4_info *info;
3041 info = get_svr4_info (current_program_space);
3043 /* Clear the probes-based interface's state. */
3044 free_probes_table (info);
3045 info->solib_lists.clear ();
3047 /* Relocate the main executable if necessary. */
3048 svr4_relocate_main_executable ();
3050 /* No point setting a breakpoint in the dynamic linker if we can't
3051 hit it (e.g., a core file, or a trace file). */
3052 if (!target_has_execution ())
3053 return;
3055 if (!svr4_have_link_map_offsets ())
3056 return;
3058 if (!enable_break (info, from_tty))
3059 return;
3062 static void
3063 svr4_clear_solib (program_space *pspace)
3065 svr4_info *info = get_svr4_info (pspace);
3066 info->debug_base = 0;
3067 info->debug_loader_offset_p = 0;
3068 info->debug_loader_offset = 0;
3069 xfree (info->debug_loader_name);
3070 info->debug_loader_name = NULL;
3073 /* Clear any bits of ADDR that wouldn't fit in a target-format
3074 data pointer. "Data pointer" here refers to whatever sort of
3075 address the dynamic linker uses to manage its sections. At the
3076 moment, we don't support shared libraries on any processors where
3077 code and data pointers are different sizes.
3079 This isn't really the right solution. What we really need here is
3080 a way to do arithmetic on CORE_ADDR values that respects the
3081 natural pointer/address correspondence. (For example, on the MIPS,
3082 converting a 32-bit pointer to a 64-bit CORE_ADDR requires you to
3083 sign-extend the value. There, simply truncating the bits above
3084 gdbarch_ptr_bit, as we do below, is no good.) This should probably
3085 be a new gdbarch method or something. */
3086 static CORE_ADDR
3087 svr4_truncate_ptr (CORE_ADDR addr)
3089 if (gdbarch_ptr_bit (current_inferior ()->arch ()) == sizeof (CORE_ADDR) * 8)
3090 /* We don't need to truncate anything, and the bit twiddling below
3091 will fail due to overflow problems. */
3092 return addr;
3093 else
3094 return addr & (((CORE_ADDR) 1 << gdbarch_ptr_bit (current_inferior ()->arch ())) - 1);
3098 static void
3099 svr4_relocate_section_addresses (solib &so, target_section *sec)
3101 bfd *abfd = sec->the_bfd_section->owner;
3103 sec->addr = svr4_truncate_ptr (sec->addr + lm_addr_check (so, abfd));
3104 sec->endaddr = svr4_truncate_ptr (sec->endaddr + lm_addr_check (so, abfd));
3108 /* Architecture-specific operations. */
3110 struct solib_svr4_ops
3112 /* Return a description of the layout of `struct link_map'. */
3113 struct link_map_offsets *(*fetch_link_map_offsets)(void) = nullptr;
3116 /* Per-architecture data key. */
3117 static const registry<gdbarch>::key<struct solib_svr4_ops> solib_svr4_data;
3119 /* Return a default for the architecture-specific operations. */
3121 static struct solib_svr4_ops *
3122 get_ops (struct gdbarch *gdbarch)
3124 struct solib_svr4_ops *ops = solib_svr4_data.get (gdbarch);
3125 if (ops == nullptr)
3126 ops = solib_svr4_data.emplace (gdbarch);
3127 return ops;
3130 /* Set the architecture-specific `struct link_map_offsets' fetcher for
3131 GDBARCH to FLMO. Also, install SVR4 solib_ops into GDBARCH. */
3133 void
3134 set_solib_svr4_fetch_link_map_offsets (struct gdbarch *gdbarch,
3135 struct link_map_offsets *(*flmo) (void))
3137 struct solib_svr4_ops *ops = get_ops (gdbarch);
3139 ops->fetch_link_map_offsets = flmo;
3141 set_gdbarch_so_ops (gdbarch, &svr4_so_ops);
3142 set_gdbarch_iterate_over_objfiles_in_search_order
3143 (gdbarch, svr4_iterate_over_objfiles_in_search_order);
3146 /* Fetch a link_map_offsets structure using the architecture-specific
3147 `struct link_map_offsets' fetcher. */
3149 static struct link_map_offsets *
3150 svr4_fetch_link_map_offsets (void)
3152 struct solib_svr4_ops *ops = get_ops (current_inferior ()->arch ());
3154 gdb_assert (ops->fetch_link_map_offsets);
3155 return ops->fetch_link_map_offsets ();
3158 /* Return 1 if a link map offset fetcher has been defined, 0 otherwise. */
3160 static int
3161 svr4_have_link_map_offsets (void)
3163 struct solib_svr4_ops *ops = get_ops (current_inferior ()->arch ());
3165 return (ops->fetch_link_map_offsets != NULL);
3169 /* Most OS'es that have SVR4-style ELF dynamic libraries define a
3170 `struct r_debug' and a `struct link_map' that are binary compatible
3171 with the original SVR4 implementation. */
3173 /* Fetch (and possibly build) an appropriate `struct link_map_offsets'
3174 for an ILP32 SVR4 system. */
3176 struct link_map_offsets *
3177 svr4_ilp32_fetch_link_map_offsets (void)
3179 static struct link_map_offsets lmo;
3180 static struct link_map_offsets *lmp = NULL;
3182 if (lmp == NULL)
3184 lmp = &lmo;
3186 lmo.r_version_offset = 0;
3187 lmo.r_version_size = 4;
3188 lmo.r_map_offset = 4;
3189 lmo.r_brk_offset = 8;
3190 lmo.r_ldsomap_offset = 20;
3191 lmo.r_next_offset = -1;
3193 /* Everything we need is in the first 20 bytes. */
3194 lmo.link_map_size = 20;
3195 lmo.l_addr_offset = 0;
3196 lmo.l_name_offset = 4;
3197 lmo.l_ld_offset = 8;
3198 lmo.l_next_offset = 12;
3199 lmo.l_prev_offset = 16;
3202 return lmp;
3205 /* Fetch (and possibly build) an appropriate `struct link_map_offsets'
3206 for an LP64 SVR4 system. */
3208 struct link_map_offsets *
3209 svr4_lp64_fetch_link_map_offsets (void)
3211 static struct link_map_offsets lmo;
3212 static struct link_map_offsets *lmp = NULL;
3214 if (lmp == NULL)
3216 lmp = &lmo;
3218 lmo.r_version_offset = 0;
3219 lmo.r_version_size = 4;
3220 lmo.r_map_offset = 8;
3221 lmo.r_brk_offset = 16;
3222 lmo.r_ldsomap_offset = 40;
3223 lmo.r_next_offset = -1;
3225 /* Everything we need is in the first 40 bytes. */
3226 lmo.link_map_size = 40;
3227 lmo.l_addr_offset = 0;
3228 lmo.l_name_offset = 8;
3229 lmo.l_ld_offset = 16;
3230 lmo.l_next_offset = 24;
3231 lmo.l_prev_offset = 32;
3234 return lmp;
3238 /* Return the DSO matching OBJFILE or nullptr if none can be found. */
3240 static const solib *
3241 find_solib_for_objfile (struct objfile *objfile)
3243 if (objfile == nullptr)
3244 return nullptr;
3246 /* If OBJFILE is a separate debug object file, look for the original
3247 object file. */
3248 if (objfile->separate_debug_objfile_backlink != nullptr)
3249 objfile = objfile->separate_debug_objfile_backlink;
3251 for (const solib &so : current_program_space->solibs ())
3252 if (so.objfile == objfile)
3253 return &so;
3255 return nullptr;
3258 /* Return the address of the r_debug object for the namespace containing
3259 SOLIB or zero if it cannot be found. This may happen when symbol files
3260 are added manually, for example, or with the main executable.
3262 Current callers treat zero as initial namespace so they are doing the
3263 right thing for the main executable. */
3265 static CORE_ADDR
3266 find_debug_base_for_solib (const solib *solib)
3268 if (solib == nullptr)
3269 return 0;
3271 svr4_info *info = get_svr4_info (current_program_space);
3272 gdb_assert (info != nullptr);
3274 auto *lm_info
3275 = gdb::checked_static_cast<const lm_info_svr4 *> (solib->lm_info.get ());
3277 for (const auto &tuple : info->solib_lists)
3279 CORE_ADDR debug_base = tuple.first;
3280 const std::vector<svr4_so> &sos = tuple.second;
3282 for (const svr4_so &so : sos)
3283 if (svr4_same (solib->so_original_name.c_str (), so.name.c_str (),
3284 *lm_info, *so.lm_info))
3285 return debug_base;
3288 return 0;
3291 /* Search order for ELF DSOs linked with -Bsymbolic. Those DSOs have a
3292 different rule for symbol lookup. The lookup begins here in the DSO,
3293 not in the main executable. When starting from CURRENT_OBJFILE, we
3294 stay in the same namespace as that file. Otherwise, we only consider
3295 the initial namespace. */
3297 static void
3298 svr4_iterate_over_objfiles_in_search_order
3299 (gdbarch *gdbarch, iterate_over_objfiles_in_search_order_cb_ftype cb,
3300 objfile *current_objfile)
3302 bool checked_current_objfile = false;
3303 if (current_objfile != nullptr)
3305 bfd *abfd;
3307 if (current_objfile->separate_debug_objfile_backlink != nullptr)
3308 current_objfile = current_objfile->separate_debug_objfile_backlink;
3310 if (current_objfile == current_program_space->symfile_object_file)
3311 abfd = current_program_space->exec_bfd ();
3312 else
3313 abfd = current_objfile->obfd.get ();
3315 if (abfd != nullptr
3316 && gdb_bfd_scan_elf_dyntag (DT_SYMBOLIC, abfd, nullptr, nullptr) == 1)
3318 checked_current_objfile = true;
3319 if (cb (current_objfile))
3320 return;
3324 /* The linker namespace to iterate identified by the address of its
3325 r_debug object, defaulting to the initial namespace. */
3326 CORE_ADDR initial = elf_locate_base ();
3327 const solib *curr_solib = find_solib_for_objfile (current_objfile);
3328 CORE_ADDR debug_base = find_debug_base_for_solib (curr_solib);
3329 if (debug_base == 0)
3330 debug_base = initial;
3332 for (objfile *objfile : current_program_space->objfiles ())
3334 if (checked_current_objfile && objfile == current_objfile)
3335 continue;
3337 /* Try to determine the namespace into which objfile was loaded.
3339 If we fail, e.g. for manually added symbol files or for the main
3340 executable, we assume that they were added to the initial
3341 namespace. */
3342 const solib *solib = find_solib_for_objfile (objfile);
3343 CORE_ADDR solib_base = find_debug_base_for_solib (solib);
3344 if (solib_base == 0)
3345 solib_base = initial;
3347 /* Ignore objfiles that were added to a different namespace. */
3348 if (solib_base != debug_base)
3349 continue;
3351 if (cb (objfile))
3352 return;
3356 const struct solib_ops svr4_so_ops =
3358 svr4_relocate_section_addresses,
3359 svr4_clear_so,
3360 svr4_clear_solib,
3361 svr4_solib_create_inferior_hook,
3362 svr4_current_sos,
3363 open_symbol_file_object,
3364 svr4_in_dynsym_resolve_code,
3365 solib_bfd_open,
3366 nullptr,
3367 svr4_same,
3368 svr4_keep_data_in_core,
3369 svr4_update_solib_event_breakpoints,
3370 svr4_handle_solib_event,
3373 void _initialize_svr4_solib ();
3374 void
3375 _initialize_svr4_solib ()
3377 gdb::observers::free_objfile.attach (svr4_free_objfile_observer,
3378 "solib-svr4");