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