Home | History | Annotate | Line # | Download | only in gdb
solib-svr4.c revision 1.1.1.10
      1 /* Handle SVR4 shared libraries for GDB, the GNU Debugger.
      2 
      3    Copyright (C) 1990-2024 Free Software Foundation, Inc.
      4 
      5    This file is part of GDB.
      6 
      7    This program is free software; you can redistribute it and/or modify
      8    it under the terms of the GNU General Public License as published by
      9    the Free Software Foundation; either version 3 of the License, or
     10    (at your option) any later version.
     11 
     12    This program is distributed in the hope that it will be useful,
     13    but WITHOUT ANY WARRANTY; without even the implied warranty of
     14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15    GNU General Public License for more details.
     16 
     17    You should have received a copy of the GNU General Public License
     18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
     19 
     20 
     21 #include "elf/external.h"
     22 #include "elf/common.h"
     23 #include "elf/mips.h"
     24 
     25 #include "exceptions.h"
     26 #include "extract-store-integer.h"
     27 #include "symtab.h"
     28 #include "bfd.h"
     29 #include "symfile.h"
     30 #include "objfiles.h"
     31 #include "gdbcore.h"
     32 #include "target.h"
     33 #include "inferior.h"
     34 #include "infrun.h"
     35 #include "regcache.h"
     36 #include "observable.h"
     37 
     38 #include "solist.h"
     39 #include "solib.h"
     40 #include "solib-svr4.h"
     41 
     42 #include "bfd-target.h"
     43 #include "elf-bfd.h"
     44 #include "exec.h"
     45 #include "auxv.h"
     46 #include "gdb_bfd.h"
     47 #include "probe.h"
     48 
     49 #include <map>
     50 
     51 static struct link_map_offsets *svr4_fetch_link_map_offsets (void);
     52 static int svr4_have_link_map_offsets (void);
     53 static void svr4_relocate_main_executable (void);
     54 static void probes_table_remove_objfile_probes (struct objfile *objfile);
     55 static void svr4_iterate_over_objfiles_in_search_order
     56   (gdbarch *gdbarch, iterate_over_objfiles_in_search_order_cb_ftype cb,
     57    objfile *current_objfile);
     58 
     59 
     60 /* On SVR4 systems, a list of symbols in the dynamic linker where
     61    GDB can try to place a breakpoint to monitor shared library
     62    events.
     63 
     64    If none of these symbols are found, or other errors occur, then
     65    SVR4 systems will fall back to using a symbol as the "startup
     66    mapping complete" breakpoint address.  */
     67 
     68 static const char * const solib_break_names[] =
     69 {
     70   "r_debug_state",
     71   "_r_debug_state",
     72   "_dl_debug_state",
     73   "rtld_db_dlactivity",
     74   "__dl_rtld_db_dlactivity",
     75   "_rtld_debug_state",
     76 
     77   NULL
     78 };
     79 
     80 static const char * const bkpt_names[] =
     81 {
     82   "_start",
     83   "__start",
     84   "main",
     85   NULL
     86 };
     87 
     88 static const  char * const main_name_list[] =
     89 {
     90   "main_$main",
     91   NULL
     92 };
     93 
     94 /* What to do when a probe stop occurs.  */
     95 
     96 enum probe_action
     97 {
     98   /* Something went seriously wrong.  Stop using probes and
     99      revert to using the older interface.  */
    100   PROBES_INTERFACE_FAILED,
    101 
    102   /* No action is required.  The shared object list is still
    103      valid.  */
    104   DO_NOTHING,
    105 
    106   /* The shared object list should be reloaded entirely.  */
    107   FULL_RELOAD,
    108 
    109   /* Attempt to incrementally update the shared object list. If
    110      the update fails or is not possible, fall back to reloading
    111      the list in full.  */
    112   UPDATE_OR_RELOAD,
    113 };
    114 
    115 /* A probe's name and its associated action.  */
    116 
    117 struct probe_info
    118 {
    119   /* The name of the probe.  */
    120   const char *name;
    121 
    122   /* What to do when a probe stop occurs.  */
    123   enum probe_action action;
    124 };
    125 
    126 /* A list of named probes and their associated actions.  If all
    127    probes are present in the dynamic linker then the probes-based
    128    interface will be used.  */
    129 
    130 static const struct probe_info probe_info[] =
    131 {
    132   { "init_start", DO_NOTHING },
    133   { "init_complete", FULL_RELOAD },
    134   { "map_start", DO_NOTHING },
    135   { "map_failed", DO_NOTHING },
    136   { "reloc_complete", UPDATE_OR_RELOAD },
    137   { "unmap_start", DO_NOTHING },
    138   { "unmap_complete", FULL_RELOAD },
    139 };
    140 
    141 #define NUM_PROBES ARRAY_SIZE (probe_info)
    142 
    143 /* Return non-zero if GDB_SO_NAME and INFERIOR_SO_NAME represent
    144    the same shared library.  */
    145 
    146 static int
    147 svr4_same_1 (const char *gdb_so_name, const char *inferior_so_name)
    148 {
    149   if (strcmp (gdb_so_name, inferior_so_name) == 0)
    150     return 1;
    151 
    152   /* On Solaris, when starting inferior we think that dynamic linker is
    153      /usr/lib/ld.so.1, but later on, the table of loaded shared libraries
    154      contains /lib/ld.so.1.  Sometimes one file is a link to another, but
    155      sometimes they have identical content, but are not linked to each
    156      other.  We don't restrict this check for Solaris, but the chances
    157      of running into this situation elsewhere are very low.  */
    158   if (strcmp (gdb_so_name, "/usr/lib/ld.so.1") == 0
    159       && strcmp (inferior_so_name, "/lib/ld.so.1") == 0)
    160     return 1;
    161 
    162   /* Similarly, we observed the same issue with amd64 and sparcv9, but with
    163      different locations.  */
    164   if (strcmp (gdb_so_name, "/usr/lib/amd64/ld.so.1") == 0
    165       && strcmp (inferior_so_name, "/lib/amd64/ld.so.1") == 0)
    166     return 1;
    167 
    168   if (strcmp (gdb_so_name, "/usr/lib/sparcv9/ld.so.1") == 0
    169       && strcmp (inferior_so_name, "/lib/sparcv9/ld.so.1") == 0)
    170     return 1;
    171 
    172   return 0;
    173 }
    174 
    175 static bool
    176 svr4_same (const char *gdb_name, const char *inferior_name,
    177 	   const lm_info_svr4 &gdb_lm_info,
    178 	   const lm_info_svr4 &inferior_lm_info)
    179 {
    180   if (!svr4_same_1 (gdb_name, inferior_name))
    181     return false;
    182 
    183   /* There may be different instances of the same library, in different
    184      namespaces.  Each instance, however, must have been loaded at a
    185      different address so its relocation offset would be different.  */
    186   return gdb_lm_info.l_addr_inferior == inferior_lm_info.l_addr_inferior;
    187 }
    188 
    189 static int
    190 svr4_same (const solib &gdb, const solib &inferior)
    191 {
    192   auto *lmg
    193     = gdb::checked_static_cast<const lm_info_svr4 *> (gdb.lm_info.get ());
    194   auto *lmi
    195     = gdb::checked_static_cast<const lm_info_svr4 *> (inferior.lm_info.get ());
    196 
    197   return svr4_same (gdb.so_original_name.c_str (),
    198 		    inferior.so_original_name.c_str (), *lmg, *lmi);
    199 }
    200 
    201 static lm_info_svr4_up
    202 lm_info_read (CORE_ADDR lm_addr)
    203 {
    204   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
    205   lm_info_svr4_up lm_info;
    206 
    207   gdb::byte_vector lm (lmo->link_map_size);
    208 
    209   if (target_read_memory (lm_addr, lm.data (), lmo->link_map_size) != 0)
    210     warning (_("Error reading shared library list entry at %s"),
    211 	     paddress (current_inferior ()->arch (), lm_addr));
    212   else
    213     {
    214       type *ptr_type
    215 	= builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
    216 
    217       lm_info = std::make_unique<lm_info_svr4> ();
    218       lm_info->lm_addr = lm_addr;
    219 
    220       lm_info->l_addr_inferior = extract_typed_address (&lm[lmo->l_addr_offset],
    221 							ptr_type);
    222       lm_info->l_ld = extract_typed_address (&lm[lmo->l_ld_offset], ptr_type);
    223       lm_info->l_next = extract_typed_address (&lm[lmo->l_next_offset],
    224 					       ptr_type);
    225       lm_info->l_prev = extract_typed_address (&lm[lmo->l_prev_offset],
    226 					       ptr_type);
    227       lm_info->l_name = extract_typed_address (&lm[lmo->l_name_offset],
    228 					       ptr_type);
    229     }
    230 
    231   return lm_info;
    232 }
    233 
    234 static int
    235 has_lm_dynamic_from_link_map (void)
    236 {
    237   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
    238 
    239   return lmo->l_ld_offset >= 0;
    240 }
    241 
    242 static CORE_ADDR
    243 lm_addr_check (const solib &so, bfd *abfd)
    244 {
    245   auto *li = gdb::checked_static_cast<lm_info_svr4 *> (so.lm_info.get ());
    246 
    247   if (!li->l_addr_p)
    248     {
    249       struct bfd_section *dyninfo_sect;
    250       CORE_ADDR l_addr, l_dynaddr, dynaddr;
    251 
    252       l_addr = li->l_addr_inferior;
    253 
    254       if (! abfd || ! has_lm_dynamic_from_link_map ())
    255 	goto set_addr;
    256 
    257       l_dynaddr = li->l_ld;
    258 
    259       dyninfo_sect = bfd_get_section_by_name (abfd, ".dynamic");
    260       if (dyninfo_sect == NULL)
    261 	goto set_addr;
    262 
    263       dynaddr = bfd_section_vma (dyninfo_sect);
    264 
    265       if (dynaddr + l_addr != l_dynaddr)
    266 	{
    267 	  CORE_ADDR align = 0x1000;
    268 	  CORE_ADDR minpagesize = align;
    269 
    270 	  if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
    271 	    {
    272 	      Elf_Internal_Ehdr *ehdr = elf_tdata (abfd)->elf_header;
    273 	      Elf_Internal_Phdr *phdr = elf_tdata (abfd)->phdr;
    274 	      int i;
    275 
    276 	      align = 1;
    277 
    278 	      for (i = 0; i < ehdr->e_phnum; i++)
    279 		if (phdr[i].p_type == PT_LOAD && phdr[i].p_align > align)
    280 		  align = phdr[i].p_align;
    281 
    282 	      minpagesize = get_elf_backend_data (abfd)->minpagesize;
    283 	    }
    284 
    285 	  /* Turn it into a mask.  */
    286 	  align--;
    287 
    288 	  /* If the changes match the alignment requirements, we
    289 	     assume we're using a core file that was generated by the
    290 	     same binary, just prelinked with a different base offset.
    291 	     If it doesn't match, we may have a different binary, the
    292 	     same binary with the dynamic table loaded at an unrelated
    293 	     location, or anything, really.  To avoid regressions,
    294 	     don't adjust the base offset in the latter case, although
    295 	     odds are that, if things really changed, debugging won't
    296 	     quite work.
    297 
    298 	     One could expect more the condition
    299 	       ((l_addr & align) == 0 && ((l_dynaddr - dynaddr) & align) == 0)
    300 	     but the one below is relaxed for PPC.  The PPC kernel supports
    301 	     either 4k or 64k page sizes.  To be prepared for 64k pages,
    302 	     PPC ELF files are built using an alignment requirement of 64k.
    303 	     However, when running on a kernel supporting 4k pages, the memory
    304 	     mapping of the library may not actually happen on a 64k boundary!
    305 
    306 	     (In the usual case where (l_addr & align) == 0, this check is
    307 	     equivalent to the possibly expected check above.)
    308 
    309 	     Even on PPC it must be zero-aligned at least for MINPAGESIZE.  */
    310 
    311 	  l_addr = l_dynaddr - dynaddr;
    312 
    313 	  if ((l_addr & (minpagesize - 1)) == 0
    314 	      && (l_addr & align) == ((l_dynaddr - dynaddr) & align))
    315 	    {
    316 	      if (info_verbose)
    317 		gdb_printf (_("Using PIC (Position Independent Code) "
    318 			      "prelink displacement %s for \"%s\".\n"),
    319 			    paddress (current_inferior ()->arch (), l_addr),
    320 			    so.so_name.c_str ());
    321 	    }
    322 	  else
    323 	    {
    324 	      /* There is no way to verify the library file matches.  prelink
    325 		 can during prelinking of an unprelinked file (or unprelinking
    326 		 of a prelinked file) shift the DYNAMIC segment by arbitrary
    327 		 offset without any page size alignment.  There is no way to
    328 		 find out the ELF header and/or Program Headers for a limited
    329 		 verification if it they match.  One could do a verification
    330 		 of the DYNAMIC segment.  Still the found address is the best
    331 		 one GDB could find.  */
    332 
    333 	      warning (_(".dynamic section for \"%s\" "
    334 			 "is not at the expected address "
    335 			 "(wrong library or version mismatch?)"),
    336 			 so.so_name.c_str ());
    337 	    }
    338 	}
    339 
    340     set_addr:
    341       li->l_addr = l_addr;
    342       li->l_addr_p = 1;
    343     }
    344 
    345   return li->l_addr;
    346 }
    347 
    348 struct svr4_so
    349 {
    350   svr4_so (const char *name, lm_info_svr4_up lm_info)
    351     : name (name), lm_info (std::move (lm_info))
    352   {}
    353 
    354   std::string name;
    355   lm_info_svr4_up lm_info;
    356 };
    357 
    358 /* Per pspace SVR4 specific data.  */
    359 
    360 struct svr4_info
    361 {
    362   /* Base of dynamic linker structures in default namespace.  */
    363   CORE_ADDR debug_base = 0;
    364 
    365   /* Validity flag for debug_loader_offset.  */
    366   int debug_loader_offset_p = 0;
    367 
    368   /* Load address for the dynamic linker, inferred.  */
    369   CORE_ADDR debug_loader_offset = 0;
    370 
    371   /* Name of the dynamic linker, valid if debug_loader_offset_p.  */
    372   char *debug_loader_name = nullptr;
    373 
    374   /* Load map address for the main executable in default namespace.  */
    375   CORE_ADDR main_lm_addr = 0;
    376 
    377   CORE_ADDR interp_text_sect_low = 0;
    378   CORE_ADDR interp_text_sect_high = 0;
    379   CORE_ADDR interp_plt_sect_low = 0;
    380   CORE_ADDR interp_plt_sect_high = 0;
    381 
    382   /* True if the list of objects was last obtained from the target
    383      via qXfer:libraries-svr4:read.  */
    384   bool using_xfer = false;
    385 
    386   /* Table of struct probe_and_action instances, used by the
    387      probes-based interface to map breakpoint addresses to probes
    388      and their associated actions.  Lookup is performed using
    389      probe_and_action->prob->address.  */
    390   htab_up probes_table;
    391 
    392   /* List of objects loaded into the inferior per namespace, used by the
    393      probes-based interface.
    394 
    395      The namespace is represented by the address of its corresponding
    396      r_debug[_ext] object.  We get the namespace id as argument to the
    397      'reloc_complete' probe but we don't get it when scanning the load map
    398      on attach.
    399 
    400      The r_debug[_ext] objects may move when ld.so itself moves.  In that
    401      case, we expect also the global _r_debug to move so we can detect
    402      this and reload everything.  The r_debug[_ext] objects are not
    403      expected to move individually.
    404 
    405      The special entry zero is reserved for a linear list to support
    406      gdbstubs that do not support namespaces.  */
    407   std::map<CORE_ADDR, std::vector<svr4_so>> solib_lists;
    408 };
    409 
    410 /* Per-program-space data key.  */
    411 static const registry<program_space>::key<svr4_info> solib_svr4_pspace_data;
    412 
    413 /* Return whether DEBUG_BASE is the default namespace of INFO.  */
    414 
    415 static bool
    416 svr4_is_default_namespace (const svr4_info *info, CORE_ADDR debug_base)
    417 {
    418   return (debug_base == info->debug_base);
    419 }
    420 
    421 /* Free the probes table.  */
    422 
    423 static void
    424 free_probes_table (struct svr4_info *info)
    425 {
    426   info->probes_table.reset (nullptr);
    427 }
    428 
    429 /* Get the svr4 data for program space PSPACE.  If none is found yet, add it now.
    430    This function always returns a valid object.  */
    431 
    432 static struct svr4_info *
    433 get_svr4_info (program_space *pspace)
    434 {
    435   struct svr4_info *info = solib_svr4_pspace_data.get (pspace);
    436 
    437   if (info == NULL)
    438     info = solib_svr4_pspace_data.emplace (pspace);
    439 
    440   return info;
    441 }
    442 
    443 /* Local function prototypes */
    444 
    445 static int match_main (const char *);
    446 
    447 /* Read program header TYPE from inferior memory.  The header is found
    448    by scanning the OS auxiliary vector.
    449 
    450    If TYPE == -1, return the program headers instead of the contents of
    451    one program header.
    452 
    453    Return vector of bytes holding the program header contents, or an empty
    454    optional on failure.  If successful and P_ARCH_SIZE is non-NULL, the target
    455    architecture size (32-bit or 64-bit) is returned to *P_ARCH_SIZE.  Likewise,
    456    the base address of the section is returned in *BASE_ADDR.  */
    457 
    458 static std::optional<gdb::byte_vector>
    459 read_program_header (int type, int *p_arch_size, CORE_ADDR *base_addr)
    460 {
    461   bfd_endian byte_order = gdbarch_byte_order (current_inferior ()->arch ());
    462   CORE_ADDR at_phdr, at_phent, at_phnum, pt_phdr = 0;
    463   int arch_size, sect_size;
    464   CORE_ADDR sect_addr;
    465   int pt_phdr_p = 0;
    466 
    467   /* Get required auxv elements from target.  */
    468   if (target_auxv_search (AT_PHDR, &at_phdr) <= 0)
    469     return {};
    470   if (target_auxv_search (AT_PHENT, &at_phent) <= 0)
    471     return {};
    472   if (target_auxv_search (AT_PHNUM, &at_phnum) <= 0)
    473     return {};
    474   if (!at_phdr || !at_phnum)
    475     return {};
    476 
    477   /* Determine ELF architecture type.  */
    478   if (at_phent == sizeof (Elf32_External_Phdr))
    479     arch_size = 32;
    480   else if (at_phent == sizeof (Elf64_External_Phdr))
    481     arch_size = 64;
    482   else
    483     return {};
    484 
    485   /* Find the requested segment.  */
    486   if (type == -1)
    487     {
    488       sect_addr = at_phdr;
    489       sect_size = at_phent * at_phnum;
    490     }
    491   else if (arch_size == 32)
    492     {
    493       Elf32_External_Phdr phdr;
    494       int i;
    495 
    496       /* Search for requested PHDR.  */
    497       for (i = 0; i < at_phnum; i++)
    498 	{
    499 	  int p_type;
    500 
    501 	  if (target_read_memory (at_phdr + i * sizeof (phdr),
    502 				  (gdb_byte *)&phdr, sizeof (phdr)))
    503 	    return {};
    504 
    505 	  p_type = extract_unsigned_integer ((gdb_byte *) phdr.p_type,
    506 					     4, byte_order);
    507 
    508 	  if (p_type == PT_PHDR)
    509 	    {
    510 	      pt_phdr_p = 1;
    511 	      pt_phdr = extract_unsigned_integer ((gdb_byte *) phdr.p_vaddr,
    512 						  4, byte_order);
    513 	    }
    514 
    515 	  if (p_type == type)
    516 	    break;
    517 	}
    518 
    519       if (i == at_phnum)
    520 	return {};
    521 
    522       /* Retrieve address and size.  */
    523       sect_addr = extract_unsigned_integer ((gdb_byte *)phdr.p_vaddr,
    524 					    4, byte_order);
    525       sect_size = extract_unsigned_integer ((gdb_byte *)phdr.p_memsz,
    526 					    4, byte_order);
    527     }
    528   else
    529     {
    530       Elf64_External_Phdr phdr;
    531       int i;
    532 
    533       /* Search for requested PHDR.  */
    534       for (i = 0; i < at_phnum; i++)
    535 	{
    536 	  int p_type;
    537 
    538 	  if (target_read_memory (at_phdr + i * sizeof (phdr),
    539 				  (gdb_byte *)&phdr, sizeof (phdr)))
    540 	    return {};
    541 
    542 	  p_type = extract_unsigned_integer ((gdb_byte *) phdr.p_type,
    543 					     4, byte_order);
    544 
    545 	  if (p_type == PT_PHDR)
    546 	    {
    547 	      pt_phdr_p = 1;
    548 	      pt_phdr = extract_unsigned_integer ((gdb_byte *) phdr.p_vaddr,
    549 						  8, byte_order);
    550 	    }
    551 
    552 	  if (p_type == type)
    553 	    break;
    554 	}
    555 
    556       if (i == at_phnum)
    557 	return {};
    558 
    559       /* Retrieve address and size.  */
    560       sect_addr = extract_unsigned_integer ((gdb_byte *)phdr.p_vaddr,
    561 					    8, byte_order);
    562       sect_size = extract_unsigned_integer ((gdb_byte *)phdr.p_memsz,
    563 					    8, byte_order);
    564     }
    565 
    566   /* PT_PHDR is optional, but we really need it
    567      for PIE to make this work in general.  */
    568 
    569   if (pt_phdr_p)
    570     {
    571       /* at_phdr is real address in memory. pt_phdr is what pheader says it is.
    572 	 Relocation offset is the difference between the two. */
    573       sect_addr = sect_addr + (at_phdr - pt_phdr);
    574     }
    575 
    576   /* Read in requested program header.  */
    577   gdb::byte_vector buf (sect_size);
    578   if (target_read_memory (sect_addr, buf.data (), sect_size))
    579     return {};
    580 
    581 #if defined(__NetBSD__) && defined(__m68k__)
    582   /*
    583    * XXX PR toolchain/56268
    584    *
    585    * For NetBSD/m68k, program header is erroneously readable from core dump,
    586    * although a page containing it is missing. This spoils relocation for
    587    * the main executable, and debugging with core dumps becomes impossible,
    588    * as described in toolchain/56268.
    589    *
    590    * In order to avoid this failure, we carry out consistency check for
    591    * program header; for NetBSD, 1st entry of program header refers program
    592    * header itself. If this is not the case, we should be reading random
    593    * garbage from core dump.
    594    */
    595   if (type == -1 && arch_size == 32)
    596     {
    597       Elf32_External_Phdr phdr;
    598       int p_type, p_filesz, p_memsz;
    599 
    600       if (target_read_memory (at_phdr, (gdb_byte *)&phdr, sizeof (phdr)))
    601         return {};
    602 
    603       p_type = extract_unsigned_integer ((gdb_byte *) phdr.p_type, 4,
    604 					 byte_order);
    605       p_filesz = extract_unsigned_integer ((gdb_byte *)phdr.p_filesz, 4,
    606 					   byte_order);
    607       p_memsz = extract_unsigned_integer ((gdb_byte *)phdr.p_memsz, 4,
    608 					  byte_order);
    609 
    610       if (p_type != PT_PHDR || p_filesz != sect_size || p_memsz != sect_size)
    611 	return {};
    612     }
    613 #endif
    614 
    615   if (p_arch_size)
    616     *p_arch_size = arch_size;
    617   if (base_addr)
    618     *base_addr = sect_addr;
    619 
    620   return buf;
    621 }
    622 
    623 
    624 /* Return program interpreter string.  */
    625 static std::optional<gdb::byte_vector>
    626 find_program_interpreter (void)
    627 {
    628   /* If we have a current exec_bfd, use its section table.  */
    629   if (current_program_space->exec_bfd ()
    630       && (bfd_get_flavour (current_program_space->exec_bfd ())
    631 	  == bfd_target_elf_flavour))
    632    {
    633      struct bfd_section *interp_sect;
    634 
    635      interp_sect = bfd_get_section_by_name (current_program_space->exec_bfd (),
    636 					    ".interp");
    637      if (interp_sect != NULL)
    638       {
    639 	int sect_size = bfd_section_size (interp_sect);
    640 
    641 	gdb::byte_vector buf (sect_size);
    642 	bool res
    643 	  = bfd_get_section_contents (current_program_space->exec_bfd (),
    644 				      interp_sect, buf.data (), 0, sect_size);
    645 	if (res)
    646 	  return buf;
    647       }
    648    }
    649 
    650   /* If we didn't find it, use the target auxiliary vector.  */
    651   return read_program_header (PT_INTERP, NULL, NULL);
    652 }
    653 
    654 
    655 /* Scan for DESIRED_DYNTAG in .dynamic section of the target's main executable,
    656    found by consulting the OS auxiliary vector.  If DESIRED_DYNTAG is found, 1
    657    is returned and the corresponding PTR is set.  */
    658 
    659 static int
    660 scan_dyntag_auxv (const int desired_dyntag, CORE_ADDR *ptr,
    661 		  CORE_ADDR *ptr_addr)
    662 {
    663   bfd_endian byte_order = gdbarch_byte_order (current_inferior ()->arch ());
    664   int arch_size, step;
    665   long current_dyntag;
    666   CORE_ADDR dyn_ptr;
    667   CORE_ADDR base_addr;
    668 
    669   /* Read in .dynamic section.  */
    670   std::optional<gdb::byte_vector> ph_data
    671     = read_program_header (PT_DYNAMIC, &arch_size, &base_addr);
    672   if (!ph_data)
    673     return 0;
    674 
    675   /* Iterate over BUF and scan for DYNTAG.  If found, set PTR and return.  */
    676   step = (arch_size == 32) ? sizeof (Elf32_External_Dyn)
    677 			   : sizeof (Elf64_External_Dyn);
    678   for (gdb_byte *buf = ph_data->data (), *bufend = buf + ph_data->size ();
    679        buf < bufend; buf += step)
    680   {
    681     if (arch_size == 32)
    682       {
    683 	Elf32_External_Dyn *dynp = (Elf32_External_Dyn *) buf;
    684 
    685 	current_dyntag = extract_unsigned_integer ((gdb_byte *) dynp->d_tag,
    686 					    4, byte_order);
    687 	dyn_ptr = extract_unsigned_integer ((gdb_byte *) dynp->d_un.d_ptr,
    688 					    4, byte_order);
    689       }
    690     else
    691       {
    692 	Elf64_External_Dyn *dynp = (Elf64_External_Dyn *) buf;
    693 
    694 	current_dyntag = extract_unsigned_integer ((gdb_byte *) dynp->d_tag,
    695 					    8, byte_order);
    696 	dyn_ptr = extract_unsigned_integer ((gdb_byte *) dynp->d_un.d_ptr,
    697 					    8, byte_order);
    698       }
    699     if (current_dyntag == DT_NULL)
    700       break;
    701 
    702     if (current_dyntag == desired_dyntag)
    703       {
    704 	if (ptr)
    705 	  *ptr = dyn_ptr;
    706 
    707 	if (ptr_addr)
    708 	  *ptr_addr = base_addr + buf - ph_data->data ();
    709 
    710 	return 1;
    711       }
    712   }
    713 
    714   return 0;
    715 }
    716 
    717 /* Locate the base address of dynamic linker structs for SVR4 elf
    718    targets.
    719 
    720    For SVR4 elf targets the address of the dynamic linker's runtime
    721    structure is contained within the dynamic info section in the
    722    executable file.  The dynamic section is also mapped into the
    723    inferior address space.  Because the runtime loader fills in the
    724    real address before starting the inferior, we have to read in the
    725    dynamic info section from the inferior address space.
    726    If there are any errors while trying to find the address, we
    727    silently return 0, otherwise the found address is returned.  */
    728 
    729 static CORE_ADDR
    730 elf_locate_base (void)
    731 {
    732   CORE_ADDR dyn_ptr, dyn_ptr_addr;
    733 
    734   if (!svr4_have_link_map_offsets ())
    735     return 0;
    736 
    737   /* Look for DT_MIPS_RLD_MAP first.  MIPS executables use this
    738      instead of DT_DEBUG, although they sometimes contain an unused
    739      DT_DEBUG.  */
    740   if (gdb_bfd_scan_elf_dyntag (DT_MIPS_RLD_MAP,
    741 			       current_program_space->exec_bfd (),
    742 			       &dyn_ptr, NULL)
    743       || scan_dyntag_auxv (DT_MIPS_RLD_MAP, &dyn_ptr, NULL))
    744     {
    745       type *ptr_type
    746 	= builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
    747       gdb_byte *pbuf;
    748       int pbuf_size = ptr_type->length ();
    749 
    750       pbuf = (gdb_byte *) alloca (pbuf_size);
    751       /* DT_MIPS_RLD_MAP contains a pointer to the address
    752 	 of the dynamic link structure.  */
    753       if (target_read_memory (dyn_ptr, pbuf, pbuf_size))
    754 	return 0;
    755       return extract_typed_address (pbuf, ptr_type);
    756     }
    757 
    758   /* Then check DT_MIPS_RLD_MAP_REL.  MIPS executables now use this form
    759      because of needing to support PIE.  DT_MIPS_RLD_MAP will also exist
    760      in non-PIE.  */
    761   if (gdb_bfd_scan_elf_dyntag (DT_MIPS_RLD_MAP_REL,
    762 			       current_program_space->exec_bfd (),
    763 			       &dyn_ptr, &dyn_ptr_addr)
    764       || scan_dyntag_auxv (DT_MIPS_RLD_MAP_REL, &dyn_ptr, &dyn_ptr_addr))
    765     {
    766       type *ptr_type
    767 	= builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
    768       gdb_byte *pbuf;
    769       int pbuf_size = ptr_type->length ();
    770 
    771       pbuf = (gdb_byte *) alloca (pbuf_size);
    772       /* DT_MIPS_RLD_MAP_REL contains an offset from the address of the
    773 	 DT slot to the address of the dynamic link structure.  */
    774       if (target_read_memory (dyn_ptr + dyn_ptr_addr, pbuf, pbuf_size))
    775 	return 0;
    776       return extract_typed_address (pbuf, ptr_type);
    777     }
    778 
    779   /* Find DT_DEBUG.  */
    780   if (gdb_bfd_scan_elf_dyntag (DT_DEBUG, current_program_space->exec_bfd (),
    781 			       &dyn_ptr, NULL)
    782       || scan_dyntag_auxv (DT_DEBUG, &dyn_ptr, NULL))
    783     return dyn_ptr;
    784 
    785   /* This may be a static executable.  Look for the symbol
    786      conventionally named _r_debug, as a last resort.  */
    787   bound_minimal_symbol msymbol
    788     = lookup_minimal_symbol (current_program_space, "_r_debug",
    789 			     current_program_space->symfile_object_file);
    790   if (msymbol.minsym != NULL)
    791     return msymbol.value_address ();
    792 
    793   /* DT_DEBUG entry not found.  */
    794   return 0;
    795 }
    796 
    797 /* Find the first element in the inferior's dynamic link map, and
    798    return its address in the inferior.  Return zero if the address
    799    could not be determined.
    800 
    801    FIXME: Perhaps we should validate the info somehow, perhaps by
    802    checking r_version for a known version number, or r_state for
    803    RT_CONSISTENT.  */
    804 
    805 static CORE_ADDR
    806 solib_svr4_r_map (CORE_ADDR debug_base)
    807 {
    808   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
    809   type *ptr_type
    810     = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
    811   CORE_ADDR addr = 0;
    812 
    813   try
    814     {
    815       addr = read_memory_typed_address (debug_base + lmo->r_map_offset,
    816 					ptr_type);
    817     }
    818   catch (const gdb_exception_error &ex)
    819     {
    820       exception_print (gdb_stderr, ex);
    821     }
    822 
    823   return addr;
    824 }
    825 
    826 /* Find r_brk from the inferior's debug base.  */
    827 
    828 static CORE_ADDR
    829 solib_svr4_r_brk (struct svr4_info *info)
    830 {
    831   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
    832   type *ptr_type
    833     = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
    834 
    835   return read_memory_typed_address (info->debug_base + lmo->r_brk_offset,
    836 				    ptr_type);
    837 }
    838 
    839 /* Find the link map for the dynamic linker (if it is not in the
    840    normal list of loaded shared objects).  */
    841 
    842 static CORE_ADDR
    843 solib_svr4_r_ldsomap (struct svr4_info *info)
    844 {
    845   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
    846   type *ptr_type
    847     = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
    848   enum bfd_endian byte_order = type_byte_order (ptr_type);
    849   ULONGEST version = 0;
    850 
    851   try
    852     {
    853       /* Check version, and return zero if `struct r_debug' doesn't have
    854 	 the r_ldsomap member.  */
    855       version
    856 	= read_memory_unsigned_integer (info->debug_base + lmo->r_version_offset,
    857 					lmo->r_version_size, byte_order);
    858     }
    859   catch (const gdb_exception_error &ex)
    860     {
    861       exception_print (gdb_stderr, ex);
    862     }
    863 
    864   if (version < 2 || lmo->r_ldsomap_offset == -1)
    865     return 0;
    866 
    867   return read_memory_typed_address (info->debug_base + lmo->r_ldsomap_offset,
    868 				    ptr_type);
    869 }
    870 
    871 /* Find the next namespace from the r_next field.  */
    872 
    873 static CORE_ADDR
    874 solib_svr4_r_next (CORE_ADDR debug_base)
    875 {
    876   link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
    877   type *ptr_type
    878     = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
    879   bfd_endian byte_order = type_byte_order (ptr_type);
    880   ULONGEST version = 0;
    881 
    882   try
    883     {
    884       version
    885 	= read_memory_unsigned_integer (debug_base + lmo->r_version_offset,
    886 					lmo->r_version_size, byte_order);
    887     }
    888   catch (const gdb_exception_error &ex)
    889     {
    890       exception_print (gdb_stderr, ex);
    891     }
    892 
    893   /* The r_next field is added with r_version == 2.  */
    894   if (version < 2 || lmo->r_next_offset == -1)
    895     return 0;
    896 
    897   return read_memory_typed_address (debug_base + lmo->r_next_offset,
    898 				    ptr_type);
    899 }
    900 
    901 /* On Solaris systems with some versions of the dynamic linker,
    902    ld.so's l_name pointer points to the SONAME in the string table
    903    rather than into writable memory.  So that GDB can find shared
    904    libraries when loading a core file generated by gcore, ensure that
    905    memory areas containing the l_name string are saved in the core
    906    file.  */
    907 
    908 static int
    909 svr4_keep_data_in_core (CORE_ADDR vaddr, unsigned long size)
    910 {
    911   struct svr4_info *info;
    912   CORE_ADDR ldsomap;
    913   CORE_ADDR name_lm;
    914 
    915   info = get_svr4_info (current_program_space);
    916 
    917   info->debug_base = elf_locate_base ();
    918   if (info->debug_base == 0)
    919     return 0;
    920 
    921   ldsomap = solib_svr4_r_ldsomap (info);
    922   if (!ldsomap)
    923     return 0;
    924 
    925   std::unique_ptr<lm_info_svr4> li = lm_info_read (ldsomap);
    926   name_lm = li != NULL ? li->l_name : 0;
    927 
    928   return (name_lm >= vaddr && name_lm < vaddr + size);
    929 }
    930 
    931 /* See solist.h.  */
    932 
    933 static int
    934 open_symbol_file_object (int from_tty)
    935 {
    936   CORE_ADDR lm, l_name;
    937   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
    938   type *ptr_type
    939     = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
    940   int l_name_size = ptr_type->length ();
    941   gdb::byte_vector l_name_buf (l_name_size);
    942   struct svr4_info *info = get_svr4_info (current_program_space);
    943   symfile_add_flags add_flags = 0;
    944 
    945   if (from_tty)
    946     add_flags |= SYMFILE_VERBOSE;
    947 
    948   if (current_program_space->symfile_object_file)
    949     if (!query (_("Attempt to reload symbols from process? ")))
    950       return 0;
    951 
    952   /* Always locate the debug struct, in case it has moved.  */
    953   info->debug_base = elf_locate_base ();
    954   if (info->debug_base == 0)
    955     return 0;	/* failed somehow...  */
    956 
    957   /* First link map member should be the executable.  */
    958   lm = solib_svr4_r_map (info->debug_base);
    959   if (lm == 0)
    960     return 0;	/* failed somehow...  */
    961 
    962   /* Read address of name from target memory to GDB.  */
    963   read_memory (lm + lmo->l_name_offset, l_name_buf.data (), l_name_size);
    964 
    965   /* Convert the address to host format.  */
    966   l_name = extract_typed_address (l_name_buf.data (), ptr_type);
    967 
    968   if (l_name == 0)
    969     return 0;		/* No filename.  */
    970 
    971   /* Now fetch the filename from target memory.  */
    972   gdb::unique_xmalloc_ptr<char> filename
    973     = target_read_string (l_name, SO_NAME_MAX_PATH_SIZE - 1);
    974 
    975   if (filename == nullptr)
    976     {
    977       warning (_("failed to read exec filename from attached file"));
    978       return 0;
    979     }
    980 
    981   /* Have a pathname: read the symbol file.  */
    982   symbol_file_add_main (filename.get (), add_flags);
    983 
    984   return 1;
    985 }
    986 
    987 /* Data exchange structure for the XML parser as returned by
    988    svr4_current_sos_via_xfer_libraries.  */
    989 
    990 struct svr4_library_list
    991 {
    992   /* The so list for the current namespace.  This is internal to XML
    993      parsing.  */
    994   std::vector<svr4_so> *cur_list;
    995 
    996   /* Inferior address of struct link_map used for the main executable.  It is
    997      NULL if not known.  */
    998   CORE_ADDR main_lm;
    999 
   1000   /* List of objects loaded into the inferior per namespace.  This does
   1001      not include any default sos.
   1002 
   1003      See comment on struct svr4_info.solib_lists.  */
   1004   std::map<CORE_ADDR, std::vector<svr4_so>> solib_lists;
   1005 };
   1006 
   1007 /* This module's 'free_objfile' observer.  */
   1008 
   1009 static void
   1010 svr4_free_objfile_observer (struct objfile *objfile)
   1011 {
   1012   probes_table_remove_objfile_probes (objfile);
   1013 }
   1014 
   1015 /* Implement solib_ops.clear_so.  */
   1016 
   1017 static void
   1018 svr4_clear_so (const solib &so)
   1019 {
   1020   auto *li = gdb::checked_static_cast<lm_info_svr4 *> (so.lm_info.get ());
   1021 
   1022   if (li != NULL)
   1023     li->l_addr_p = 0;
   1024 }
   1025 
   1026 /* Create the so_list objects equivalent to the svr4_sos in SOS.  */
   1027 
   1028 static owning_intrusive_list<solib>
   1029 so_list_from_svr4_sos (const std::vector<svr4_so> &sos)
   1030 {
   1031   owning_intrusive_list<solib> dst;
   1032 
   1033   for (const svr4_so &so : sos)
   1034     {
   1035       auto &newobj = dst.emplace_back ();
   1036 
   1037       newobj.so_name = so.name;
   1038       newobj.so_original_name = so.name;
   1039       newobj.lm_info = std::make_unique<lm_info_svr4> (*so.lm_info);
   1040     }
   1041 
   1042   return dst;
   1043 }
   1044 
   1045 #ifdef HAVE_LIBEXPAT
   1046 
   1047 #include "xml-support.h"
   1048 
   1049 /* Handle the start of a <library> element.  Note: new elements are added
   1050    at the tail of the list, keeping the list in order.  */
   1051 
   1052 static void
   1053 library_list_start_library (struct gdb_xml_parser *parser,
   1054 			    const struct gdb_xml_element *element,
   1055 			    void *user_data,
   1056 			    std::vector<gdb_xml_value> &attributes)
   1057 {
   1058   struct svr4_library_list *list = (struct svr4_library_list *) user_data;
   1059   const char *name
   1060     = (const char *) xml_find_attribute (attributes, "name")->value.get ();
   1061   ULONGEST *lmp
   1062     = (ULONGEST *) xml_find_attribute (attributes, "lm")->value.get ();
   1063   ULONGEST *l_addrp
   1064     = (ULONGEST *) xml_find_attribute (attributes, "l_addr")->value.get ();
   1065   ULONGEST *l_ldp
   1066     = (ULONGEST *) xml_find_attribute (attributes, "l_ld")->value.get ();
   1067 
   1068   lm_info_svr4_up li = std::make_unique<lm_info_svr4> ();
   1069   li->lm_addr = *lmp;
   1070   li->l_addr_inferior = *l_addrp;
   1071   li->l_ld = *l_ldp;
   1072 
   1073   std::vector<svr4_so> *solist;
   1074 
   1075   /* Older versions did not supply lmid.  Put the element into the flat
   1076      list of the special namespace zero in that case.  */
   1077   gdb_xml_value *at_lmid = xml_find_attribute (attributes, "lmid");
   1078   if (at_lmid == nullptr)
   1079     solist = list->cur_list;
   1080   else
   1081     {
   1082       ULONGEST lmid = *(ULONGEST *) at_lmid->value.get ();
   1083       solist = &list->solib_lists[lmid];
   1084     }
   1085 
   1086   solist->emplace_back (name, std::move (li));
   1087 }
   1088 
   1089 /* Handle the start of a <library-list-svr4> element.  */
   1090 
   1091 static void
   1092 svr4_library_list_start_list (struct gdb_xml_parser *parser,
   1093 			      const struct gdb_xml_element *element,
   1094 			      void *user_data,
   1095 			      std::vector<gdb_xml_value> &attributes)
   1096 {
   1097   struct svr4_library_list *list = (struct svr4_library_list *) user_data;
   1098   const char *version
   1099     = (const char *) xml_find_attribute (attributes, "version")->value.get ();
   1100   struct gdb_xml_value *main_lm = xml_find_attribute (attributes, "main-lm");
   1101 
   1102   if (strcmp (version, "1.0") != 0)
   1103     gdb_xml_error (parser,
   1104 		   _("SVR4 Library list has unsupported version \"%s\""),
   1105 		   version);
   1106 
   1107   if (main_lm)
   1108     list->main_lm = *(ULONGEST *) main_lm->value.get ();
   1109 
   1110   /* Older gdbserver do not support namespaces.  We use the special
   1111      namespace zero for a linear list of libraries.  */
   1112   list->cur_list = &list->solib_lists[0];
   1113 }
   1114 
   1115 /* The allowed elements and attributes for an XML library list.
   1116    The root element is a <library-list>.  */
   1117 
   1118 static const struct gdb_xml_attribute svr4_library_attributes[] =
   1119 {
   1120   { "name", GDB_XML_AF_NONE, NULL, NULL },
   1121   { "lm", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
   1122   { "l_addr", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
   1123   { "l_ld", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
   1124   { "lmid", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
   1125   { NULL, GDB_XML_AF_NONE, NULL, NULL }
   1126 };
   1127 
   1128 static const struct gdb_xml_element svr4_library_list_children[] =
   1129 {
   1130   {
   1131     "library", svr4_library_attributes, NULL,
   1132     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
   1133     library_list_start_library, NULL
   1134   },
   1135   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   1136 };
   1137 
   1138 static const struct gdb_xml_attribute svr4_library_list_attributes[] =
   1139 {
   1140   { "version", GDB_XML_AF_NONE, NULL, NULL },
   1141   { "main-lm", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
   1142   { NULL, GDB_XML_AF_NONE, NULL, NULL }
   1143 };
   1144 
   1145 static const struct gdb_xml_element svr4_library_list_elements[] =
   1146 {
   1147   { "library-list-svr4", svr4_library_list_attributes, svr4_library_list_children,
   1148     GDB_XML_EF_NONE, svr4_library_list_start_list, NULL },
   1149   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   1150 };
   1151 
   1152 /* Parse qXfer:libraries:read packet into *SO_LIST_RETURN.  Return 1 if
   1153 
   1154    Return 0 if packet not supported, *SO_LIST_RETURN is not modified in such
   1155    case.  Return 1 if *SO_LIST_RETURN contains the library list, it may be
   1156    empty, caller is responsible for freeing all its entries.  */
   1157 
   1158 static int
   1159 svr4_parse_libraries (const char *document, struct svr4_library_list *list)
   1160 {
   1161   auto cleanup = make_scope_exit ([list] ()
   1162     {  list->solib_lists.clear (); });
   1163 
   1164   list->cur_list = nullptr;
   1165   list->main_lm = 0;
   1166   list->solib_lists.clear ();
   1167   if (gdb_xml_parse_quick (_("target library list"), "library-list-svr4.dtd",
   1168 			   svr4_library_list_elements, document, list) == 0)
   1169     {
   1170       /* Parsed successfully, keep the result.  */
   1171       cleanup.release ();
   1172       return 1;
   1173     }
   1174 
   1175   return 0;
   1176 }
   1177 
   1178 /* Attempt to get so_list from target via qXfer:libraries-svr4:read packet.
   1179 
   1180    Return 0 if packet not supported, *SO_LIST_RETURN is not modified in such
   1181    case.  Return 1 if *SO_LIST_RETURN contains the library list, it may be
   1182    empty, caller is responsible for freeing all its entries.
   1183 
   1184    Note that ANNEX must be NULL if the remote does not explicitly allow
   1185    qXfer:libraries-svr4:read packets with non-empty annexes.  Support for
   1186    this can be checked using target_augmented_libraries_svr4_read ().  */
   1187 
   1188 static int
   1189 svr4_current_sos_via_xfer_libraries (struct svr4_library_list *list,
   1190 				     const char *annex)
   1191 {
   1192   gdb_assert (annex == NULL || target_augmented_libraries_svr4_read ());
   1193 
   1194   /* Fetch the list of shared libraries.  */
   1195   std::optional<gdb::char_vector> svr4_library_document
   1196     = target_read_stralloc (current_inferior ()->top_target (),
   1197 			    TARGET_OBJECT_LIBRARIES_SVR4,
   1198 			    annex);
   1199   if (!svr4_library_document)
   1200     return 0;
   1201 
   1202   return svr4_parse_libraries (svr4_library_document->data (), list);
   1203 }
   1204 
   1205 #else
   1206 
   1207 static int
   1208 svr4_current_sos_via_xfer_libraries (struct svr4_library_list *list,
   1209 				     const char *annex)
   1210 {
   1211   return 0;
   1212 }
   1213 
   1214 #endif
   1215 
   1216 /* If no shared library information is available from the dynamic
   1217    linker, build a fallback list from other sources.  */
   1218 
   1219 static owning_intrusive_list<solib>
   1220 svr4_default_sos (svr4_info *info)
   1221 {
   1222   if (!info->debug_loader_offset_p)
   1223     return {};
   1224 
   1225   auto li = std::make_unique<lm_info_svr4> ();
   1226 
   1227   /* Nothing will ever check the other fields if we set l_addr_p.  */
   1228   li->l_addr = li->l_addr_inferior = info->debug_loader_offset;
   1229   li->l_addr_p = 1;
   1230 
   1231   owning_intrusive_list<solib> sos;
   1232   auto &newobj = sos.emplace_back ();
   1233 
   1234   newobj.lm_info = std::move (li);
   1235   newobj.so_name = info->debug_loader_name;
   1236   newobj.so_original_name = newobj.so_name;
   1237 
   1238   return sos;
   1239 }
   1240 
   1241 /* Read the whole inferior libraries chain starting at address LM.
   1242    Expect the first entry in the chain's previous entry to be PREV_LM.
   1243    Add the entries to SOS.  Ignore the first entry if IGNORE_FIRST and set
   1244    global MAIN_LM_ADDR according to it.  Returns nonzero upon success.  If zero
   1245    is returned the entries stored to LINK_PTR_PTR are still valid although they may
   1246    represent only part of the inferior library list.  */
   1247 
   1248 static int
   1249 svr4_read_so_list (svr4_info *info, CORE_ADDR lm, CORE_ADDR prev_lm,
   1250 		   std::vector<svr4_so> &sos, int ignore_first)
   1251 {
   1252   CORE_ADDR first_l_name = 0;
   1253   CORE_ADDR next_lm;
   1254 
   1255   for (; lm != 0; prev_lm = lm, lm = next_lm)
   1256     {
   1257       lm_info_svr4_up li = lm_info_read (lm);
   1258       if (li == NULL)
   1259 	return 0;
   1260 
   1261       next_lm = li->l_next;
   1262 
   1263       if (li->l_prev != prev_lm)
   1264 	{
   1265 	  warning (_("Corrupted shared library list: %s != %s"),
   1266 		   paddress (current_inferior ()->arch (), prev_lm),
   1267 		   paddress (current_inferior ()->arch (), li->l_prev));
   1268 	  return 0;
   1269 	}
   1270 
   1271       /* For SVR4 versions, the first entry in the link map is for the
   1272 	 inferior executable, so we must ignore it.  For some versions of
   1273 	 SVR4, it has no name.  For others (Solaris 2.3 for example), it
   1274 	 does have a name, so we can no longer use a missing name to
   1275 	 decide when to ignore it.  */
   1276       if (ignore_first && li->l_prev == 0)
   1277 	{
   1278 	  first_l_name = li->l_name;
   1279 	  info->main_lm_addr = li->lm_addr;
   1280 	  continue;
   1281 	}
   1282 
   1283       /* Extract this shared object's name.  */
   1284       gdb::unique_xmalloc_ptr<char> name
   1285 	= target_read_string (li->l_name, SO_NAME_MAX_PATH_SIZE - 1);
   1286       if (name == nullptr)
   1287 	{
   1288 	  /* If this entry's l_name address matches that of the
   1289 	     inferior executable, then this is not a normal shared
   1290 	     object, but (most likely) a vDSO.  In this case, silently
   1291 	     skip it; otherwise emit a warning. */
   1292 	  if (first_l_name == 0 || li->l_name != first_l_name)
   1293 	    warning (_("Can't read pathname for load map."));
   1294 	  continue;
   1295 	}
   1296 
   1297       /* If this entry has no name, or its name matches the name
   1298 	 for the main executable, don't include it in the list.  */
   1299       if (*name == '\0' || match_main (name.get ()))
   1300 	continue;
   1301 
   1302       sos.emplace_back (name.get (), std::move (li));
   1303     }
   1304 
   1305   return 1;
   1306 }
   1307 
   1308 /* Read the full list of currently loaded shared objects directly
   1309    from the inferior, without referring to any libraries read and
   1310    stored by the probes interface.  Handle special cases relating
   1311    to the first elements of the list in default namespace.  */
   1312 
   1313 static void
   1314 svr4_current_sos_direct (struct svr4_info *info)
   1315 {
   1316   CORE_ADDR lm;
   1317   bool ignore_first;
   1318   struct svr4_library_list library_list;
   1319 
   1320   /* Remove any old libraries.  We're going to read them back in again.  */
   1321   info->solib_lists.clear ();
   1322 
   1323   /* Fall back to manual examination of the target if the packet is not
   1324      supported or gdbserver failed to find DT_DEBUG.  gdb.server/solib-list.exp
   1325      tests a case where gdbserver cannot find the shared libraries list while
   1326      GDB itself is able to find it via SYMFILE_OBJFILE.
   1327 
   1328      Unfortunately statically linked inferiors will also fall back through this
   1329      suboptimal code path.  */
   1330 
   1331   info->using_xfer = svr4_current_sos_via_xfer_libraries (&library_list,
   1332 							  NULL);
   1333   if (info->using_xfer)
   1334     {
   1335       if (library_list.main_lm)
   1336 	info->main_lm_addr = library_list.main_lm;
   1337 
   1338       /* Remove an empty special zero namespace so we know that when there
   1339 	 is one, it is actually used, and we have a flat list without
   1340 	 namespace information.  */
   1341       auto it_0 = library_list.solib_lists.find (0);
   1342       if (it_0 != library_list.solib_lists.end ()
   1343 	  && it_0->second.empty ())
   1344 	library_list.solib_lists.erase (it_0);
   1345 
   1346       /* Replace the (empty) solib_lists in INFO with the one generated
   1347 	 from the target.  We don't want to copy it on assignment and then
   1348 	 delete the original afterwards, so let's just swap the
   1349 	 internals.  */
   1350       std::swap (info->solib_lists, library_list.solib_lists);
   1351       return;
   1352     }
   1353 
   1354   /* If we can't find the dynamic linker's base structure, this
   1355      must not be a dynamically linked executable.  Hmm.  */
   1356   info->debug_base = elf_locate_base ();
   1357   if (info->debug_base == 0)
   1358     return;
   1359 
   1360   /* Assume that everything is a library if the dynamic loader was loaded
   1361      late by a static executable.  */
   1362   if (current_program_space->exec_bfd ()
   1363       && bfd_get_section_by_name (current_program_space->exec_bfd (),
   1364 				  ".dynamic") == NULL)
   1365     ignore_first = false;
   1366   else
   1367     ignore_first = true;
   1368 
   1369   auto cleanup = make_scope_exit ([info] ()
   1370     { info->solib_lists.clear (); });
   1371 
   1372   /* Collect the sos in each namespace.  */
   1373   CORE_ADDR debug_base = info->debug_base;
   1374   for (; debug_base != 0;
   1375        ignore_first = false, debug_base = solib_svr4_r_next (debug_base))
   1376     {
   1377       /* Walk the inferior's link map list, and build our so_list list.  */
   1378       lm = solib_svr4_r_map (debug_base);
   1379       if (lm != 0)
   1380 	svr4_read_so_list (info, lm, 0, info->solib_lists[debug_base],
   1381 			   ignore_first);
   1382     }
   1383 
   1384   /* On Solaris, the dynamic linker is not in the normal list of
   1385      shared objects, so make sure we pick it up too.  Having
   1386      symbol information for the dynamic linker is quite crucial
   1387      for skipping dynamic linker resolver code.
   1388 
   1389      Note that we interpret the ldsomap load map address as 'virtual'
   1390      r_debug object.  If we added it to the default namespace (as it was),
   1391      we would probably run into inconsistencies with the load map's
   1392      prev/next links (I wonder if we did).  */
   1393   debug_base = solib_svr4_r_ldsomap (info);
   1394   if (debug_base != 0)
   1395     {
   1396       /* Add the dynamic linker's namespace unless we already did.  */
   1397       if (info->solib_lists.find (debug_base) == info->solib_lists.end ())
   1398 	svr4_read_so_list (info, debug_base, 0, info->solib_lists[debug_base],
   1399 			   0);
   1400     }
   1401 
   1402   cleanup.release ();
   1403 }
   1404 
   1405 /* Collect sos read and stored by the probes interface.  */
   1406 
   1407 static owning_intrusive_list<solib>
   1408 svr4_collect_probes_sos (svr4_info *info)
   1409 {
   1410   owning_intrusive_list<solib> res;
   1411 
   1412   for (const auto &tuple : info->solib_lists)
   1413     {
   1414       const std::vector<svr4_so> &sos = tuple.second;
   1415       res.splice (so_list_from_svr4_sos (sos));
   1416     }
   1417 
   1418   return res;
   1419 }
   1420 
   1421 /* Implement the main part of the "current_sos" solib_ops
   1422    method.  */
   1423 
   1424 static owning_intrusive_list<solib>
   1425 svr4_current_sos_1 (svr4_info *info)
   1426 {
   1427   owning_intrusive_list<solib> sos;
   1428 
   1429   /* If we're using the probes interface, we can use the cache as it will
   1430      be maintained by probe update/reload actions.  */
   1431   if (info->probes_table != nullptr)
   1432     sos = svr4_collect_probes_sos (info);
   1433 
   1434   /* If we're not using the probes interface or if we didn't cache
   1435      anything, read the sos to fill the cache, then collect them from the
   1436      cache.  */
   1437   if (sos.empty ())
   1438     {
   1439       svr4_current_sos_direct (info);
   1440 
   1441       sos = svr4_collect_probes_sos (info);
   1442       if (sos.empty ())
   1443 	sos = svr4_default_sos (info);
   1444     }
   1445 
   1446   return sos;
   1447 }
   1448 
   1449 /* Implement the "current_sos" solib_ops method.  */
   1450 
   1451 static owning_intrusive_list<solib>
   1452 svr4_current_sos ()
   1453 {
   1454   svr4_info *info = get_svr4_info (current_program_space);
   1455   owning_intrusive_list<solib> sos = svr4_current_sos_1 (info);
   1456   struct mem_range vsyscall_range;
   1457 
   1458   /* Filter out the vDSO module, if present.  Its symbol file would
   1459      not be found on disk.  The vDSO/vsyscall's OBJFILE is instead
   1460      managed by symfile-mem.c:add_vsyscall_page.  */
   1461   if (gdbarch_vsyscall_range (current_inferior ()->arch (), &vsyscall_range)
   1462       && vsyscall_range.length != 0)
   1463     {
   1464       for (auto so = sos.begin (); so != sos.end (); )
   1465 	{
   1466 	  /* We can't simply match the vDSO by starting address alone,
   1467 	     because lm_info->l_addr_inferior (and also l_addr) do not
   1468 	     necessarily represent the real starting address of the
   1469 	     ELF if the vDSO's ELF itself is "prelinked".  The l_ld
   1470 	     field (the ".dynamic" section of the shared object)
   1471 	     always points at the absolute/resolved address though.
   1472 	     So check whether that address is inside the vDSO's
   1473 	     mapping instead.
   1474 
   1475 	     E.g., on Linux 3.16 (x86_64) the vDSO is a regular
   1476 	     0-based ELF, and we see:
   1477 
   1478 	      (gdb) info auxv
   1479 	      33  AT_SYSINFO_EHDR  System-supplied DSO's ELF header 0x7ffff7ffb000
   1480 	      (gdb)  p/x *_r_debug.r_map.l_next
   1481 	      $1 = {l_addr = 0x7ffff7ffb000, ..., l_ld = 0x7ffff7ffb318, ...}
   1482 
   1483 	     And on Linux 2.6.32 (x86_64) we see:
   1484 
   1485 	      (gdb) info auxv
   1486 	      33  AT_SYSINFO_EHDR  System-supplied DSO's ELF header 0x7ffff7ffe000
   1487 	      (gdb) p/x *_r_debug.r_map.l_next
   1488 	      $5 = {l_addr = 0x7ffff88fe000, ..., l_ld = 0x7ffff7ffe580, ... }
   1489 
   1490 	     Dumping that vDSO shows:
   1491 
   1492 	      (gdb) info proc mappings
   1493 	      0x7ffff7ffe000  0x7ffff7fff000  0x1000  0  [vdso]
   1494 	      (gdb) dump memory vdso.bin 0x7ffff7ffe000 0x7ffff7fff000
   1495 	      # readelf -Wa vdso.bin
   1496 	      [...]
   1497 		Entry point address: 0xffffffffff700700
   1498 	      [...]
   1499 	      Section Headers:
   1500 		[Nr] Name     Type    Address	       Off    Size
   1501 		[ 0]	      NULL    0000000000000000 000000 000000
   1502 		[ 1] .hash    HASH    ffffffffff700120 000120 000038
   1503 		[ 2] .dynsym  DYNSYM  ffffffffff700158 000158 0000d8
   1504 	      [...]
   1505 		[ 9] .dynamic DYNAMIC ffffffffff700580 000580 0000f0
   1506 	  */
   1507 
   1508 	  auto *li = gdb::checked_static_cast<lm_info_svr4 *> (so->lm_info.get ());
   1509 
   1510 	  if (vsyscall_range.contains (li->l_ld))
   1511 	    {
   1512 	      so = sos.erase (so);
   1513 	      break;
   1514 	    }
   1515 
   1516 	  ++so;
   1517 	}
   1518     }
   1519 
   1520   return sos;
   1521 }
   1522 
   1523 /* Get the address of the link_map for a given OBJFILE.  */
   1524 
   1525 CORE_ADDR
   1526 svr4_fetch_objfile_link_map (struct objfile *objfile)
   1527 {
   1528   struct svr4_info *info = get_svr4_info (objfile->pspace ());
   1529 
   1530   /* Cause svr4_current_sos() to be run if it hasn't been already.  */
   1531   if (info->main_lm_addr == 0)
   1532     solib_add (NULL, 0, auto_solib_add);
   1533 
   1534   /* svr4_current_sos() will set main_lm_addr for the main executable.  */
   1535   if (objfile == current_program_space->symfile_object_file)
   1536     return info->main_lm_addr;
   1537 
   1538   /* The other link map addresses may be found by examining the list
   1539      of shared libraries.  */
   1540   for (const solib &so : current_program_space->solibs ())
   1541     if (so.objfile == objfile)
   1542       {
   1543 	auto *li
   1544 	  = gdb::checked_static_cast<lm_info_svr4 *> (so.lm_info.get ());
   1545 
   1546 	return li->lm_addr;
   1547       }
   1548 
   1549   /* Not found!  */
   1550   return 0;
   1551 }
   1552 
   1553 /* On some systems, the only way to recognize the link map entry for
   1554    the main executable file is by looking at its name.  Return
   1555    non-zero iff SONAME matches one of the known main executable names.  */
   1556 
   1557 static int
   1558 match_main (const char *soname)
   1559 {
   1560   const char * const *mainp;
   1561 
   1562   for (mainp = main_name_list; *mainp != NULL; mainp++)
   1563     {
   1564       if (strcmp (soname, *mainp) == 0)
   1565 	return (1);
   1566     }
   1567 
   1568   return (0);
   1569 }
   1570 
   1571 /* Return 1 if PC lies in the dynamic symbol resolution code of the
   1572    SVR4 run time loader.  */
   1573 
   1574 int
   1575 svr4_in_dynsym_resolve_code (CORE_ADDR pc)
   1576 {
   1577   struct svr4_info *info = get_svr4_info (current_program_space);
   1578 
   1579   return ((pc >= info->interp_text_sect_low
   1580 	   && pc < info->interp_text_sect_high)
   1581 	  || (pc >= info->interp_plt_sect_low
   1582 	      && pc < info->interp_plt_sect_high)
   1583 	  || in_plt_section (pc)
   1584 	  || in_gnu_ifunc_stub (pc));
   1585 }
   1586 
   1587 /* Given an executable's ABFD and target, compute the entry-point
   1588    address.  */
   1589 
   1590 static CORE_ADDR
   1591 exec_entry_point (struct bfd *abfd, struct target_ops *targ)
   1592 {
   1593   CORE_ADDR addr;
   1594 
   1595   /* KevinB wrote ... for most targets, the address returned by
   1596      bfd_get_start_address() is the entry point for the start
   1597      function.  But, for some targets, bfd_get_start_address() returns
   1598      the address of a function descriptor from which the entry point
   1599      address may be extracted.  This address is extracted by
   1600      gdbarch_convert_from_func_ptr_addr().  The method
   1601      gdbarch_convert_from_func_ptr_addr() is the merely the identify
   1602      function for targets which don't use function descriptors.  */
   1603   addr = gdbarch_convert_from_func_ptr_addr (current_inferior ()->arch (),
   1604 					     bfd_get_start_address (abfd),
   1605 					     targ);
   1606   return gdbarch_addr_bits_remove (current_inferior ()->arch (), addr);
   1607 }
   1608 
   1609 /* A probe and its associated action.  */
   1610 
   1611 struct probe_and_action
   1612 {
   1613   /* The probe.  */
   1614   probe *prob;
   1615 
   1616   /* The relocated address of the probe.  */
   1617   CORE_ADDR address;
   1618 
   1619   /* The action.  */
   1620   enum probe_action action;
   1621 
   1622   /* The objfile where this probe was found.  */
   1623   struct objfile *objfile;
   1624 };
   1625 
   1626 /* Returns a hash code for the probe_and_action referenced by p.  */
   1627 
   1628 static hashval_t
   1629 hash_probe_and_action (const void *p)
   1630 {
   1631   const struct probe_and_action *pa = (const struct probe_and_action *) p;
   1632 
   1633   return (hashval_t) pa->address;
   1634 }
   1635 
   1636 /* Returns non-zero if the probe_and_actions referenced by p1 and p2
   1637    are equal.  */
   1638 
   1639 static int
   1640 equal_probe_and_action (const void *p1, const void *p2)
   1641 {
   1642   const struct probe_and_action *pa1 = (const struct probe_and_action *) p1;
   1643   const struct probe_and_action *pa2 = (const struct probe_and_action *) p2;
   1644 
   1645   return pa1->address == pa2->address;
   1646 }
   1647 
   1648 /* Traversal function for probes_table_remove_objfile_probes.  */
   1649 
   1650 static int
   1651 probes_table_htab_remove_objfile_probes (void **slot, void *info)
   1652 {
   1653   probe_and_action *pa = (probe_and_action *) *slot;
   1654   struct objfile *objfile = (struct objfile *) info;
   1655 
   1656   if (pa->objfile == objfile)
   1657     htab_clear_slot (get_svr4_info (objfile->pspace ())->probes_table.get (),
   1658 		     slot);
   1659 
   1660   return 1;
   1661 }
   1662 
   1663 /* Remove all probes that belong to OBJFILE from the probes table.  */
   1664 
   1665 static void
   1666 probes_table_remove_objfile_probes (struct objfile *objfile)
   1667 {
   1668   svr4_info *info = solib_svr4_pspace_data.get (objfile->pspace ());
   1669   if (info == nullptr || info->probes_table == nullptr)
   1670     return;
   1671 
   1672   htab_traverse_noresize (info->probes_table.get (),
   1673 			  probes_table_htab_remove_objfile_probes, objfile);
   1674 }
   1675 
   1676 /* Register a solib event probe and its associated action in the
   1677    probes table.  */
   1678 
   1679 static void
   1680 register_solib_event_probe (svr4_info *info, struct objfile *objfile,
   1681 			    probe *prob, CORE_ADDR address,
   1682 			    enum probe_action action)
   1683 {
   1684   struct probe_and_action lookup, *pa;
   1685   void **slot;
   1686 
   1687   /* Create the probes table, if necessary.  */
   1688   if (info->probes_table == NULL)
   1689     info->probes_table.reset (htab_create_alloc (1, hash_probe_and_action,
   1690 						 equal_probe_and_action,
   1691 						 xfree, xcalloc, xfree));
   1692 
   1693   lookup.address = address;
   1694   slot = htab_find_slot (info->probes_table.get (), &lookup, INSERT);
   1695   gdb_assert (*slot == HTAB_EMPTY_ENTRY);
   1696 
   1697   pa = XCNEW (struct probe_and_action);
   1698   pa->prob = prob;
   1699   pa->address = address;
   1700   pa->action = action;
   1701   pa->objfile = objfile;
   1702 
   1703   *slot = pa;
   1704 }
   1705 
   1706 /* Get the solib event probe at the specified location, and the
   1707    action associated with it.  Returns NULL if no solib event probe
   1708    was found.  */
   1709 
   1710 static struct probe_and_action *
   1711 solib_event_probe_at (struct svr4_info *info, CORE_ADDR address)
   1712 {
   1713   struct probe_and_action lookup;
   1714   void **slot;
   1715 
   1716   lookup.address = address;
   1717   slot = htab_find_slot (info->probes_table.get (), &lookup, NO_INSERT);
   1718 
   1719   if (slot == NULL)
   1720     return NULL;
   1721 
   1722   return (struct probe_and_action *) *slot;
   1723 }
   1724 
   1725 /* Decide what action to take when the specified solib event probe is
   1726    hit.  */
   1727 
   1728 static enum probe_action
   1729 solib_event_probe_action (struct probe_and_action *pa)
   1730 {
   1731   enum probe_action action;
   1732   unsigned probe_argc = 0;
   1733   frame_info_ptr frame = get_current_frame ();
   1734 
   1735   action = pa->action;
   1736   if (action == DO_NOTHING || action == PROBES_INTERFACE_FAILED)
   1737     return action;
   1738 
   1739   gdb_assert (action == FULL_RELOAD || action == UPDATE_OR_RELOAD);
   1740 
   1741   /* Check that an appropriate number of arguments has been supplied.
   1742      We expect:
   1743        arg0: Lmid_t lmid (mandatory)
   1744        arg1: struct r_debug *debug_base (mandatory)
   1745        arg2: struct link_map *new (optional, for incremental updates)  */
   1746   try
   1747     {
   1748       probe_argc = pa->prob->get_argument_count (get_frame_arch (frame));
   1749     }
   1750   catch (const gdb_exception_error &ex)
   1751     {
   1752       exception_print (gdb_stderr, ex);
   1753       probe_argc = 0;
   1754     }
   1755 
   1756   /* If get_argument_count throws an exception, probe_argc will be set
   1757      to zero.  However, if pa->prob does not have arguments, then
   1758      get_argument_count will succeed but probe_argc will also be zero.
   1759      Both cases happen because of different things, but they are
   1760      treated equally here: action will be set to
   1761      PROBES_INTERFACE_FAILED.  */
   1762   if (probe_argc == 2)
   1763     action = FULL_RELOAD;
   1764   else if (probe_argc < 2)
   1765     action = PROBES_INTERFACE_FAILED;
   1766 
   1767   return action;
   1768 }
   1769 
   1770 /* Populate the shared object list by reading the entire list of
   1771    shared objects from the inferior.  Handle special cases relating
   1772    to the first elements of the list.  Returns nonzero on success.  */
   1773 
   1774 static int
   1775 solist_update_full (struct svr4_info *info)
   1776 {
   1777   svr4_current_sos_direct (info);
   1778 
   1779   return 1;
   1780 }
   1781 
   1782 /* Update the shared object list starting from the link-map entry
   1783    passed by the linker in the probe's third argument.  Returns
   1784    nonzero if the list was successfully updated, or zero to indicate
   1785    failure.  */
   1786 
   1787 static int
   1788 solist_update_incremental (svr4_info *info, CORE_ADDR debug_base,
   1789 			   CORE_ADDR lm)
   1790 {
   1791   /* Fall back to a full update if we are using a remote target
   1792      that does not support incremental transfers.  */
   1793   if (info->using_xfer && !target_augmented_libraries_svr4_read ())
   1794     return 0;
   1795 
   1796   /* Fall back to a full update if we used the special namespace zero.  We
   1797      wouldn't be able to find the last item in the DEBUG_BASE namespace
   1798      and hence get the prev link wrong.  */
   1799   if (info->solib_lists.find (0) != info->solib_lists.end ())
   1800     return 0;
   1801 
   1802   std::vector<svr4_so> &solist = info->solib_lists[debug_base];
   1803   CORE_ADDR prev_lm;
   1804 
   1805   if (solist.empty ())
   1806     {
   1807       /* svr4_current_sos_direct contains logic to handle a number of
   1808 	 special cases relating to the first elements of the list in
   1809 	 default namespace.  To avoid duplicating this logic we defer to
   1810 	 solist_update_full in this case.  */
   1811       if (svr4_is_default_namespace (info, debug_base))
   1812 	return 0;
   1813 
   1814       prev_lm = 0;
   1815     }
   1816   else
   1817     prev_lm = solist.back ().lm_info->lm_addr;
   1818 
   1819   /* Read the new objects.  */
   1820   if (info->using_xfer)
   1821     {
   1822       struct svr4_library_list library_list;
   1823       char annex[64];
   1824 
   1825       /* Unknown key=value pairs are ignored by the gdbstub.  */
   1826       xsnprintf (annex, sizeof (annex), "lmid=%s;start=%s;prev=%s",
   1827 		 phex_nz (debug_base, sizeof (debug_base)),
   1828 		 phex_nz (lm, sizeof (lm)),
   1829 		 phex_nz (prev_lm, sizeof (prev_lm)));
   1830       if (!svr4_current_sos_via_xfer_libraries (&library_list, annex))
   1831 	return 0;
   1832 
   1833       /* Get the so list from the target.  We replace the list in the
   1834 	 target response so we can easily check that the response only
   1835 	 covers one namespace.
   1836 
   1837 	 We expect gdbserver to provide updates for the namespace that
   1838 	 contains LM, which would be this namespace...  */
   1839       std::vector<svr4_so> sos;
   1840       auto it_debug_base = library_list.solib_lists.find (debug_base);
   1841       if (it_debug_base != library_list.solib_lists.end ())
   1842 	std::swap (sos, it_debug_base->second);
   1843       else
   1844 	{
   1845 	  /* ...or for the special zero namespace for earlier versions...  */
   1846 	  auto it_0 = library_list.solib_lists.find (0);
   1847 	  if (it_0 != library_list.solib_lists.end ())
   1848 	    std::swap (sos, it_0->second);
   1849 	}
   1850 
   1851       /* ...but nothing else.  */
   1852       for (const auto &tuple : library_list.solib_lists)
   1853 	gdb_assert (tuple.second.empty ());
   1854 
   1855       std::move (sos.begin (), sos.end (), std::back_inserter (solist));
   1856     }
   1857   else
   1858     {
   1859       /* IGNORE_FIRST may safely be set to zero here because the
   1860 	 above check and deferral to solist_update_full ensures
   1861 	 that this call to svr4_read_so_list will never see the
   1862 	 first element.  */
   1863       if (!svr4_read_so_list (info, lm, prev_lm, solist, 0))
   1864 	return 0;
   1865     }
   1866 
   1867   return 1;
   1868 }
   1869 
   1870 /* Disable the probes-based linker interface and revert to the
   1871    original interface.  We don't reset the breakpoints as the
   1872    ones set up for the probes-based interface are adequate.  */
   1873 
   1874 static void
   1875 disable_probes_interface (svr4_info *info)
   1876 {
   1877   warning (_("Probes-based dynamic linker interface failed.\n"
   1878 	     "Reverting to original interface."));
   1879 
   1880   free_probes_table (info);
   1881   info->solib_lists.clear ();
   1882 }
   1883 
   1884 /* Update the solib list as appropriate when using the
   1885    probes-based linker interface.  Do nothing if using the
   1886    standard interface.  */
   1887 
   1888 static void
   1889 svr4_handle_solib_event (void)
   1890 {
   1891   struct svr4_info *info = get_svr4_info (current_program_space);
   1892   struct probe_and_action *pa;
   1893   enum probe_action action;
   1894   struct value *val = NULL;
   1895   CORE_ADDR pc, debug_base, lm = 0;
   1896   frame_info_ptr frame = get_current_frame ();
   1897 
   1898   /* Do nothing if not using the probes interface.  */
   1899   if (info->probes_table == NULL)
   1900     return;
   1901 
   1902   pc = regcache_read_pc (get_thread_regcache (inferior_thread ()));
   1903   pa = solib_event_probe_at (info, pc);
   1904   if (pa == nullptr)
   1905     {
   1906       /* When some solib ops sits above us, it can respond to a solib event
   1907 	 by calling in here.  This is done assuming that if the current event
   1908 	 is not an SVR4 solib event, calling here should be a no-op.  */
   1909       return;
   1910     }
   1911 
   1912   /* If anything goes wrong we revert to the original linker
   1913      interface.  */
   1914   auto cleanup = make_scope_exit ([info] ()
   1915     {
   1916       disable_probes_interface (info);
   1917     });
   1918 
   1919   action = solib_event_probe_action (pa);
   1920   if (action == PROBES_INTERFACE_FAILED)
   1921     return;
   1922 
   1923   if (action == DO_NOTHING)
   1924     {
   1925       cleanup.release ();
   1926       return;
   1927     }
   1928 
   1929   /* evaluate_argument looks up symbols in the dynamic linker
   1930      using find_pc_section.  find_pc_section is accelerated by a cache
   1931      called the section map.  The section map is invalidated every
   1932      time a shared library is loaded or unloaded, and if the inferior
   1933      is generating a lot of shared library events then the section map
   1934      will be updated every time svr4_handle_solib_event is called.
   1935      We called find_pc_section in svr4_create_solib_event_breakpoints,
   1936      so we can guarantee that the dynamic linker's sections are in the
   1937      section map.  We can therefore inhibit section map updates across
   1938      these calls to evaluate_argument and save a lot of time.  */
   1939   {
   1940     scoped_restore inhibit_updates
   1941       = inhibit_section_map_updates (current_program_space);
   1942 
   1943     try
   1944       {
   1945 	val = pa->prob->evaluate_argument (1, frame);
   1946       }
   1947     catch (const gdb_exception_error &ex)
   1948       {
   1949 	exception_print (gdb_stderr, ex);
   1950 	val = NULL;
   1951       }
   1952 
   1953     if (val == NULL)
   1954       return;
   1955 
   1956     debug_base = value_as_address (val);
   1957     if (debug_base == 0)
   1958       return;
   1959 
   1960     /* If the global _r_debug object moved, we need to reload everything
   1961        since we cannot identify namespaces (by the location of their
   1962        r_debug_ext object) anymore.  */
   1963     CORE_ADDR global_debug_base = elf_locate_base ();
   1964     if (global_debug_base != info->debug_base)
   1965       {
   1966 	info->debug_base = global_debug_base;
   1967 	action = FULL_RELOAD;
   1968       }
   1969 
   1970     if (info->debug_base == 0)
   1971       {
   1972 	/* It's possible for the reloc_complete probe to be triggered before
   1973 	   the linker has set the DT_DEBUG pointer (for example, when the
   1974 	   linker has finished relocating an LD_AUDIT library or its
   1975 	   dependencies).  Since we can't yet handle libraries from other link
   1976 	   namespaces, we don't lose anything by ignoring them here.  */
   1977 	struct value *link_map_id_val;
   1978 	try
   1979 	  {
   1980 	    link_map_id_val = pa->prob->evaluate_argument (0, frame);
   1981 	  }
   1982 	catch (const gdb_exception_error &)
   1983 	  {
   1984 	    link_map_id_val = NULL;
   1985 	  }
   1986 	/* glibc and illumos' libc both define LM_ID_BASE as zero.  */
   1987 	if (link_map_id_val != NULL && value_as_long (link_map_id_val) != 0)
   1988 	  action = DO_NOTHING;
   1989 	else
   1990 	  return;
   1991       }
   1992 
   1993     if (action == UPDATE_OR_RELOAD)
   1994       {
   1995 	try
   1996 	  {
   1997 	    val = pa->prob->evaluate_argument (2, frame);
   1998 	  }
   1999 	catch (const gdb_exception_error &ex)
   2000 	  {
   2001 	    exception_print (gdb_stderr, ex);
   2002 	    return;
   2003 	  }
   2004 
   2005 	if (val != NULL)
   2006 	  lm = value_as_address (val);
   2007 
   2008 	if (lm == 0)
   2009 	  action = FULL_RELOAD;
   2010       }
   2011 
   2012     /* Resume section map updates.  Closing the scope is
   2013        sufficient.  */
   2014   }
   2015 
   2016   if (action == UPDATE_OR_RELOAD)
   2017     {
   2018       if (!solist_update_incremental (info, debug_base, lm))
   2019 	action = FULL_RELOAD;
   2020     }
   2021 
   2022   if (action == FULL_RELOAD)
   2023     {
   2024       if (!solist_update_full (info))
   2025 	return;
   2026     }
   2027 
   2028   cleanup.release ();
   2029 }
   2030 
   2031 /* Helper function for svr4_update_solib_event_breakpoints.  */
   2032 
   2033 static bool
   2034 svr4_update_solib_event_breakpoint (struct breakpoint *b)
   2035 {
   2036   if (b->type != bp_shlib_event)
   2037     {
   2038       /* Continue iterating.  */
   2039       return false;
   2040     }
   2041 
   2042   for (bp_location &loc : b->locations ())
   2043     {
   2044       struct svr4_info *info;
   2045       struct probe_and_action *pa;
   2046 
   2047       info = solib_svr4_pspace_data.get (loc.pspace);
   2048       if (info == NULL || info->probes_table == NULL)
   2049 	continue;
   2050 
   2051       pa = solib_event_probe_at (info, loc.address);
   2052       if (pa == NULL)
   2053 	continue;
   2054 
   2055       if (pa->action == DO_NOTHING)
   2056 	{
   2057 	  if (b->enable_state == bp_disabled && stop_on_solib_events)
   2058 	    enable_breakpoint (b);
   2059 	  else if (b->enable_state == bp_enabled && !stop_on_solib_events)
   2060 	    disable_breakpoint (b);
   2061 	}
   2062 
   2063       break;
   2064     }
   2065 
   2066   /* Continue iterating.  */
   2067   return false;
   2068 }
   2069 
   2070 /* Enable or disable optional solib event breakpoints as appropriate.
   2071    Called whenever stop_on_solib_events is changed.  */
   2072 
   2073 static void
   2074 svr4_update_solib_event_breakpoints (void)
   2075 {
   2076   for (breakpoint &bp : all_breakpoints_safe ())
   2077     svr4_update_solib_event_breakpoint (&bp);
   2078 }
   2079 
   2080 /* Create and register solib event breakpoints.  PROBES is an array
   2081    of NUM_PROBES elements, each of which is vector of probes.  A
   2082    solib event breakpoint will be created and registered for each
   2083    probe.  */
   2084 
   2085 static void
   2086 svr4_create_probe_breakpoints (svr4_info *info, struct gdbarch *gdbarch,
   2087 			       const std::vector<probe *> *probes,
   2088 			       struct objfile *objfile)
   2089 {
   2090   for (int i = 0; i < NUM_PROBES; i++)
   2091     {
   2092       enum probe_action action = probe_info[i].action;
   2093 
   2094       for (probe *p : probes[i])
   2095 	{
   2096 	  CORE_ADDR address = p->get_relocated_address (objfile);
   2097 
   2098 	  solib_debug_printf ("name=%s, addr=%s", probe_info[i].name,
   2099 			      paddress (gdbarch, address));
   2100 
   2101 	  create_solib_event_breakpoint (gdbarch, address);
   2102 	  register_solib_event_probe (info, objfile, p, address, action);
   2103 	}
   2104     }
   2105 
   2106   svr4_update_solib_event_breakpoints ();
   2107 }
   2108 
   2109 /* Find all the glibc named probes.  Only if all of the probes are found, then
   2110    create them and return true.  Otherwise return false.  If WITH_PREFIX is set
   2111    then add "rtld" to the front of the probe names.  */
   2112 static bool
   2113 svr4_find_and_create_probe_breakpoints (svr4_info *info,
   2114 					struct gdbarch *gdbarch,
   2115 					struct obj_section *os,
   2116 					bool with_prefix)
   2117 {
   2118   SOLIB_SCOPED_DEBUG_START_END ("objfile=%s, with_prefix=%d",
   2119 				os->objfile->original_name, with_prefix);
   2120 
   2121   std::vector<probe *> probes[NUM_PROBES];
   2122 
   2123   for (int i = 0; i < NUM_PROBES; i++)
   2124     {
   2125       const char *name = probe_info[i].name;
   2126       char buf[32];
   2127 
   2128       /* Fedora 17 and Red Hat Enterprise Linux 6.2-6.4 shipped with an early
   2129 	 version of the probes code in which the probes' names were prefixed
   2130 	 with "rtld_" and the "map_failed" probe did not exist.  The locations
   2131 	 of the probes are otherwise the same, so we check for probes with
   2132 	 prefixed names if probes with unprefixed names are not present.  */
   2133       if (with_prefix)
   2134 	{
   2135 	  xsnprintf (buf, sizeof (buf), "rtld_%s", name);
   2136 	  name = buf;
   2137 	}
   2138 
   2139       probes[i] = find_probes_in_objfile (os->objfile, "rtld", name);
   2140       solib_debug_printf ("probe=%s, num found=%zu", name, probes[i].size ());
   2141 
   2142       /* Ensure at least one probe for the current name was found.  */
   2143       if (probes[i].empty ())
   2144 	{
   2145 	  /* The "map_failed" probe did not exist in early versions of the
   2146 	     probes code in which the probes' names were prefixed with
   2147 	     "rtld_".
   2148 
   2149 	     Additionally, the "map_failed" probe was accidentally removed
   2150 	     from glibc 2.35 and 2.36, when changes in glibc meant the
   2151 	     probe could no longer be reached, and the compiler optimized
   2152 	     the probe away.  In this case the probe name doesn't have the
   2153 	     "rtld_" prefix.
   2154 
   2155 	     To handle this, and give GDB as much flexibility as possible,
   2156 	     we make the rule that, if a probe isn't required for the
   2157 	     correct operation of GDB (i.e. its action is DO_NOTHING), then
   2158 	     we will still use the probes interface, even if that probe is
   2159 	     missing.
   2160 
   2161 	     The only (possible) downside of this is that, if the user has
   2162 	     'set stop-on-solib-events on' in effect, then they might get
   2163 	     fewer events using the probes interface than with the classic
   2164 	     non-probes interface.  */
   2165 	  if (probe_info[i].action == DO_NOTHING)
   2166 	    continue;
   2167 	  else
   2168 	    return false;
   2169 	}
   2170 
   2171       /* Ensure probe arguments can be evaluated.  */
   2172       for (probe *p : probes[i])
   2173 	{
   2174 	  if (!p->can_evaluate_arguments ())
   2175 	    return false;
   2176 	  /* This will fail if the probe is invalid.  This has been seen on Arm
   2177 	     due to references to symbols that have been resolved away.  */
   2178 	  try
   2179 	    {
   2180 	      p->get_argument_count (gdbarch);
   2181 	    }
   2182 	  catch (const gdb_exception_error &ex)
   2183 	    {
   2184 	      exception_print (gdb_stderr, ex);
   2185 	      warning (_("Initializing probes-based dynamic linker interface "
   2186 			 "failed.\nReverting to original interface."));
   2187 	      return false;
   2188 	    }
   2189 	}
   2190     }
   2191 
   2192   /* All probes found.  Now create them.  */
   2193   solib_debug_printf ("using probes interface");
   2194   svr4_create_probe_breakpoints (info, gdbarch, probes, os->objfile);
   2195   return true;
   2196 }
   2197 
   2198 /* Both the SunOS and the SVR4 dynamic linkers call a marker function
   2199    before and after mapping and unmapping shared libraries.  The sole
   2200    purpose of this method is to allow debuggers to set a breakpoint so
   2201    they can track these changes.
   2202 
   2203    Some versions of the glibc dynamic linker contain named probes
   2204    to allow more fine grained stopping.  Given the address of the
   2205    original marker function, this function attempts to find these
   2206    probes, and if found, sets breakpoints on those instead.  If the
   2207    probes aren't found, a single breakpoint is set on the original
   2208    marker function.  */
   2209 
   2210 static void
   2211 svr4_create_solib_event_breakpoints (svr4_info *info, struct gdbarch *gdbarch,
   2212 				     CORE_ADDR address)
   2213 {
   2214   struct obj_section *os = find_pc_section (address);
   2215 
   2216   if (os == nullptr
   2217       || (!svr4_find_and_create_probe_breakpoints (info, gdbarch, os, false)
   2218 	  && !svr4_find_and_create_probe_breakpoints (info, gdbarch, os, true)))
   2219     {
   2220       solib_debug_printf ("falling back to r_brk breakpoint: addr=%s",
   2221 			  paddress (gdbarch, address));
   2222       create_solib_event_breakpoint (gdbarch, address);
   2223     }
   2224 }
   2225 
   2226 /* Arrange for dynamic linker to hit breakpoint.
   2227 
   2228    Both the SunOS and the SVR4 dynamic linkers have, as part of their
   2229    debugger interface, support for arranging for the inferior to hit
   2230    a breakpoint after mapping in the shared libraries.  This function
   2231    enables that breakpoint.
   2232 
   2233    For SunOS, there is a special flag location (in_debugger) which we
   2234    set to 1.  When the dynamic linker sees this flag set, it will set
   2235    a breakpoint at a location known only to itself, after saving the
   2236    original contents of that place and the breakpoint address itself,
   2237    in its own internal structures.  When we resume the inferior, it
   2238    will eventually take a SIGTRAP when it runs into the breakpoint.
   2239    We handle this (in a different place) by restoring the contents of
   2240    the breakpointed location (which is only known after it stops),
   2241    chasing around to locate the shared libraries that have been
   2242    loaded, then resuming.
   2243 
   2244    For SVR4, the debugger interface structure contains a member (r_brk)
   2245    which is statically initialized at the time the shared library is
   2246    built, to the offset of a function (_r_debug_state) which is guaran-
   2247    teed to be called once before mapping in a library, and again when
   2248    the mapping is complete.  At the time we are examining this member,
   2249    it contains only the unrelocated offset of the function, so we have
   2250    to do our own relocation.  Later, when the dynamic linker actually
   2251    runs, it relocates r_brk to be the actual address of _r_debug_state().
   2252 
   2253    The debugger interface structure also contains an enumeration which
   2254    is set to either RT_ADD or RT_DELETE prior to changing the mapping,
   2255    depending upon whether or not the library is being mapped or unmapped,
   2256    and then set to RT_CONSISTENT after the library is mapped/unmapped.  */
   2257 
   2258 static int
   2259 enable_break (struct svr4_info *info, int from_tty)
   2260 {
   2261   const char * const *bkpt_namep;
   2262   asection *interp_sect;
   2263   CORE_ADDR sym_addr;
   2264 
   2265   info->interp_text_sect_low = info->interp_text_sect_high = 0;
   2266   info->interp_plt_sect_low = info->interp_plt_sect_high = 0;
   2267 
   2268   /* If we already have a shared library list in the target, and
   2269      r_debug contains r_brk, set the breakpoint there - this should
   2270      mean r_brk has already been relocated.  Assume the dynamic linker
   2271      is the object containing r_brk.  */
   2272 
   2273   solib_add (NULL, from_tty, auto_solib_add);
   2274   sym_addr = 0;
   2275   if (info->debug_base && solib_svr4_r_map (info->debug_base) != 0)
   2276     sym_addr = solib_svr4_r_brk (info);
   2277 
   2278   if (sym_addr != 0)
   2279     {
   2280       struct obj_section *os;
   2281 
   2282       sym_addr = gdbarch_addr_bits_remove
   2283 	(current_inferior ()->arch (),
   2284 	 gdbarch_convert_from_func_ptr_addr
   2285 	   (current_inferior ()->arch (), sym_addr,
   2286 	    current_inferior ()->top_target ()));
   2287 
   2288       /* On at least some versions of Solaris there's a dynamic relocation
   2289 	 on _r_debug.r_brk and SYM_ADDR may not be relocated yet, e.g., if
   2290 	 we get control before the dynamic linker has self-relocated.
   2291 	 Check if SYM_ADDR is in a known section, if it is assume we can
   2292 	 trust its value.  This is just a heuristic though, it could go away
   2293 	 or be replaced if it's getting in the way.
   2294 
   2295 	 On ARM we need to know whether the ISA of rtld_db_dlactivity (or
   2296 	 however it's spelled in your particular system) is ARM or Thumb.
   2297 	 That knowledge is encoded in the address, if it's Thumb the low bit
   2298 	 is 1.  However, we've stripped that info above and it's not clear
   2299 	 what all the consequences are of passing a non-addr_bits_remove'd
   2300 	 address to svr4_create_solib_event_breakpoints.  The call to
   2301 	 find_pc_section verifies we know about the address and have some
   2302 	 hope of computing the right kind of breakpoint to use (via
   2303 	 symbol info).  It does mean that GDB needs to be pointed at a
   2304 	 non-stripped version of the dynamic linker in order to obtain
   2305 	 information it already knows about.  Sigh.  */
   2306 
   2307       os = find_pc_section (sym_addr);
   2308       if (os != NULL)
   2309 	{
   2310 	  /* Record the relocated start and end address of the dynamic linker
   2311 	     text and plt section for svr4_in_dynsym_resolve_code.  */
   2312 	  bfd *tmp_bfd;
   2313 	  CORE_ADDR load_addr;
   2314 
   2315 	  tmp_bfd = os->objfile->obfd.get ();
   2316 	  load_addr = os->objfile->text_section_offset ();
   2317 
   2318 	  interp_sect = bfd_get_section_by_name (tmp_bfd, ".text");
   2319 	  if (interp_sect)
   2320 	    {
   2321 	      info->interp_text_sect_low
   2322 		= bfd_section_vma (interp_sect) + load_addr;
   2323 	      info->interp_text_sect_high
   2324 		= info->interp_text_sect_low + bfd_section_size (interp_sect);
   2325 	    }
   2326 	  interp_sect = bfd_get_section_by_name (tmp_bfd, ".plt");
   2327 	  if (interp_sect)
   2328 	    {
   2329 	      info->interp_plt_sect_low
   2330 		= bfd_section_vma (interp_sect) + load_addr;
   2331 	      info->interp_plt_sect_high
   2332 		= info->interp_plt_sect_low + bfd_section_size (interp_sect);
   2333 	    }
   2334 
   2335 	  svr4_create_solib_event_breakpoints
   2336 	    (info, current_inferior ()->arch (), sym_addr);
   2337 	  return 1;
   2338 	}
   2339     }
   2340 
   2341   /* Find the program interpreter; if not found, warn the user and drop
   2342      into the old breakpoint at symbol code.  */
   2343   std::optional<gdb::byte_vector> interp_name_holder
   2344     = find_program_interpreter ();
   2345   if (interp_name_holder)
   2346     {
   2347       const char *interp_name = (const char *) interp_name_holder->data ();
   2348       CORE_ADDR load_addr = 0;
   2349       int load_addr_found = 0;
   2350       int loader_found_in_list = 0;
   2351       target_ops_up tmp_bfd_target;
   2352 
   2353       sym_addr = 0;
   2354 
   2355       /* Now we need to figure out where the dynamic linker was
   2356 	 loaded so that we can load its symbols and place a breakpoint
   2357 	 in the dynamic linker itself.
   2358 
   2359 	 This address is stored on the stack.  However, I've been unable
   2360 	 to find any magic formula to find it for Solaris (appears to
   2361 	 be trivial on GNU/Linux).  Therefore, we have to try an alternate
   2362 	 mechanism to find the dynamic linker's base address.  */
   2363 
   2364       gdb_bfd_ref_ptr tmp_bfd;
   2365       try
   2366 	{
   2367 	  tmp_bfd = solib_bfd_open (interp_name);
   2368 	}
   2369       catch (const gdb_exception &ex)
   2370 	{
   2371 	}
   2372 
   2373       if (tmp_bfd == NULL)
   2374 	goto bkpt_at_symbol;
   2375 
   2376       /* Now convert the TMP_BFD into a target.  That way target, as
   2377 	 well as BFD operations can be used.  */
   2378       tmp_bfd_target = target_bfd_reopen (tmp_bfd);
   2379 
   2380       /* On a running target, we can get the dynamic linker's base
   2381 	 address from the shared library table.  */
   2382       for (const solib &so : current_program_space->solibs ())
   2383 	{
   2384 	  if (svr4_same_1 (interp_name, so.so_original_name.c_str ()))
   2385 	    {
   2386 	      load_addr_found = 1;
   2387 	      loader_found_in_list = 1;
   2388 	      load_addr = lm_addr_check (so, tmp_bfd.get ());
   2389 	      break;
   2390 	    }
   2391 	}
   2392 
   2393       /* If we were not able to find the base address of the loader
   2394 	 from our so_list, then try using the AT_BASE auxiliary entry.  */
   2395       if (!load_addr_found)
   2396 	if (target_auxv_search (AT_BASE, &load_addr) > 0)
   2397 	  {
   2398 	    int addr_bit = gdbarch_addr_bit (current_inferior ()->arch ());
   2399 
   2400 	    /* Ensure LOAD_ADDR has proper sign in its possible upper bits so
   2401 	       that `+ load_addr' will overflow CORE_ADDR width not creating
   2402 	       invalid addresses like 0x101234567 for 32bit inferiors on 64bit
   2403 	       GDB.  */
   2404 
   2405 	    if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
   2406 	      {
   2407 		CORE_ADDR space_size = (CORE_ADDR) 1 << addr_bit;
   2408 		CORE_ADDR tmp_entry_point
   2409 		  = exec_entry_point (tmp_bfd.get (), tmp_bfd_target.get ());
   2410 
   2411 		gdb_assert (load_addr < space_size);
   2412 
   2413 		/* TMP_ENTRY_POINT exceeding SPACE_SIZE would be for prelinked
   2414 		   64bit ld.so with 32bit executable, it should not happen.  */
   2415 
   2416 		if (tmp_entry_point < space_size
   2417 		    && tmp_entry_point + load_addr >= space_size)
   2418 		  load_addr -= space_size;
   2419 	      }
   2420 
   2421 	    load_addr_found = 1;
   2422 	  }
   2423 
   2424       /* Otherwise we find the dynamic linker's base address by examining
   2425 	 the current pc (which should point at the entry point for the
   2426 	 dynamic linker) and subtracting the offset of the entry point.
   2427 
   2428 	 This is more fragile than the previous approaches, but is a good
   2429 	 fallback method because it has actually been working well in
   2430 	 most cases.  */
   2431       if (!load_addr_found)
   2432 	{
   2433 	  regcache *regcache
   2434 	    = get_thread_arch_regcache (current_inferior (), inferior_ptid,
   2435 					current_inferior ()->arch ());
   2436 
   2437 	  load_addr = (regcache_read_pc (regcache)
   2438 		       - exec_entry_point (tmp_bfd.get (),
   2439 					   tmp_bfd_target.get ()));
   2440 	}
   2441 
   2442       if (!loader_found_in_list)
   2443 	{
   2444 	  info->debug_loader_name = xstrdup (interp_name);
   2445 	  info->debug_loader_offset_p = 1;
   2446 	  info->debug_loader_offset = load_addr;
   2447 	  solib_add (NULL, from_tty, auto_solib_add);
   2448 	}
   2449 
   2450       /* Record the relocated start and end address of the dynamic linker
   2451 	 text and plt section for svr4_in_dynsym_resolve_code.  */
   2452       interp_sect = bfd_get_section_by_name (tmp_bfd.get (), ".text");
   2453       if (interp_sect)
   2454 	{
   2455 	  info->interp_text_sect_low
   2456 	    = bfd_section_vma (interp_sect) + load_addr;
   2457 	  info->interp_text_sect_high
   2458 	    = info->interp_text_sect_low + bfd_section_size (interp_sect);
   2459 	}
   2460       interp_sect = bfd_get_section_by_name (tmp_bfd.get (), ".plt");
   2461       if (interp_sect)
   2462 	{
   2463 	  info->interp_plt_sect_low
   2464 	    = bfd_section_vma (interp_sect) + load_addr;
   2465 	  info->interp_plt_sect_high
   2466 	    = info->interp_plt_sect_low + bfd_section_size (interp_sect);
   2467 	}
   2468 
   2469       /* Now try to set a breakpoint in the dynamic linker.  */
   2470       for (bkpt_namep = solib_break_names; *bkpt_namep != NULL; bkpt_namep++)
   2471 	{
   2472 	  sym_addr
   2473 	    = (gdb_bfd_lookup_symbol
   2474 	       (tmp_bfd.get (),
   2475 		[=] (const asymbol *sym)
   2476 		{
   2477 		  return (strcmp (sym->name, *bkpt_namep) == 0
   2478 			  && ((sym->section->flags & (SEC_CODE | SEC_DATA))
   2479 			      != 0));
   2480 		}));
   2481 	  if (sym_addr != 0)
   2482 	    break;
   2483 	}
   2484 
   2485       if (sym_addr != 0)
   2486 	/* Convert 'sym_addr' from a function pointer to an address.
   2487 	   Because we pass tmp_bfd_target instead of the current
   2488 	   target, this will always produce an unrelocated value.  */
   2489 	sym_addr = gdbarch_convert_from_func_ptr_addr
   2490 		     (current_inferior ()->arch (), sym_addr,
   2491 		      tmp_bfd_target.get ());
   2492 
   2493       if (sym_addr != 0)
   2494 	{
   2495 	  svr4_create_solib_event_breakpoints (info,
   2496 					       current_inferior ()->arch (),
   2497 					       load_addr + sym_addr);
   2498 	  return 1;
   2499 	}
   2500 
   2501       /* For whatever reason we couldn't set a breakpoint in the dynamic
   2502 	 linker.  Warn and drop into the old code.  */
   2503     bkpt_at_symbol:
   2504       warning (_("Unable to find dynamic linker breakpoint function.\n"
   2505 	       "GDB will be unable to debug shared library initializers\n"
   2506 	       "and track explicitly loaded dynamic code."));
   2507     }
   2508 
   2509   /* Scan through the lists of symbols, trying to look up the symbol and
   2510      set a breakpoint there.  Terminate loop when we/if we succeed.  */
   2511 
   2512   objfile *objf = current_program_space->symfile_object_file;
   2513   for (bkpt_namep = solib_break_names; *bkpt_namep != NULL; bkpt_namep++)
   2514     {
   2515       bound_minimal_symbol msymbol
   2516 	= lookup_minimal_symbol (current_program_space, *bkpt_namep, objf);
   2517       if ((msymbol.minsym != NULL)
   2518 	  && (msymbol.value_address () != 0))
   2519 	{
   2520 	  sym_addr = msymbol.value_address ();
   2521 	  sym_addr = gdbarch_convert_from_func_ptr_addr
   2522 	    (current_inferior ()->arch (), sym_addr,
   2523 	     current_inferior ()->top_target ());
   2524 	  svr4_create_solib_event_breakpoints (info,
   2525 					       current_inferior ()->arch (),
   2526 					       sym_addr);
   2527 	  return 1;
   2528 	}
   2529     }
   2530 
   2531   if (interp_name_holder && !current_inferior ()->attach_flag)
   2532     {
   2533       for (bkpt_namep = bkpt_names; *bkpt_namep != NULL; bkpt_namep++)
   2534 	{
   2535 	  bound_minimal_symbol msymbol
   2536 	    = lookup_minimal_symbol (current_program_space, *bkpt_namep, objf);
   2537 	  if ((msymbol.minsym != NULL)
   2538 	      && (msymbol.value_address () != 0))
   2539 	    {
   2540 	      sym_addr = msymbol.value_address ();
   2541 	      sym_addr = gdbarch_convert_from_func_ptr_addr
   2542 		(current_inferior ()->arch (), sym_addr,
   2543 		 current_inferior ()->top_target ());
   2544 	      svr4_create_solib_event_breakpoints
   2545 		(info, current_inferior ()->arch (), sym_addr);
   2546 	      return 1;
   2547 	    }
   2548 	}
   2549     }
   2550   return 0;
   2551 }
   2552 
   2553 /* Read the ELF program headers from ABFD.  */
   2554 
   2555 static std::optional<gdb::byte_vector>
   2556 read_program_headers_from_bfd (bfd *abfd)
   2557 {
   2558   Elf_Internal_Ehdr *ehdr = elf_elfheader (abfd);
   2559   int phdrs_size = ehdr->e_phnum * ehdr->e_phentsize;
   2560   if (phdrs_size == 0)
   2561     return {};
   2562 
   2563   gdb::byte_vector buf (phdrs_size);
   2564   if (bfd_seek (abfd, ehdr->e_phoff, SEEK_SET) != 0
   2565       || bfd_read (buf.data (), phdrs_size, abfd) != phdrs_size)
   2566     return {};
   2567 
   2568   return buf;
   2569 }
   2570 
   2571 /* Return 1 and fill *DISPLACEMENTP with detected PIE offset of inferior
   2572    exec_bfd.  Otherwise return 0.
   2573 
   2574    We relocate all of the sections by the same amount.  This
   2575    behavior is mandated by recent editions of the System V ABI.
   2576    According to the System V Application Binary Interface,
   2577    Edition 4.1, page 5-5:
   2578 
   2579      ...  Though the system chooses virtual addresses for
   2580      individual processes, it maintains the segments' relative
   2581      positions.  Because position-independent code uses relative
   2582      addressing between segments, the difference between
   2583      virtual addresses in memory must match the difference
   2584      between virtual addresses in the file.  The difference
   2585      between the virtual address of any segment in memory and
   2586      the corresponding virtual address in the file is thus a
   2587      single constant value for any one executable or shared
   2588      object in a given process.  This difference is the base
   2589      address.  One use of the base address is to relocate the
   2590      memory image of the program during dynamic linking.
   2591 
   2592    The same language also appears in Edition 4.0 of the System V
   2593    ABI and is left unspecified in some of the earlier editions.
   2594 
   2595    Decide if the objfile needs to be relocated.  As indicated above, we will
   2596    only be here when execution is stopped.  But during attachment PC can be at
   2597    arbitrary address therefore regcache_read_pc can be misleading (contrary to
   2598    the auxv AT_ENTRY value).  Moreover for executable with interpreter section
   2599    regcache_read_pc would point to the interpreter and not the main executable.
   2600 
   2601    So, to summarize, relocations are necessary when the start address obtained
   2602    from the executable is different from the address in auxv AT_ENTRY entry.
   2603 
   2604    [ The astute reader will note that we also test to make sure that
   2605      the executable in question has the DYNAMIC flag set.  It is my
   2606      opinion that this test is unnecessary (undesirable even).  It
   2607      was added to avoid inadvertent relocation of an executable
   2608      whose e_type member in the ELF header is not ET_DYN.  There may
   2609      be a time in the future when it is desirable to do relocations
   2610      on other types of files as well in which case this condition
   2611      should either be removed or modified to accommodate the new file
   2612      type.  - Kevin, Nov 2000. ]  */
   2613 
   2614 static int
   2615 svr4_exec_displacement (CORE_ADDR *displacementp)
   2616 {
   2617   /* ENTRY_POINT is a possible function descriptor - before
   2618      a call to gdbarch_convert_from_func_ptr_addr.  */
   2619   CORE_ADDR entry_point, exec_displacement;
   2620 
   2621   if (current_program_space->exec_bfd () == NULL)
   2622     return 0;
   2623 
   2624   /* Therefore for ELF it is ET_EXEC and not ET_DYN.  Both shared libraries
   2625      being executed themselves and PIE (Position Independent Executable)
   2626      executables are ET_DYN.  */
   2627 
   2628   if ((bfd_get_file_flags (current_program_space->exec_bfd ()) & DYNAMIC) == 0)
   2629     return 0;
   2630 
   2631   if (target_auxv_search (AT_ENTRY, &entry_point) <= 0)
   2632     return 0;
   2633 
   2634   exec_displacement
   2635     = entry_point - bfd_get_start_address (current_program_space->exec_bfd ());
   2636 
   2637   /* Verify the EXEC_DISPLACEMENT candidate complies with the required page
   2638      alignment.  It is cheaper than the program headers comparison below.  */
   2639 
   2640   if (bfd_get_flavour (current_program_space->exec_bfd ())
   2641       == bfd_target_elf_flavour)
   2642     {
   2643       const struct elf_backend_data *elf
   2644 	= get_elf_backend_data (current_program_space->exec_bfd ());
   2645 
   2646       /* p_align of PT_LOAD segments does not specify any alignment but
   2647 	 only congruency of addresses:
   2648 	   p_offset % p_align == p_vaddr % p_align
   2649 	 Kernel is free to load the executable with lower alignment.  */
   2650 
   2651       if ((exec_displacement & (elf->minpagesize - 1)) != 0)
   2652 	return 0;
   2653     }
   2654 
   2655   /* Verify that the auxiliary vector describes the same file as exec_bfd, by
   2656      comparing their program headers.  If the program headers in the auxiliary
   2657      vector do not match the program headers in the executable, then we are
   2658      looking at a different file than the one used by the kernel - for
   2659      instance, "gdb program" connected to "gdbserver :PORT ld.so program".  */
   2660 
   2661   if (bfd_get_flavour (current_program_space->exec_bfd ())
   2662       == bfd_target_elf_flavour)
   2663     {
   2664       /* Be optimistic and return 0 only if GDB was able to verify the headers
   2665 	 really do not match.  */
   2666       int arch_size;
   2667 
   2668       std::optional<gdb::byte_vector> phdrs_target
   2669 	= read_program_header (-1, &arch_size, NULL);
   2670       std::optional<gdb::byte_vector> phdrs_binary
   2671 	= read_program_headers_from_bfd (current_program_space->exec_bfd ());
   2672       if (phdrs_target && phdrs_binary)
   2673 	{
   2674 	  bfd_endian byte_order = gdbarch_byte_order (current_inferior ()->arch ());
   2675 
   2676 	  /* We are dealing with three different addresses.  EXEC_BFD
   2677 	     represents current address in on-disk file.  target memory content
   2678 	     may be different from EXEC_BFD as the file may have been prelinked
   2679 	     to a different address after the executable has been loaded.
   2680 	     Moreover the address of placement in target memory can be
   2681 	     different from what the program headers in target memory say -
   2682 	     this is the goal of PIE.
   2683 
   2684 	     Detected DISPLACEMENT covers both the offsets of PIE placement and
   2685 	     possible new prelink performed after start of the program.  Here
   2686 	     relocate BUF and BUF2 just by the EXEC_BFD vs. target memory
   2687 	     content offset for the verification purpose.  */
   2688 
   2689 	  if (phdrs_target->size () != phdrs_binary->size ()
   2690 	      || bfd_get_arch_size (current_program_space->exec_bfd ()) != arch_size)
   2691 	    return 0;
   2692 	  else if (arch_size == 32
   2693 		   && phdrs_target->size () >= sizeof (Elf32_External_Phdr)
   2694 		   && phdrs_target->size () % sizeof (Elf32_External_Phdr) == 0)
   2695 	    {
   2696 	      Elf_Internal_Ehdr *ehdr2
   2697 		= elf_tdata (current_program_space->exec_bfd ())->elf_header;
   2698 	      Elf_Internal_Phdr *phdr2
   2699 		= elf_tdata (current_program_space->exec_bfd ())->phdr;
   2700 	      CORE_ADDR displacement = 0;
   2701 	      int i;
   2702 
   2703 	      /* DISPLACEMENT could be found more easily by the difference of
   2704 		 ehdr2->e_entry.  But we haven't read the ehdr yet, and we
   2705 		 already have enough information to compute that displacement
   2706 		 with what we've read.  */
   2707 
   2708 	      for (i = 0; i < ehdr2->e_phnum; i++)
   2709 		if (phdr2[i].p_type == PT_LOAD)
   2710 		  {
   2711 		    Elf32_External_Phdr *phdrp;
   2712 		    gdb_byte *buf_vaddr_p, *buf_paddr_p;
   2713 		    CORE_ADDR vaddr, paddr;
   2714 		    CORE_ADDR displacement_vaddr = 0;
   2715 		    CORE_ADDR displacement_paddr = 0;
   2716 
   2717 		    phdrp = &((Elf32_External_Phdr *) phdrs_target->data ())[i];
   2718 		    buf_vaddr_p = (gdb_byte *) &phdrp->p_vaddr;
   2719 		    buf_paddr_p = (gdb_byte *) &phdrp->p_paddr;
   2720 
   2721 		    vaddr = extract_unsigned_integer (buf_vaddr_p, 4,
   2722 						      byte_order);
   2723 		    displacement_vaddr = vaddr - phdr2[i].p_vaddr;
   2724 
   2725 		    paddr = extract_unsigned_integer (buf_paddr_p, 4,
   2726 						      byte_order);
   2727 		    displacement_paddr = paddr - phdr2[i].p_paddr;
   2728 
   2729 		    if (displacement_vaddr == displacement_paddr)
   2730 		      displacement = displacement_vaddr;
   2731 
   2732 		    break;
   2733 		  }
   2734 
   2735 	      /* Now compare program headers from the target and the binary
   2736 		 with optional DISPLACEMENT.  */
   2737 
   2738 	      for (i = 0;
   2739 		   i < phdrs_target->size () / sizeof (Elf32_External_Phdr);
   2740 		   i++)
   2741 		{
   2742 		  Elf32_External_Phdr *phdrp;
   2743 		  Elf32_External_Phdr *phdr2p;
   2744 		  gdb_byte *buf_vaddr_p, *buf_paddr_p;
   2745 		  CORE_ADDR vaddr, paddr;
   2746 		  asection *plt2_asect;
   2747 
   2748 		  phdrp = &((Elf32_External_Phdr *) phdrs_target->data ())[i];
   2749 		  buf_vaddr_p = (gdb_byte *) &phdrp->p_vaddr;
   2750 		  buf_paddr_p = (gdb_byte *) &phdrp->p_paddr;
   2751 		  phdr2p = &((Elf32_External_Phdr *) phdrs_binary->data ())[i];
   2752 
   2753 		  /* PT_GNU_STACK is an exception by being never relocated by
   2754 		     prelink as its addresses are always zero.  */
   2755 
   2756 		  if (memcmp (phdrp, phdr2p, sizeof (*phdrp)) == 0)
   2757 		    continue;
   2758 
   2759 		  /* Check also other adjustment combinations - PR 11786.  */
   2760 
   2761 		  vaddr = extract_unsigned_integer (buf_vaddr_p, 4,
   2762 						    byte_order);
   2763 		  vaddr -= displacement;
   2764 		  store_unsigned_integer (buf_vaddr_p, 4, byte_order, vaddr);
   2765 
   2766 		  paddr = extract_unsigned_integer (buf_paddr_p, 4,
   2767 						    byte_order);
   2768 		  paddr -= displacement;
   2769 		  store_unsigned_integer (buf_paddr_p, 4, byte_order, paddr);
   2770 
   2771 		  if (memcmp (phdrp, phdr2p, sizeof (*phdrp)) == 0)
   2772 		    continue;
   2773 
   2774 		  /* Strip modifies the flags and alignment of PT_GNU_RELRO.
   2775 		     CentOS-5 has problems with filesz, memsz as well.
   2776 		     Strip also modifies memsz of PT_TLS.
   2777 		     See PR 11786.  */
   2778 		  if (phdr2[i].p_type == PT_GNU_RELRO
   2779 		      || phdr2[i].p_type == PT_TLS)
   2780 		    {
   2781 		      Elf32_External_Phdr tmp_phdr = *phdrp;
   2782 		      Elf32_External_Phdr tmp_phdr2 = *phdr2p;
   2783 
   2784 		      memset (tmp_phdr.p_filesz, 0, 4);
   2785 		      memset (tmp_phdr.p_memsz, 0, 4);
   2786 		      memset (tmp_phdr.p_flags, 0, 4);
   2787 		      memset (tmp_phdr.p_align, 0, 4);
   2788 		      memset (tmp_phdr2.p_filesz, 0, 4);
   2789 		      memset (tmp_phdr2.p_memsz, 0, 4);
   2790 		      memset (tmp_phdr2.p_flags, 0, 4);
   2791 		      memset (tmp_phdr2.p_align, 0, 4);
   2792 
   2793 		      if (memcmp (&tmp_phdr, &tmp_phdr2, sizeof (tmp_phdr))
   2794 			  == 0)
   2795 			continue;
   2796 		    }
   2797 
   2798 		  /* prelink can convert .plt SHT_NOBITS to SHT_PROGBITS.  */
   2799 		  bfd *exec_bfd = current_program_space->exec_bfd ();
   2800 		  plt2_asect = bfd_get_section_by_name (exec_bfd, ".plt");
   2801 		  if (plt2_asect)
   2802 		    {
   2803 		      int content2;
   2804 		      gdb_byte *buf_filesz_p = (gdb_byte *) &phdrp->p_filesz;
   2805 		      CORE_ADDR filesz;
   2806 
   2807 		      content2 = (bfd_section_flags (plt2_asect)
   2808 				  & SEC_HAS_CONTENTS) != 0;
   2809 
   2810 		      filesz = extract_unsigned_integer (buf_filesz_p, 4,
   2811 							 byte_order);
   2812 
   2813 		      /* PLT2_ASECT is from on-disk file (exec_bfd) while
   2814 			 FILESZ is from the in-memory image.  */
   2815 		      if (content2)
   2816 			filesz += bfd_section_size (plt2_asect);
   2817 		      else
   2818 			filesz -= bfd_section_size (plt2_asect);
   2819 
   2820 		      store_unsigned_integer (buf_filesz_p, 4, byte_order,
   2821 					      filesz);
   2822 
   2823 		      if (memcmp (phdrp, phdr2p, sizeof (*phdrp)) == 0)
   2824 			continue;
   2825 		    }
   2826 
   2827 		  return 0;
   2828 		}
   2829 	    }
   2830 	  else if (arch_size == 64
   2831 		   && phdrs_target->size () >= sizeof (Elf64_External_Phdr)
   2832 		   && phdrs_target->size () % sizeof (Elf64_External_Phdr) == 0)
   2833 	    {
   2834 	      Elf_Internal_Ehdr *ehdr2
   2835 		= elf_tdata (current_program_space->exec_bfd ())->elf_header;
   2836 	      Elf_Internal_Phdr *phdr2
   2837 		= elf_tdata (current_program_space->exec_bfd ())->phdr;
   2838 	      CORE_ADDR displacement = 0;
   2839 	      int i;
   2840 
   2841 	      /* DISPLACEMENT could be found more easily by the difference of
   2842 		 ehdr2->e_entry.  But we haven't read the ehdr yet, and we
   2843 		 already have enough information to compute that displacement
   2844 		 with what we've read.  */
   2845 
   2846 	      for (i = 0; i < ehdr2->e_phnum; i++)
   2847 		if (phdr2[i].p_type == PT_LOAD)
   2848 		  {
   2849 		    Elf64_External_Phdr *phdrp;
   2850 		    gdb_byte *buf_vaddr_p, *buf_paddr_p;
   2851 		    CORE_ADDR vaddr, paddr;
   2852 		    CORE_ADDR displacement_vaddr = 0;
   2853 		    CORE_ADDR displacement_paddr = 0;
   2854 
   2855 		    phdrp = &((Elf64_External_Phdr *) phdrs_target->data ())[i];
   2856 		    buf_vaddr_p = (gdb_byte *) &phdrp->p_vaddr;
   2857 		    buf_paddr_p = (gdb_byte *) &phdrp->p_paddr;
   2858 
   2859 		    vaddr = extract_unsigned_integer (buf_vaddr_p, 8,
   2860 						      byte_order);
   2861 		    displacement_vaddr = vaddr - phdr2[i].p_vaddr;
   2862 
   2863 		    paddr = extract_unsigned_integer (buf_paddr_p, 8,
   2864 						      byte_order);
   2865 		    displacement_paddr = paddr - phdr2[i].p_paddr;
   2866 
   2867 		    if (displacement_vaddr == displacement_paddr)
   2868 		      displacement = displacement_vaddr;
   2869 
   2870 		    break;
   2871 		  }
   2872 
   2873 	      /* Now compare BUF and BUF2 with optional DISPLACEMENT.  */
   2874 
   2875 	      for (i = 0;
   2876 		   i < phdrs_target->size () / sizeof (Elf64_External_Phdr);
   2877 		   i++)
   2878 		{
   2879 		  Elf64_External_Phdr *phdrp;
   2880 		  Elf64_External_Phdr *phdr2p;
   2881 		  gdb_byte *buf_vaddr_p, *buf_paddr_p;
   2882 		  CORE_ADDR vaddr, paddr;
   2883 		  asection *plt2_asect;
   2884 
   2885 		  phdrp = &((Elf64_External_Phdr *) phdrs_target->data ())[i];
   2886 		  buf_vaddr_p = (gdb_byte *) &phdrp->p_vaddr;
   2887 		  buf_paddr_p = (gdb_byte *) &phdrp->p_paddr;
   2888 		  phdr2p = &((Elf64_External_Phdr *) phdrs_binary->data ())[i];
   2889 
   2890 		  /* PT_GNU_STACK is an exception by being never relocated by
   2891 		     prelink as its addresses are always zero.  */
   2892 
   2893 		  if (memcmp (phdrp, phdr2p, sizeof (*phdrp)) == 0)
   2894 		    continue;
   2895 
   2896 		  /* Check also other adjustment combinations - PR 11786.  */
   2897 
   2898 		  vaddr = extract_unsigned_integer (buf_vaddr_p, 8,
   2899 						    byte_order);
   2900 		  vaddr -= displacement;
   2901 		  store_unsigned_integer (buf_vaddr_p, 8, byte_order, vaddr);
   2902 
   2903 		  paddr = extract_unsigned_integer (buf_paddr_p, 8,
   2904 						    byte_order);
   2905 		  paddr -= displacement;
   2906 		  store_unsigned_integer (buf_paddr_p, 8, byte_order, paddr);
   2907 
   2908 		  if (memcmp (phdrp, phdr2p, sizeof (*phdrp)) == 0)
   2909 		    continue;
   2910 
   2911 		  /* Strip modifies the flags and alignment of PT_GNU_RELRO.
   2912 		     CentOS-5 has problems with filesz, memsz as well.
   2913 		     Strip also modifies memsz of PT_TLS.
   2914 		     See PR 11786.  */
   2915 		  if (phdr2[i].p_type == PT_GNU_RELRO
   2916 		      || phdr2[i].p_type == PT_TLS)
   2917 		    {
   2918 		      Elf64_External_Phdr tmp_phdr = *phdrp;
   2919 		      Elf64_External_Phdr tmp_phdr2 = *phdr2p;
   2920 
   2921 		      memset (tmp_phdr.p_filesz, 0, 8);
   2922 		      memset (tmp_phdr.p_memsz, 0, 8);
   2923 		      memset (tmp_phdr.p_flags, 0, 4);
   2924 		      memset (tmp_phdr.p_align, 0, 8);
   2925 		      memset (tmp_phdr2.p_filesz, 0, 8);
   2926 		      memset (tmp_phdr2.p_memsz, 0, 8);
   2927 		      memset (tmp_phdr2.p_flags, 0, 4);
   2928 		      memset (tmp_phdr2.p_align, 0, 8);
   2929 
   2930 		      if (memcmp (&tmp_phdr, &tmp_phdr2, sizeof (tmp_phdr))
   2931 			  == 0)
   2932 			continue;
   2933 		    }
   2934 
   2935 		  /* prelink can convert .plt SHT_NOBITS to SHT_PROGBITS.  */
   2936 		  plt2_asect
   2937 		    = bfd_get_section_by_name (current_program_space->exec_bfd (),
   2938 					       ".plt");
   2939 		  if (plt2_asect)
   2940 		    {
   2941 		      int content2;
   2942 		      gdb_byte *buf_filesz_p = (gdb_byte *) &phdrp->p_filesz;
   2943 		      CORE_ADDR filesz;
   2944 
   2945 		      content2 = (bfd_section_flags (plt2_asect)
   2946 				  & SEC_HAS_CONTENTS) != 0;
   2947 
   2948 		      filesz = extract_unsigned_integer (buf_filesz_p, 8,
   2949 							 byte_order);
   2950 
   2951 		      /* PLT2_ASECT is from on-disk file (current
   2952 			 exec_bfd) while FILESZ is from the in-memory
   2953 			 image.  */
   2954 		      if (content2)
   2955 			filesz += bfd_section_size (plt2_asect);
   2956 		      else
   2957 			filesz -= bfd_section_size (plt2_asect);
   2958 
   2959 		      store_unsigned_integer (buf_filesz_p, 8, byte_order,
   2960 					      filesz);
   2961 
   2962 		      if (memcmp (phdrp, phdr2p, sizeof (*phdrp)) == 0)
   2963 			continue;
   2964 		    }
   2965 
   2966 		  return 0;
   2967 		}
   2968 	    }
   2969 	  else
   2970 	    return 0;
   2971 	}
   2972     }
   2973 
   2974   if (info_verbose)
   2975     {
   2976       /* It can be printed repeatedly as there is no easy way to check
   2977 	 the executable symbols/file has been already relocated to
   2978 	 displacement.  */
   2979 
   2980       gdb_printf (_("Using PIE (Position Independent Executable) "
   2981 		    "displacement %s for \"%s\".\n"),
   2982 		  paddress (current_inferior ()->arch (), exec_displacement),
   2983 		  bfd_get_filename (current_program_space->exec_bfd ()));
   2984     }
   2985 
   2986   *displacementp = exec_displacement;
   2987   return 1;
   2988 }
   2989 
   2990 /* Relocate the main executable.  This function should be called upon
   2991    stopping the inferior process at the entry point to the program.
   2992    The entry point from BFD is compared to the AT_ENTRY of AUXV and if they are
   2993    different, the main executable is relocated by the proper amount.  */
   2994 
   2995 static void
   2996 svr4_relocate_main_executable (void)
   2997 {
   2998   CORE_ADDR displacement;
   2999 
   3000   /* If we are re-running this executable, SYMFILE_OBJFILE->SECTION_OFFSETS
   3001      probably contains the offsets computed using the PIE displacement
   3002      from the previous run, which of course are irrelevant for this run.
   3003      So we need to determine the new PIE displacement and recompute the
   3004      section offsets accordingly, even if SYMFILE_OBJFILE->SECTION_OFFSETS
   3005      already contains pre-computed offsets.
   3006 
   3007      If we cannot compute the PIE displacement, either:
   3008 
   3009        - The executable is not PIE.
   3010 
   3011        - SYMFILE_OBJFILE does not match the executable started in the target.
   3012 	 This can happen for main executable symbols loaded at the host while
   3013 	 `ld.so --ld-args main-executable' is loaded in the target.
   3014 
   3015      Then we leave the section offsets untouched and use them as is for
   3016      this run.  Either:
   3017 
   3018        - These section offsets were properly reset earlier, and thus
   3019 	 already contain the correct values.  This can happen for instance
   3020 	 when reconnecting via the remote protocol to a target that supports
   3021 	 the `qOffsets' packet.
   3022 
   3023        - The section offsets were not reset earlier, and the best we can
   3024 	 hope is that the old offsets are still applicable to the new run.  */
   3025 
   3026   if (! svr4_exec_displacement (&displacement))
   3027     return;
   3028 
   3029   /* Even DISPLACEMENT 0 is a valid new difference of in-memory vs. in-file
   3030      addresses.  */
   3031 
   3032   objfile *objf = current_program_space->symfile_object_file;
   3033   if (objf)
   3034     {
   3035       section_offsets new_offsets (objf->section_offsets.size (),
   3036 				   displacement);
   3037       objfile_relocate (objf, new_offsets);
   3038     }
   3039   else if (current_program_space->exec_bfd ())
   3040     {
   3041       asection *asect;
   3042 
   3043       bfd *exec_bfd = current_program_space->exec_bfd ();
   3044       for (asect = exec_bfd->sections; asect != NULL; asect = asect->next)
   3045 	exec_set_section_address (bfd_get_filename (exec_bfd), asect->index,
   3046 				  bfd_section_vma (asect) + displacement);
   3047     }
   3048 }
   3049 
   3050 /* Implement the "create_inferior_hook" target_solib_ops method.
   3051 
   3052    For SVR4 executables, this first instruction is either the first
   3053    instruction in the dynamic linker (for dynamically linked
   3054    executables) or the instruction at "start" for statically linked
   3055    executables.  For dynamically linked executables, the system
   3056    first exec's /lib/libc.so.N, which contains the dynamic linker,
   3057    and starts it running.  The dynamic linker maps in any needed
   3058    shared libraries, maps in the actual user executable, and then
   3059    jumps to "start" in the user executable.
   3060 
   3061    We can arrange to cooperate with the dynamic linker to discover the
   3062    names of shared libraries that are dynamically linked, and the base
   3063    addresses to which they are linked.
   3064 
   3065    This function is responsible for discovering those names and
   3066    addresses, and saving sufficient information about them to allow
   3067    their symbols to be read at a later time.  */
   3068 
   3069 static void
   3070 svr4_solib_create_inferior_hook (int from_tty)
   3071 {
   3072   struct svr4_info *info;
   3073 
   3074   info = get_svr4_info (current_program_space);
   3075 
   3076   /* Clear the probes-based interface's state.  */
   3077   free_probes_table (info);
   3078   info->solib_lists.clear ();
   3079 
   3080   /* Relocate the main executable if necessary.  */
   3081   svr4_relocate_main_executable ();
   3082 
   3083   /* No point setting a breakpoint in the dynamic linker if we can't
   3084      hit it (e.g., a core file, or a trace file).  */
   3085   if (!target_has_execution ())
   3086     return;
   3087 
   3088   if (!svr4_have_link_map_offsets ())
   3089     return;
   3090 
   3091   if (!enable_break (info, from_tty))
   3092     return;
   3093 }
   3094 
   3095 static void
   3096 svr4_clear_solib (program_space *pspace)
   3097 {
   3098   svr4_info *info = get_svr4_info (pspace);
   3099   info->debug_base = 0;
   3100   info->debug_loader_offset_p = 0;
   3101   info->debug_loader_offset = 0;
   3102   xfree (info->debug_loader_name);
   3103   info->debug_loader_name = NULL;
   3104 }
   3105 
   3106 /* Clear any bits of ADDR that wouldn't fit in a target-format
   3107    data pointer.  "Data pointer" here refers to whatever sort of
   3108    address the dynamic linker uses to manage its sections.  At the
   3109    moment, we don't support shared libraries on any processors where
   3110    code and data pointers are different sizes.
   3111 
   3112    This isn't really the right solution.  What we really need here is
   3113    a way to do arithmetic on CORE_ADDR values that respects the
   3114    natural pointer/address correspondence.  (For example, on the MIPS,
   3115    converting a 32-bit pointer to a 64-bit CORE_ADDR requires you to
   3116    sign-extend the value.  There, simply truncating the bits above
   3117    gdbarch_ptr_bit, as we do below, is no good.)  This should probably
   3118    be a new gdbarch method or something.  */
   3119 static CORE_ADDR
   3120 svr4_truncate_ptr (CORE_ADDR addr)
   3121 {
   3122   if (gdbarch_ptr_bit (current_inferior ()->arch ()) == sizeof (CORE_ADDR) * 8)
   3123     /* We don't need to truncate anything, and the bit twiddling below
   3124        will fail due to overflow problems.  */
   3125     return addr;
   3126   else
   3127     return addr & (((CORE_ADDR) 1 << gdbarch_ptr_bit (current_inferior ()->arch ())) - 1);
   3128 }
   3129 
   3130 
   3131 static void
   3132 svr4_relocate_section_addresses (solib &so, target_section *sec)
   3133 {
   3134   bfd *abfd = sec->the_bfd_section->owner;
   3135 
   3136   sec->addr = svr4_truncate_ptr (sec->addr + lm_addr_check (so, abfd));
   3137   sec->endaddr = svr4_truncate_ptr (sec->endaddr + lm_addr_check (so, abfd));
   3138 }
   3139 
   3140 
   3142 /* Architecture-specific operations.  */
   3143 
   3144 struct solib_svr4_ops
   3145 {
   3146   /* Return a description of the layout of `struct link_map'.  */
   3147   struct link_map_offsets *(*fetch_link_map_offsets)(void) = nullptr;
   3148 };
   3149 
   3150 /* Per-architecture data key.  */
   3151 static const registry<gdbarch>::key<struct solib_svr4_ops> solib_svr4_data;
   3152 
   3153 /* Return a default for the architecture-specific operations.  */
   3154 
   3155 static struct solib_svr4_ops *
   3156 get_ops (struct gdbarch *gdbarch)
   3157 {
   3158   struct solib_svr4_ops *ops = solib_svr4_data.get (gdbarch);
   3159   if (ops == nullptr)
   3160     ops = solib_svr4_data.emplace (gdbarch);
   3161   return ops;
   3162 }
   3163 
   3164 /* Set the architecture-specific `struct link_map_offsets' fetcher for
   3165    GDBARCH to FLMO.  Also, install SVR4 solib_ops into GDBARCH.  */
   3166 
   3167 void
   3168 set_solib_svr4_fetch_link_map_offsets (struct gdbarch *gdbarch,
   3169 				       struct link_map_offsets *(*flmo) (void))
   3170 {
   3171   struct solib_svr4_ops *ops = get_ops (gdbarch);
   3172 
   3173   ops->fetch_link_map_offsets = flmo;
   3174 
   3175   set_gdbarch_so_ops (gdbarch, &svr4_so_ops);
   3176   set_gdbarch_iterate_over_objfiles_in_search_order
   3177     (gdbarch, svr4_iterate_over_objfiles_in_search_order);
   3178 }
   3179 
   3180 /* Fetch a link_map_offsets structure using the architecture-specific
   3181    `struct link_map_offsets' fetcher.  */
   3182 
   3183 static struct link_map_offsets *
   3184 svr4_fetch_link_map_offsets (void)
   3185 {
   3186   struct solib_svr4_ops *ops = get_ops (current_inferior ()->arch ());
   3187 
   3188   gdb_assert (ops->fetch_link_map_offsets);
   3189   return ops->fetch_link_map_offsets ();
   3190 }
   3191 
   3192 /* Return 1 if a link map offset fetcher has been defined, 0 otherwise.  */
   3193 
   3194 static int
   3195 svr4_have_link_map_offsets (void)
   3196 {
   3197   struct solib_svr4_ops *ops = get_ops (current_inferior ()->arch ());
   3198 
   3199   return (ops->fetch_link_map_offsets != NULL);
   3200 }
   3201 
   3202 
   3204 /* Most OS'es that have SVR4-style ELF dynamic libraries define a
   3205    `struct r_debug' and a `struct link_map' that are binary compatible
   3206    with the original SVR4 implementation.  */
   3207 
   3208 /* Fetch (and possibly build) an appropriate `struct link_map_offsets'
   3209    for an ILP32 SVR4 system.  */
   3210 
   3211 struct link_map_offsets *
   3212 svr4_ilp32_fetch_link_map_offsets (void)
   3213 {
   3214   static struct link_map_offsets lmo;
   3215   static struct link_map_offsets *lmp = NULL;
   3216 
   3217   if (lmp == NULL)
   3218     {
   3219       lmp = &lmo;
   3220 
   3221       lmo.r_version_offset = 0;
   3222       lmo.r_version_size = 4;
   3223       lmo.r_map_offset = 4;
   3224       lmo.r_brk_offset = 8;
   3225       lmo.r_ldsomap_offset = 20;
   3226       lmo.r_next_offset = -1;
   3227 
   3228       /* Everything we need is in the first 20 bytes.  */
   3229       lmo.link_map_size = 20;
   3230       lmo.l_addr_offset = 0;
   3231       lmo.l_name_offset = 4;
   3232       lmo.l_ld_offset = 8;
   3233       lmo.l_next_offset = 12;
   3234       lmo.l_prev_offset = 16;
   3235     }
   3236 
   3237   return lmp;
   3238 }
   3239 
   3240 /* Fetch (and possibly build) an appropriate `struct link_map_offsets'
   3241    for an LP64 SVR4 system.  */
   3242 
   3243 struct link_map_offsets *
   3244 svr4_lp64_fetch_link_map_offsets (void)
   3245 {
   3246   static struct link_map_offsets lmo;
   3247   static struct link_map_offsets *lmp = NULL;
   3248 
   3249   if (lmp == NULL)
   3250     {
   3251       lmp = &lmo;
   3252 
   3253       lmo.r_version_offset = 0;
   3254       lmo.r_version_size = 4;
   3255       lmo.r_map_offset = 8;
   3256       lmo.r_brk_offset = 16;
   3257       lmo.r_ldsomap_offset = 40;
   3258       lmo.r_next_offset = -1;
   3259 
   3260       /* Everything we need is in the first 40 bytes.  */
   3261       lmo.link_map_size = 40;
   3262       lmo.l_addr_offset = 0;
   3263       lmo.l_name_offset = 8;
   3264       lmo.l_ld_offset = 16;
   3265       lmo.l_next_offset = 24;
   3266       lmo.l_prev_offset = 32;
   3267     }
   3268 
   3269   return lmp;
   3270 }
   3271 
   3272 
   3274 /* Return the DSO matching OBJFILE or nullptr if none can be found.  */
   3275 
   3276 static const solib *
   3277 find_solib_for_objfile (struct objfile *objfile)
   3278 {
   3279   if (objfile == nullptr)
   3280     return nullptr;
   3281 
   3282   /* If OBJFILE is a separate debug object file, look for the original
   3283      object file.  */
   3284   if (objfile->separate_debug_objfile_backlink != nullptr)
   3285     objfile = objfile->separate_debug_objfile_backlink;
   3286 
   3287   for (const solib &so : current_program_space->solibs ())
   3288     if (so.objfile == objfile)
   3289       return &so;
   3290 
   3291   return nullptr;
   3292 }
   3293 
   3294 /* Return the address of the r_debug object for the namespace containing
   3295    SOLIB or zero if it cannot be found.  This may happen when symbol files
   3296    are added manually, for example, or with the main executable.
   3297 
   3298    Current callers treat zero as initial namespace so they are doing the
   3299    right thing for the main executable.  */
   3300 
   3301 static CORE_ADDR
   3302 find_debug_base_for_solib (const solib *solib)
   3303 {
   3304   if (solib == nullptr)
   3305     return 0;
   3306 
   3307   svr4_info *info = get_svr4_info (current_program_space);
   3308   gdb_assert (info != nullptr);
   3309 
   3310   auto *lm_info
   3311     = gdb::checked_static_cast<const lm_info_svr4 *> (solib->lm_info.get ());
   3312 
   3313   for (const auto &tuple : info->solib_lists)
   3314     {
   3315       CORE_ADDR debug_base = tuple.first;
   3316       const std::vector<svr4_so> &sos = tuple.second;
   3317 
   3318       for (const svr4_so &so : sos)
   3319 	if (svr4_same (solib->so_original_name.c_str (), so.name.c_str (),
   3320 		       *lm_info, *so.lm_info))
   3321 	  return debug_base;
   3322     }
   3323 
   3324   return 0;
   3325 }
   3326 
   3327 /* Search order for ELF DSOs linked with -Bsymbolic.  Those DSOs have a
   3328    different rule for symbol lookup.  The lookup begins here in the DSO,
   3329    not in the main executable.  When starting from CURRENT_OBJFILE, we
   3330    stay in the same namespace as that file.  Otherwise, we only consider
   3331    the initial namespace.  */
   3332 
   3333 static void
   3334 svr4_iterate_over_objfiles_in_search_order
   3335   (gdbarch *gdbarch, iterate_over_objfiles_in_search_order_cb_ftype cb,
   3336    objfile *current_objfile)
   3337 {
   3338   bool checked_current_objfile = false;
   3339   if (current_objfile != nullptr)
   3340     {
   3341       bfd *abfd;
   3342 
   3343       if (current_objfile->separate_debug_objfile_backlink != nullptr)
   3344 	current_objfile = current_objfile->separate_debug_objfile_backlink;
   3345 
   3346       if (current_objfile == current_program_space->symfile_object_file)
   3347 	abfd = current_program_space->exec_bfd ();
   3348       else
   3349 	abfd = current_objfile->obfd.get ();
   3350 
   3351       if (abfd != nullptr
   3352 	  && gdb_bfd_scan_elf_dyntag (DT_SYMBOLIC, abfd, nullptr, nullptr) == 1)
   3353 	{
   3354 	  checked_current_objfile = true;
   3355 	  if (cb (current_objfile))
   3356 	    return;
   3357 	}
   3358     }
   3359 
   3360   /* The linker namespace to iterate identified by the address of its
   3361      r_debug object, defaulting to the initial namespace.  */
   3362   CORE_ADDR initial = elf_locate_base ();
   3363   const solib *curr_solib = find_solib_for_objfile (current_objfile);
   3364   CORE_ADDR debug_base = find_debug_base_for_solib (curr_solib);
   3365   if (debug_base == 0)
   3366     debug_base = initial;
   3367 
   3368   for (objfile *objfile : current_program_space->objfiles ())
   3369     {
   3370       if (checked_current_objfile && objfile == current_objfile)
   3371 	continue;
   3372 
   3373       /* Try to determine the namespace into which objfile was loaded.
   3374 
   3375 	 If we fail, e.g. for manually added symbol files or for the main
   3376 	 executable, we assume that they were added to the initial
   3377 	 namespace.  */
   3378       const solib *solib = find_solib_for_objfile (objfile);
   3379       CORE_ADDR solib_base = find_debug_base_for_solib (solib);
   3380       if (solib_base == 0)
   3381 	solib_base = initial;
   3382 
   3383       /* Ignore objfiles that were added to a different namespace.  */
   3384       if (solib_base != debug_base)
   3385 	continue;
   3386 
   3387       if (cb (objfile))
   3388 	return;
   3389     }
   3390 }
   3391 
   3392 /* See solib_ops::find_solib_addr in solist.h.  */
   3393 
   3394 static std::optional<CORE_ADDR>
   3395 svr4_find_solib_addr (solib &so)
   3396 {
   3397   auto *li = gdb::checked_static_cast<lm_info_svr4 *> (so.lm_info.get ());
   3398   return li->l_addr_inferior;
   3399 }
   3400 
   3401 const struct solib_ops svr4_so_ops =
   3402 {
   3403   svr4_relocate_section_addresses,
   3404   svr4_clear_so,
   3405   svr4_clear_solib,
   3406   svr4_solib_create_inferior_hook,
   3407   svr4_current_sos,
   3408   open_symbol_file_object,
   3409   svr4_in_dynsym_resolve_code,
   3410   solib_bfd_open,
   3411   svr4_same,
   3412   svr4_keep_data_in_core,
   3413   svr4_update_solib_event_breakpoints,
   3414   svr4_handle_solib_event,
   3415   svr4_find_solib_addr,
   3416 };
   3417 
   3418 void _initialize_svr4_solib ();
   3419 void
   3420 _initialize_svr4_solib ()
   3421 {
   3422   gdb::observers::free_objfile.attach (svr4_free_objfile_observer,
   3423 				       "solib-svr4");
   3424 }
   3425