PR symtab/11198:
[platform/upstream/binutils.git] / gdb / solib-svr4.c
1 /* Handle SVR4 shared libraries for GDB, the GNU Debugger.
2
3    Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000,
4    2001, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
5    Free Software Foundation, Inc.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23
24 #include "elf/external.h"
25 #include "elf/common.h"
26 #include "elf/mips.h"
27
28 #include "symtab.h"
29 #include "bfd.h"
30 #include "symfile.h"
31 #include "objfiles.h"
32 #include "gdbcore.h"
33 #include "target.h"
34 #include "inferior.h"
35 #include "regcache.h"
36 #include "gdbthread.h"
37 #include "observer.h"
38
39 #include "gdb_assert.h"
40
41 #include "solist.h"
42 #include "solib.h"
43 #include "solib-svr4.h"
44
45 #include "bfd-target.h"
46 #include "elf-bfd.h"
47 #include "exec.h"
48 #include "auxv.h"
49 #include "exceptions.h"
50
51 static struct link_map_offsets *svr4_fetch_link_map_offsets (void);
52 static int svr4_have_link_map_offsets (void);
53 static void svr4_relocate_main_executable (void);
54
55 /* Link map info to include in an allocated so_list entry */
56
57 struct lm_info
58   {
59     /* Pointer to copy of link map from inferior.  The type is char *
60        rather than void *, so that we may use byte offsets to find the
61        various fields without the need for a cast.  */
62     gdb_byte *lm;
63
64     /* Amount by which addresses in the binary should be relocated to
65        match the inferior.  This could most often be taken directly
66        from lm, but when prelinking is involved and the prelink base
67        address changes, we may need a different offset, we want to
68        warn about the difference and compute it only once.  */
69     CORE_ADDR l_addr;
70
71     /* The target location of lm.  */
72     CORE_ADDR lm_addr;
73   };
74
75 /* On SVR4 systems, a list of symbols in the dynamic linker where
76    GDB can try to place a breakpoint to monitor shared library
77    events.
78
79    If none of these symbols are found, or other errors occur, then
80    SVR4 systems will fall back to using a symbol as the "startup
81    mapping complete" breakpoint address.  */
82
83 static char *solib_break_names[] =
84 {
85   "r_debug_state",
86   "_r_debug_state",
87   "_dl_debug_state",
88   "rtld_db_dlactivity",
89   "_rtld_debug_state",
90
91   NULL
92 };
93
94 static char *bkpt_names[] =
95 {
96   "_start",
97   "__start",
98   "main",
99   NULL
100 };
101
102 static char *main_name_list[] =
103 {
104   "main_$main",
105   NULL
106 };
107
108 /* Return non-zero if GDB_SO_NAME and INFERIOR_SO_NAME represent
109    the same shared library.  */
110
111 static int
112 svr4_same_1 (const char *gdb_so_name, const char *inferior_so_name)
113 {
114   if (strcmp (gdb_so_name, inferior_so_name) == 0)
115     return 1;
116
117   /* On Solaris, when starting inferior we think that dynamic linker is
118      /usr/lib/ld.so.1, but later on, the table of loaded shared libraries 
119      contains /lib/ld.so.1.  Sometimes one file is a link to another, but 
120      sometimes they have identical content, but are not linked to each
121      other.  We don't restrict this check for Solaris, but the chances
122      of running into this situation elsewhere are very low.  */
123   if (strcmp (gdb_so_name, "/usr/lib/ld.so.1") == 0
124       && strcmp (inferior_so_name, "/lib/ld.so.1") == 0)
125     return 1;
126
127   /* Similarly, we observed the same issue with sparc64, but with
128      different locations.  */
129   if (strcmp (gdb_so_name, "/usr/lib/sparcv9/ld.so.1") == 0
130       && strcmp (inferior_so_name, "/lib/sparcv9/ld.so.1") == 0)
131     return 1;
132
133   return 0;
134 }
135
136 static int
137 svr4_same (struct so_list *gdb, struct so_list *inferior)
138 {
139   return (svr4_same_1 (gdb->so_original_name, inferior->so_original_name));
140 }
141
142 /* link map access functions */
143
144 static CORE_ADDR
145 LM_ADDR_FROM_LINK_MAP (struct so_list *so)
146 {
147   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
148   struct type *ptr_type = builtin_type (target_gdbarch)->builtin_data_ptr;
149
150   return extract_typed_address (so->lm_info->lm + lmo->l_addr_offset,
151                                 ptr_type);
152 }
153
154 static int
155 HAS_LM_DYNAMIC_FROM_LINK_MAP (void)
156 {
157   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
158
159   return lmo->l_ld_offset >= 0;
160 }
161
162 static CORE_ADDR
163 LM_DYNAMIC_FROM_LINK_MAP (struct so_list *so)
164 {
165   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
166   struct type *ptr_type = builtin_type (target_gdbarch)->builtin_data_ptr;
167
168   return extract_typed_address (so->lm_info->lm + lmo->l_ld_offset,
169                                 ptr_type);
170 }
171
172 static CORE_ADDR
173 LM_ADDR_CHECK (struct so_list *so, bfd *abfd)
174 {
175   if (so->lm_info->l_addr == (CORE_ADDR)-1)
176     {
177       struct bfd_section *dyninfo_sect;
178       CORE_ADDR l_addr, l_dynaddr, dynaddr, align = 0x1000;
179
180       l_addr = LM_ADDR_FROM_LINK_MAP (so);
181
182       if (! abfd || ! HAS_LM_DYNAMIC_FROM_LINK_MAP ())
183         goto set_addr;
184
185       l_dynaddr = LM_DYNAMIC_FROM_LINK_MAP (so);
186
187       dyninfo_sect = bfd_get_section_by_name (abfd, ".dynamic");
188       if (dyninfo_sect == NULL)
189         goto set_addr;
190
191       dynaddr = bfd_section_vma (abfd, dyninfo_sect);
192
193       if (dynaddr + l_addr != l_dynaddr)
194         {
195           if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
196             {
197               Elf_Internal_Ehdr *ehdr = elf_tdata (abfd)->elf_header;
198               Elf_Internal_Phdr *phdr = elf_tdata (abfd)->phdr;
199               int i;
200
201               align = 1;
202
203               for (i = 0; i < ehdr->e_phnum; i++)
204                 if (phdr[i].p_type == PT_LOAD && phdr[i].p_align > align)
205                   align = phdr[i].p_align;
206             }
207
208           /* Turn it into a mask.  */
209           align--;
210
211           /* If the changes match the alignment requirements, we
212              assume we're using a core file that was generated by the
213              same binary, just prelinked with a different base offset.
214              If it doesn't match, we may have a different binary, the
215              same binary with the dynamic table loaded at an unrelated
216              location, or anything, really.  To avoid regressions,
217              don't adjust the base offset in the latter case, although
218              odds are that, if things really changed, debugging won't
219              quite work.  */
220           if ((l_addr & align) == ((l_dynaddr - dynaddr) & align))
221             {
222               l_addr = l_dynaddr - dynaddr;
223
224               warning (_(".dynamic section for \"%s\" "
225                      "is not at the expected address"), so->so_name);
226               warning (_("difference appears to be caused by prelink, "
227                          "adjusting expectations"));
228             }
229           else
230             warning (_(".dynamic section for \"%s\" "
231                        "is not at the expected address "
232                        "(wrong library or version mismatch?)"), so->so_name);
233         }
234
235     set_addr:
236       so->lm_info->l_addr = l_addr;
237     }
238
239   return so->lm_info->l_addr;
240 }
241
242 static CORE_ADDR
243 LM_NEXT (struct so_list *so)
244 {
245   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
246   struct type *ptr_type = builtin_type (target_gdbarch)->builtin_data_ptr;
247
248   return extract_typed_address (so->lm_info->lm + lmo->l_next_offset,
249                                 ptr_type);
250 }
251
252 static CORE_ADDR
253 LM_NAME (struct so_list *so)
254 {
255   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
256   struct type *ptr_type = builtin_type (target_gdbarch)->builtin_data_ptr;
257
258   return extract_typed_address (so->lm_info->lm + lmo->l_name_offset,
259                                 ptr_type);
260 }
261
262 static int
263 IGNORE_FIRST_LINK_MAP_ENTRY (struct so_list *so)
264 {
265   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
266   struct type *ptr_type = builtin_type (target_gdbarch)->builtin_data_ptr;
267
268   /* Assume that everything is a library if the dynamic loader was loaded
269      late by a static executable.  */
270   if (exec_bfd && bfd_get_section_by_name (exec_bfd, ".dynamic") == NULL)
271     return 0;
272
273   return extract_typed_address (so->lm_info->lm + lmo->l_prev_offset,
274                                 ptr_type) == 0;
275 }
276
277 /* Per pspace SVR4 specific data.  */
278
279 struct svr4_info
280 {
281   CORE_ADDR debug_base; /* Base of dynamic linker structures */
282
283   /* Validity flag for debug_loader_offset.  */
284   int debug_loader_offset_p;
285
286   /* Load address for the dynamic linker, inferred.  */
287   CORE_ADDR debug_loader_offset;
288
289   /* Name of the dynamic linker, valid if debug_loader_offset_p.  */
290   char *debug_loader_name;
291
292   /* Load map address for the main executable.  */
293   CORE_ADDR main_lm_addr;
294
295   CORE_ADDR interp_text_sect_low;
296   CORE_ADDR interp_text_sect_high;
297   CORE_ADDR interp_plt_sect_low;
298   CORE_ADDR interp_plt_sect_high;
299 };
300
301 /* Per-program-space data key.  */
302 static const struct program_space_data *solib_svr4_pspace_data;
303
304 static void
305 svr4_pspace_data_cleanup (struct program_space *pspace, void *arg)
306 {
307   struct svr4_info *info;
308
309   info = program_space_data (pspace, solib_svr4_pspace_data);
310   xfree (info);
311 }
312
313 /* Get the current svr4 data.  If none is found yet, add it now.  This
314    function always returns a valid object.  */
315
316 static struct svr4_info *
317 get_svr4_info (void)
318 {
319   struct svr4_info *info;
320
321   info = program_space_data (current_program_space, solib_svr4_pspace_data);
322   if (info != NULL)
323     return info;
324
325   info = XZALLOC (struct svr4_info);
326   set_program_space_data (current_program_space, solib_svr4_pspace_data, info);
327   return info;
328 }
329
330 /* Local function prototypes */
331
332 static int match_main (char *);
333
334 static CORE_ADDR bfd_lookup_symbol (bfd *, char *);
335
336 /*
337
338    LOCAL FUNCTION
339
340    bfd_lookup_symbol -- lookup the value for a specific symbol
341
342    SYNOPSIS
343
344    CORE_ADDR bfd_lookup_symbol (bfd *abfd, char *symname)
345
346    DESCRIPTION
347
348    An expensive way to lookup the value of a single symbol for
349    bfd's that are only temporary anyway.  This is used by the
350    shared library support to find the address of the debugger
351    notification routine in the shared library.
352
353    The returned symbol may be in a code or data section; functions
354    will normally be in a code section, but may be in a data section
355    if this architecture uses function descriptors.
356
357    Note that 0 is specifically allowed as an error return (no
358    such symbol).
359  */
360
361 static CORE_ADDR
362 bfd_lookup_symbol (bfd *abfd, char *symname)
363 {
364   long storage_needed;
365   asymbol *sym;
366   asymbol **symbol_table;
367   unsigned int number_of_symbols;
368   unsigned int i;
369   struct cleanup *back_to;
370   CORE_ADDR symaddr = 0;
371
372   storage_needed = bfd_get_symtab_upper_bound (abfd);
373
374   if (storage_needed > 0)
375     {
376       symbol_table = (asymbol **) xmalloc (storage_needed);
377       back_to = make_cleanup (xfree, symbol_table);
378       number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table);
379
380       for (i = 0; i < number_of_symbols; i++)
381         {
382           sym = *symbol_table++;
383           if (strcmp (sym->name, symname) == 0
384               && (sym->section->flags & (SEC_CODE | SEC_DATA)) != 0)
385             {
386               /* BFD symbols are section relative.  */
387               symaddr = sym->value + sym->section->vma;
388               break;
389             }
390         }
391       do_cleanups (back_to);
392     }
393
394   if (symaddr)
395     return symaddr;
396
397   /* On FreeBSD, the dynamic linker is stripped by default.  So we'll
398      have to check the dynamic string table too.  */
399
400   storage_needed = bfd_get_dynamic_symtab_upper_bound (abfd);
401
402   if (storage_needed > 0)
403     {
404       symbol_table = (asymbol **) xmalloc (storage_needed);
405       back_to = make_cleanup (xfree, symbol_table);
406       number_of_symbols = bfd_canonicalize_dynamic_symtab (abfd, symbol_table);
407
408       for (i = 0; i < number_of_symbols; i++)
409         {
410           sym = *symbol_table++;
411
412           if (strcmp (sym->name, symname) == 0
413               && (sym->section->flags & (SEC_CODE | SEC_DATA)) != 0)
414             {
415               /* BFD symbols are section relative.  */
416               symaddr = sym->value + sym->section->vma;
417               break;
418             }
419         }
420       do_cleanups (back_to);
421     }
422
423   return symaddr;
424 }
425
426
427 /* Read program header TYPE from inferior memory.  The header is found
428    by scanning the OS auxillary vector.
429
430    Return a pointer to allocated memory holding the program header contents,
431    or NULL on failure.  If sucessful, and unless P_SECT_SIZE is NULL, the
432    size of those contents is returned to P_SECT_SIZE.  Likewise, the target
433    architecture size (32-bit or 64-bit) is returned to P_ARCH_SIZE.  */
434
435 static gdb_byte *
436 read_program_header (int type, int *p_sect_size, int *p_arch_size)
437 {
438   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch);
439   CORE_ADDR at_phdr, at_phent, at_phnum;
440   int arch_size, sect_size;
441   CORE_ADDR sect_addr;
442   gdb_byte *buf;
443
444   /* Get required auxv elements from target.  */
445   if (target_auxv_search (&current_target, AT_PHDR, &at_phdr) <= 0)
446     return 0;
447   if (target_auxv_search (&current_target, AT_PHENT, &at_phent) <= 0)
448     return 0;
449   if (target_auxv_search (&current_target, AT_PHNUM, &at_phnum) <= 0)
450     return 0;
451   if (!at_phdr || !at_phnum)
452     return 0;
453
454   /* Determine ELF architecture type.  */
455   if (at_phent == sizeof (Elf32_External_Phdr))
456     arch_size = 32;
457   else if (at_phent == sizeof (Elf64_External_Phdr))
458     arch_size = 64;
459   else
460     return 0;
461
462   /* Find .dynamic section via the PT_DYNAMIC PHDR.  */
463   if (arch_size == 32)
464     {
465       Elf32_External_Phdr phdr;
466       int i;
467
468       /* Search for requested PHDR.  */
469       for (i = 0; i < at_phnum; i++)
470         {
471           if (target_read_memory (at_phdr + i * sizeof (phdr),
472                                   (gdb_byte *)&phdr, sizeof (phdr)))
473             return 0;
474
475           if (extract_unsigned_integer ((gdb_byte *)phdr.p_type,
476                                         4, byte_order) == type)
477             break;
478         }
479
480       if (i == at_phnum)
481         return 0;
482
483       /* Retrieve address and size.  */
484       sect_addr = extract_unsigned_integer ((gdb_byte *)phdr.p_vaddr,
485                                             4, byte_order);
486       sect_size = extract_unsigned_integer ((gdb_byte *)phdr.p_memsz,
487                                             4, byte_order);
488     }
489   else
490     {
491       Elf64_External_Phdr phdr;
492       int i;
493
494       /* Search for requested PHDR.  */
495       for (i = 0; i < at_phnum; i++)
496         {
497           if (target_read_memory (at_phdr + i * sizeof (phdr),
498                                   (gdb_byte *)&phdr, sizeof (phdr)))
499             return 0;
500
501           if (extract_unsigned_integer ((gdb_byte *)phdr.p_type,
502                                         4, byte_order) == type)
503             break;
504         }
505
506       if (i == at_phnum)
507         return 0;
508
509       /* Retrieve address and size.  */
510       sect_addr = extract_unsigned_integer ((gdb_byte *)phdr.p_vaddr,
511                                             8, byte_order);
512       sect_size = extract_unsigned_integer ((gdb_byte *)phdr.p_memsz,
513                                             8, byte_order);
514     }
515
516   /* Read in requested program header.  */
517   buf = xmalloc (sect_size);
518   if (target_read_memory (sect_addr, buf, sect_size))
519     {
520       xfree (buf);
521       return NULL;
522     }
523
524   if (p_arch_size)
525     *p_arch_size = arch_size;
526   if (p_sect_size)
527     *p_sect_size = sect_size;
528
529   return buf;
530 }
531
532
533 /* Return program interpreter string.  */
534 static gdb_byte *
535 find_program_interpreter (void)
536 {
537   gdb_byte *buf = NULL;
538
539   /* If we have an exec_bfd, use its section table.  */
540   if (exec_bfd
541       && bfd_get_flavour (exec_bfd) == bfd_target_elf_flavour)
542    {
543      struct bfd_section *interp_sect;
544
545      interp_sect = bfd_get_section_by_name (exec_bfd, ".interp");
546      if (interp_sect != NULL)
547       {
548         CORE_ADDR sect_addr = bfd_section_vma (exec_bfd, interp_sect);
549         int sect_size = bfd_section_size (exec_bfd, interp_sect);
550
551         buf = xmalloc (sect_size);
552         bfd_get_section_contents (exec_bfd, interp_sect, buf, 0, sect_size);
553       }
554    }
555
556   /* If we didn't find it, use the target auxillary vector.  */
557   if (!buf)
558     buf = read_program_header (PT_INTERP, NULL, NULL);
559
560   return buf;
561 }
562
563
564 /* Scan for DYNTAG in .dynamic section of ABFD. If DYNTAG is found 1 is
565    returned and the corresponding PTR is set.  */
566
567 static int
568 scan_dyntag (int dyntag, bfd *abfd, CORE_ADDR *ptr)
569 {
570   int arch_size, step, sect_size;
571   long dyn_tag;
572   CORE_ADDR dyn_ptr;
573   gdb_byte *bufend, *bufstart, *buf;
574   Elf32_External_Dyn *x_dynp_32;
575   Elf64_External_Dyn *x_dynp_64;
576   struct bfd_section *sect;
577   struct target_section *target_section;
578
579   if (abfd == NULL)
580     return 0;
581
582   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
583     return 0;
584
585   arch_size = bfd_get_arch_size (abfd);
586   if (arch_size == -1)
587     return 0;
588
589   /* Find the start address of the .dynamic section.  */
590   sect = bfd_get_section_by_name (abfd, ".dynamic");
591   if (sect == NULL)
592     return 0;
593
594   for (target_section = current_target_sections->sections;
595        target_section < current_target_sections->sections_end;
596        target_section++)
597     if (sect == target_section->the_bfd_section)
598       break;
599   gdb_assert (target_section < current_target_sections->sections_end);
600
601   /* Read in .dynamic from the BFD.  We will get the actual value
602      from memory later.  */
603   sect_size = bfd_section_size (abfd, sect);
604   buf = bufstart = alloca (sect_size);
605   if (!bfd_get_section_contents (abfd, sect,
606                                  buf, 0, sect_size))
607     return 0;
608
609   /* Iterate over BUF and scan for DYNTAG.  If found, set PTR and return.  */
610   step = (arch_size == 32) ? sizeof (Elf32_External_Dyn)
611                            : sizeof (Elf64_External_Dyn);
612   for (bufend = buf + sect_size;
613        buf < bufend;
614        buf += step)
615   {
616     if (arch_size == 32)
617       {
618         x_dynp_32 = (Elf32_External_Dyn *) buf;
619         dyn_tag = bfd_h_get_32 (abfd, (bfd_byte *) x_dynp_32->d_tag);
620         dyn_ptr = bfd_h_get_32 (abfd, (bfd_byte *) x_dynp_32->d_un.d_ptr);
621       }
622     else
623       {
624         x_dynp_64 = (Elf64_External_Dyn *) buf;
625         dyn_tag = bfd_h_get_64 (abfd, (bfd_byte *) x_dynp_64->d_tag);
626         dyn_ptr = bfd_h_get_64 (abfd, (bfd_byte *) x_dynp_64->d_un.d_ptr);
627       }
628      if (dyn_tag == DT_NULL)
629        return 0;
630      if (dyn_tag == dyntag)
631        {
632          /* If requested, try to read the runtime value of this .dynamic
633             entry.  */
634          if (ptr)
635            {
636              struct type *ptr_type;
637              gdb_byte ptr_buf[8];
638              CORE_ADDR ptr_addr;
639
640              ptr_type = builtin_type (target_gdbarch)->builtin_data_ptr;
641              ptr_addr = target_section->addr + (buf - bufstart) + arch_size / 8;
642              if (target_read_memory (ptr_addr, ptr_buf, arch_size / 8) == 0)
643                dyn_ptr = extract_typed_address (ptr_buf, ptr_type);
644              *ptr = dyn_ptr;
645            }
646          return 1;
647        }
648   }
649
650   return 0;
651 }
652
653 /* Scan for DYNTAG in .dynamic section of the target's main executable,
654    found by consulting the OS auxillary vector.  If DYNTAG is found 1 is
655    returned and the corresponding PTR is set.  */
656
657 static int
658 scan_dyntag_auxv (int dyntag, CORE_ADDR *ptr)
659 {
660   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch);
661   int sect_size, arch_size, step;
662   long dyn_tag;
663   CORE_ADDR dyn_ptr;
664   gdb_byte *bufend, *bufstart, *buf;
665
666   /* Read in .dynamic section.  */
667   buf = bufstart = read_program_header (PT_DYNAMIC, &sect_size, &arch_size);
668   if (!buf)
669     return 0;
670
671   /* Iterate over BUF and scan for DYNTAG.  If found, set PTR and return.  */
672   step = (arch_size == 32) ? sizeof (Elf32_External_Dyn)
673                            : sizeof (Elf64_External_Dyn);
674   for (bufend = buf + sect_size;
675        buf < bufend;
676        buf += step)
677   {
678     if (arch_size == 32)
679       {
680         Elf32_External_Dyn *dynp = (Elf32_External_Dyn *) buf;
681         dyn_tag = extract_unsigned_integer ((gdb_byte *) dynp->d_tag,
682                                             4, byte_order);
683         dyn_ptr = extract_unsigned_integer ((gdb_byte *) dynp->d_un.d_ptr,
684                                             4, byte_order);
685       }
686     else
687       {
688         Elf64_External_Dyn *dynp = (Elf64_External_Dyn *) buf;
689         dyn_tag = extract_unsigned_integer ((gdb_byte *) dynp->d_tag,
690                                             8, byte_order);
691         dyn_ptr = extract_unsigned_integer ((gdb_byte *) dynp->d_un.d_ptr,
692                                             8, byte_order);
693       }
694     if (dyn_tag == DT_NULL)
695       break;
696
697     if (dyn_tag == dyntag)
698       {
699         if (ptr)
700           *ptr = dyn_ptr;
701
702         xfree (bufstart);
703         return 1;
704       }
705   }
706
707   xfree (bufstart);
708   return 0;
709 }
710
711
712 /*
713
714    LOCAL FUNCTION
715
716    elf_locate_base -- locate the base address of dynamic linker structs
717    for SVR4 elf targets.
718
719    SYNOPSIS
720
721    CORE_ADDR elf_locate_base (void)
722
723    DESCRIPTION
724
725    For SVR4 elf targets the address of the dynamic linker's runtime
726    structure is contained within the dynamic info section in the
727    executable file.  The dynamic section is also mapped into the
728    inferior address space.  Because the runtime loader fills in the
729    real address before starting the inferior, we have to read in the
730    dynamic info section from the inferior address space.
731    If there are any errors while trying to find the address, we
732    silently return 0, otherwise the found address is returned.
733
734  */
735
736 static CORE_ADDR
737 elf_locate_base (void)
738 {
739   struct minimal_symbol *msymbol;
740   CORE_ADDR dyn_ptr;
741
742   /* Look for DT_MIPS_RLD_MAP first.  MIPS executables use this
743      instead of DT_DEBUG, although they sometimes contain an unused
744      DT_DEBUG.  */
745   if (scan_dyntag (DT_MIPS_RLD_MAP, exec_bfd, &dyn_ptr)
746       || scan_dyntag_auxv (DT_MIPS_RLD_MAP, &dyn_ptr))
747     {
748       struct type *ptr_type = builtin_type (target_gdbarch)->builtin_data_ptr;
749       gdb_byte *pbuf;
750       int pbuf_size = TYPE_LENGTH (ptr_type);
751       pbuf = alloca (pbuf_size);
752       /* DT_MIPS_RLD_MAP contains a pointer to the address
753          of the dynamic link structure.  */
754       if (target_read_memory (dyn_ptr, pbuf, pbuf_size))
755         return 0;
756       return extract_typed_address (pbuf, ptr_type);
757     }
758
759   /* Find DT_DEBUG.  */
760   if (scan_dyntag (DT_DEBUG, exec_bfd, &dyn_ptr)
761       || scan_dyntag_auxv (DT_DEBUG, &dyn_ptr))
762     return dyn_ptr;
763
764   /* This may be a static executable.  Look for the symbol
765      conventionally named _r_debug, as a last resort.  */
766   msymbol = lookup_minimal_symbol ("_r_debug", NULL, symfile_objfile);
767   if (msymbol != NULL)
768     return SYMBOL_VALUE_ADDRESS (msymbol);
769
770   /* DT_DEBUG entry not found.  */
771   return 0;
772 }
773
774 /*
775
776    LOCAL FUNCTION
777
778    locate_base -- locate the base address of dynamic linker structs
779
780    SYNOPSIS
781
782    CORE_ADDR locate_base (struct svr4_info *)
783
784    DESCRIPTION
785
786    For both the SunOS and SVR4 shared library implementations, if the
787    inferior executable has been linked dynamically, there is a single
788    address somewhere in the inferior's data space which is the key to
789    locating all of the dynamic linker's runtime structures.  This
790    address is the value of the debug base symbol.  The job of this
791    function is to find and return that address, or to return 0 if there
792    is no such address (the executable is statically linked for example).
793
794    For SunOS, the job is almost trivial, since the dynamic linker and
795    all of it's structures are statically linked to the executable at
796    link time.  Thus the symbol for the address we are looking for has
797    already been added to the minimal symbol table for the executable's
798    objfile at the time the symbol file's symbols were read, and all we
799    have to do is look it up there.  Note that we explicitly do NOT want
800    to find the copies in the shared library.
801
802    The SVR4 version is a bit more complicated because the address
803    is contained somewhere in the dynamic info section.  We have to go
804    to a lot more work to discover the address of the debug base symbol.
805    Because of this complexity, we cache the value we find and return that
806    value on subsequent invocations.  Note there is no copy in the
807    executable symbol tables.
808
809  */
810
811 static CORE_ADDR
812 locate_base (struct svr4_info *info)
813 {
814   /* Check to see if we have a currently valid address, and if so, avoid
815      doing all this work again and just return the cached address.  If
816      we have no cached address, try to locate it in the dynamic info
817      section for ELF executables.  There's no point in doing any of this
818      though if we don't have some link map offsets to work with.  */
819
820   if (info->debug_base == 0 && svr4_have_link_map_offsets ())
821     info->debug_base = elf_locate_base ();
822   return info->debug_base;
823 }
824
825 /* Find the first element in the inferior's dynamic link map, and
826    return its address in the inferior.
827
828    FIXME: Perhaps we should validate the info somehow, perhaps by
829    checking r_version for a known version number, or r_state for
830    RT_CONSISTENT.  */
831
832 static CORE_ADDR
833 solib_svr4_r_map (struct svr4_info *info)
834 {
835   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
836   struct type *ptr_type = builtin_type (target_gdbarch)->builtin_data_ptr;
837
838   return read_memory_typed_address (info->debug_base + lmo->r_map_offset,
839                                     ptr_type);
840 }
841
842 /* Find r_brk from the inferior's debug base.  */
843
844 static CORE_ADDR
845 solib_svr4_r_brk (struct svr4_info *info)
846 {
847   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
848   struct type *ptr_type = builtin_type (target_gdbarch)->builtin_data_ptr;
849
850   return read_memory_typed_address (info->debug_base + lmo->r_brk_offset,
851                                     ptr_type);
852 }
853
854 /* Find the link map for the dynamic linker (if it is not in the
855    normal list of loaded shared objects).  */
856
857 static CORE_ADDR
858 solib_svr4_r_ldsomap (struct svr4_info *info)
859 {
860   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
861   struct type *ptr_type = builtin_type (target_gdbarch)->builtin_data_ptr;
862   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch);
863   ULONGEST version;
864
865   /* Check version, and return zero if `struct r_debug' doesn't have
866      the r_ldsomap member.  */
867   version
868     = read_memory_unsigned_integer (info->debug_base + lmo->r_version_offset,
869                                     lmo->r_version_size, byte_order);
870   if (version < 2 || lmo->r_ldsomap_offset == -1)
871     return 0;
872
873   return read_memory_typed_address (info->debug_base + lmo->r_ldsomap_offset,
874                                     ptr_type);
875 }
876
877 /* On Solaris systems with some versions of the dynamic linker,
878    ld.so's l_name pointer points to the SONAME in the string table
879    rather than into writable memory.  So that GDB can find shared
880    libraries when loading a core file generated by gcore, ensure that
881    memory areas containing the l_name string are saved in the core
882    file.  */
883
884 static int
885 svr4_keep_data_in_core (CORE_ADDR vaddr, unsigned long size)
886 {
887   struct svr4_info *info;
888   CORE_ADDR ldsomap;
889   struct so_list *new;
890   struct cleanup *old_chain;
891   struct link_map_offsets *lmo;
892   CORE_ADDR lm_name;
893
894   info = get_svr4_info ();
895
896   info->debug_base = 0;
897   locate_base (info);
898   if (!info->debug_base)
899     return 0;
900
901   ldsomap = solib_svr4_r_ldsomap (info);
902   if (!ldsomap)
903     return 0;
904
905   lmo = svr4_fetch_link_map_offsets ();
906   new = XZALLOC (struct so_list);
907   old_chain = make_cleanup (xfree, new);
908   new->lm_info = xmalloc (sizeof (struct lm_info));
909   make_cleanup (xfree, new->lm_info);
910   new->lm_info->l_addr = (CORE_ADDR)-1;
911   new->lm_info->lm_addr = ldsomap;
912   new->lm_info->lm = xzalloc (lmo->link_map_size);
913   make_cleanup (xfree, new->lm_info->lm);
914   read_memory (ldsomap, new->lm_info->lm, lmo->link_map_size);
915   lm_name = LM_NAME (new);
916   do_cleanups (old_chain);
917
918   return (lm_name >= vaddr && lm_name < vaddr + size);
919 }
920
921 /*
922
923   LOCAL FUNCTION
924
925   open_symbol_file_object
926
927   SYNOPSIS
928
929   void open_symbol_file_object (void *from_tty)
930
931   DESCRIPTION
932
933   If no open symbol file, attempt to locate and open the main symbol
934   file.  On SVR4 systems, this is the first link map entry.  If its
935   name is here, we can open it.  Useful when attaching to a process
936   without first loading its symbol file.
937
938   If FROM_TTYP dereferences to a non-zero integer, allow messages to
939   be printed.  This parameter is a pointer rather than an int because
940   open_symbol_file_object() is called via catch_errors() and
941   catch_errors() requires a pointer argument. */
942
943 static int
944 open_symbol_file_object (void *from_ttyp)
945 {
946   CORE_ADDR lm, l_name;
947   char *filename;
948   int errcode;
949   int from_tty = *(int *)from_ttyp;
950   struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
951   struct type *ptr_type = builtin_type (target_gdbarch)->builtin_data_ptr;
952   int l_name_size = TYPE_LENGTH (ptr_type);
953   gdb_byte *l_name_buf = xmalloc (l_name_size);
954   struct cleanup *cleanups = make_cleanup (xfree, l_name_buf);
955   struct svr4_info *info = get_svr4_info ();
956
957   if (symfile_objfile)
958     if (!query (_("Attempt to reload symbols from process? ")))
959       return 0;
960
961   /* Always locate the debug struct, in case it has moved.  */
962   info->debug_base = 0;
963   if (locate_base (info) == 0)
964     return 0;   /* failed somehow... */
965
966   /* First link map member should be the executable.  */
967   lm = solib_svr4_r_map (info);
968   if (lm == 0)
969     return 0;   /* failed somehow... */
970
971   /* Read address of name from target memory to GDB.  */
972   read_memory (lm + lmo->l_name_offset, l_name_buf, l_name_size);
973
974   /* Convert the address to host format.  */
975   l_name = extract_typed_address (l_name_buf, ptr_type);
976
977   /* Free l_name_buf.  */
978   do_cleanups (cleanups);
979
980   if (l_name == 0)
981     return 0;           /* No filename.  */
982
983   /* Now fetch the filename from target memory.  */
984   target_read_string (l_name, &filename, SO_NAME_MAX_PATH_SIZE - 1, &errcode);
985   make_cleanup (xfree, filename);
986
987   if (errcode)
988     {
989       warning (_("failed to read exec filename from attached file: %s"),
990                safe_strerror (errcode));
991       return 0;
992     }
993
994   /* Have a pathname: read the symbol file.  */
995   symbol_file_add_main (filename, from_tty);
996
997   return 1;
998 }
999
1000 /* If no shared library information is available from the dynamic
1001    linker, build a fallback list from other sources.  */
1002
1003 static struct so_list *
1004 svr4_default_sos (void)
1005 {
1006   struct svr4_info *info = get_svr4_info ();
1007
1008   struct so_list *head = NULL;
1009   struct so_list **link_ptr = &head;
1010
1011   if (info->debug_loader_offset_p)
1012     {
1013       struct so_list *new = XZALLOC (struct so_list);
1014
1015       new->lm_info = xmalloc (sizeof (struct lm_info));
1016
1017       /* Nothing will ever check the cached copy of the link
1018          map if we set l_addr.  */
1019       new->lm_info->l_addr = info->debug_loader_offset;
1020       new->lm_info->lm_addr = 0;
1021       new->lm_info->lm = NULL;
1022
1023       strncpy (new->so_name, info->debug_loader_name,
1024                SO_NAME_MAX_PATH_SIZE - 1);
1025       new->so_name[SO_NAME_MAX_PATH_SIZE - 1] = '\0';
1026       strcpy (new->so_original_name, new->so_name);
1027
1028       *link_ptr = new;
1029       link_ptr = &new->next;
1030     }
1031
1032   return head;
1033 }
1034
1035 /* LOCAL FUNCTION
1036
1037    current_sos -- build a list of currently loaded shared objects
1038
1039    SYNOPSIS
1040
1041    struct so_list *current_sos ()
1042
1043    DESCRIPTION
1044
1045    Build a list of `struct so_list' objects describing the shared
1046    objects currently loaded in the inferior.  This list does not
1047    include an entry for the main executable file.
1048
1049    Note that we only gather information directly available from the
1050    inferior --- we don't examine any of the shared library files
1051    themselves.  The declaration of `struct so_list' says which fields
1052    we provide values for.  */
1053
1054 static struct so_list *
1055 svr4_current_sos (void)
1056 {
1057   CORE_ADDR lm;
1058   struct so_list *head = 0;
1059   struct so_list **link_ptr = &head;
1060   CORE_ADDR ldsomap = 0;
1061   struct svr4_info *info;
1062
1063   info = get_svr4_info ();
1064
1065   /* Always locate the debug struct, in case it has moved.  */
1066   info->debug_base = 0;
1067   locate_base (info);
1068
1069   /* If we can't find the dynamic linker's base structure, this
1070      must not be a dynamically linked executable.  Hmm.  */
1071   if (! info->debug_base)
1072     return svr4_default_sos ();
1073
1074   /* Walk the inferior's link map list, and build our list of
1075      `struct so_list' nodes.  */
1076   lm = solib_svr4_r_map (info);
1077
1078   while (lm)
1079     {
1080       struct link_map_offsets *lmo = svr4_fetch_link_map_offsets ();
1081       struct so_list *new = XZALLOC (struct so_list);
1082       struct cleanup *old_chain = make_cleanup (xfree, new);
1083
1084       new->lm_info = xmalloc (sizeof (struct lm_info));
1085       make_cleanup (xfree, new->lm_info);
1086
1087       new->lm_info->l_addr = (CORE_ADDR)-1;
1088       new->lm_info->lm_addr = lm;
1089       new->lm_info->lm = xzalloc (lmo->link_map_size);
1090       make_cleanup (xfree, new->lm_info->lm);
1091
1092       read_memory (lm, new->lm_info->lm, lmo->link_map_size);
1093
1094       lm = LM_NEXT (new);
1095
1096       /* For SVR4 versions, the first entry in the link map is for the
1097          inferior executable, so we must ignore it.  For some versions of
1098          SVR4, it has no name.  For others (Solaris 2.3 for example), it
1099          does have a name, so we can no longer use a missing name to
1100          decide when to ignore it. */
1101       if (IGNORE_FIRST_LINK_MAP_ENTRY (new) && ldsomap == 0)
1102         {
1103           info->main_lm_addr = new->lm_info->lm_addr;
1104           free_so (new);
1105         }
1106       else
1107         {
1108           int errcode;
1109           char *buffer;
1110
1111           /* Extract this shared object's name.  */
1112           target_read_string (LM_NAME (new), &buffer,
1113                               SO_NAME_MAX_PATH_SIZE - 1, &errcode);
1114           if (errcode != 0)
1115             warning (_("Can't read pathname for load map: %s."),
1116                      safe_strerror (errcode));
1117           else
1118             {
1119               strncpy (new->so_name, buffer, SO_NAME_MAX_PATH_SIZE - 1);
1120               new->so_name[SO_NAME_MAX_PATH_SIZE - 1] = '\0';
1121               strcpy (new->so_original_name, new->so_name);
1122             }
1123           xfree (buffer);
1124
1125           /* If this entry has no name, or its name matches the name
1126              for the main executable, don't include it in the list.  */
1127           if (! new->so_name[0]
1128               || match_main (new->so_name))
1129             free_so (new);
1130           else
1131             {
1132               new->next = 0;
1133               *link_ptr = new;
1134               link_ptr = &new->next;
1135             }
1136         }
1137
1138       /* On Solaris, the dynamic linker is not in the normal list of
1139          shared objects, so make sure we pick it up too.  Having
1140          symbol information for the dynamic linker is quite crucial
1141          for skipping dynamic linker resolver code.  */
1142       if (lm == 0 && ldsomap == 0)
1143         lm = ldsomap = solib_svr4_r_ldsomap (info);
1144
1145       discard_cleanups (old_chain);
1146     }
1147
1148   if (head == NULL)
1149     return svr4_default_sos ();
1150
1151   return head;
1152 }
1153
1154 /* Get the address of the link_map for a given OBJFILE.  */
1155
1156 CORE_ADDR
1157 svr4_fetch_objfile_link_map (struct objfile *objfile)
1158 {
1159   struct so_list *so;
1160   struct svr4_info *info = get_svr4_info ();
1161
1162   /* Cause svr4_current_sos() to be run if it hasn't been already.  */
1163   if (info->main_lm_addr == 0)
1164     solib_add (NULL, 0, &current_target, auto_solib_add);
1165
1166   /* svr4_current_sos() will set main_lm_addr for the main executable.  */
1167   if (objfile == symfile_objfile)
1168     return info->main_lm_addr;
1169
1170   /* The other link map addresses may be found by examining the list
1171      of shared libraries.  */
1172   for (so = master_so_list (); so; so = so->next)
1173     if (so->objfile == objfile)
1174       return so->lm_info->lm_addr;
1175
1176   /* Not found!  */
1177   return 0;
1178 }
1179
1180 /* On some systems, the only way to recognize the link map entry for
1181    the main executable file is by looking at its name.  Return
1182    non-zero iff SONAME matches one of the known main executable names.  */
1183
1184 static int
1185 match_main (char *soname)
1186 {
1187   char **mainp;
1188
1189   for (mainp = main_name_list; *mainp != NULL; mainp++)
1190     {
1191       if (strcmp (soname, *mainp) == 0)
1192         return (1);
1193     }
1194
1195   return (0);
1196 }
1197
1198 /* Return 1 if PC lies in the dynamic symbol resolution code of the
1199    SVR4 run time loader.  */
1200
1201 int
1202 svr4_in_dynsym_resolve_code (CORE_ADDR pc)
1203 {
1204   struct svr4_info *info = get_svr4_info ();
1205
1206   return ((pc >= info->interp_text_sect_low
1207            && pc < info->interp_text_sect_high)
1208           || (pc >= info->interp_plt_sect_low
1209               && pc < info->interp_plt_sect_high)
1210           || in_plt_section (pc, NULL));
1211 }
1212
1213 /* Given an executable's ABFD and target, compute the entry-point
1214    address.  */
1215
1216 static CORE_ADDR
1217 exec_entry_point (struct bfd *abfd, struct target_ops *targ)
1218 {
1219   /* KevinB wrote ... for most targets, the address returned by
1220      bfd_get_start_address() is the entry point for the start
1221      function.  But, for some targets, bfd_get_start_address() returns
1222      the address of a function descriptor from which the entry point
1223      address may be extracted.  This address is extracted by
1224      gdbarch_convert_from_func_ptr_addr().  The method
1225      gdbarch_convert_from_func_ptr_addr() is the merely the identify
1226      function for targets which don't use function descriptors.  */
1227   return gdbarch_convert_from_func_ptr_addr (target_gdbarch,
1228                                              bfd_get_start_address (abfd),
1229                                              targ);
1230 }
1231
1232 /*
1233
1234    LOCAL FUNCTION
1235
1236    enable_break -- arrange for dynamic linker to hit breakpoint
1237
1238    SYNOPSIS
1239
1240    int enable_break (void)
1241
1242    DESCRIPTION
1243
1244    Both the SunOS and the SVR4 dynamic linkers have, as part of their
1245    debugger interface, support for arranging for the inferior to hit
1246    a breakpoint after mapping in the shared libraries.  This function
1247    enables that breakpoint.
1248
1249    For SunOS, there is a special flag location (in_debugger) which we
1250    set to 1.  When the dynamic linker sees this flag set, it will set
1251    a breakpoint at a location known only to itself, after saving the
1252    original contents of that place and the breakpoint address itself,
1253    in it's own internal structures.  When we resume the inferior, it
1254    will eventually take a SIGTRAP when it runs into the breakpoint.
1255    We handle this (in a different place) by restoring the contents of
1256    the breakpointed location (which is only known after it stops),
1257    chasing around to locate the shared libraries that have been
1258    loaded, then resuming.
1259
1260    For SVR4, the debugger interface structure contains a member (r_brk)
1261    which is statically initialized at the time the shared library is
1262    built, to the offset of a function (_r_debug_state) which is guaran-
1263    teed to be called once before mapping in a library, and again when
1264    the mapping is complete.  At the time we are examining this member,
1265    it contains only the unrelocated offset of the function, so we have
1266    to do our own relocation.  Later, when the dynamic linker actually
1267    runs, it relocates r_brk to be the actual address of _r_debug_state().
1268
1269    The debugger interface structure also contains an enumeration which
1270    is set to either RT_ADD or RT_DELETE prior to changing the mapping,
1271    depending upon whether or not the library is being mapped or unmapped,
1272    and then set to RT_CONSISTENT after the library is mapped/unmapped.
1273  */
1274
1275 static int
1276 enable_break (struct svr4_info *info, int from_tty)
1277 {
1278   struct minimal_symbol *msymbol;
1279   char **bkpt_namep;
1280   asection *interp_sect;
1281   gdb_byte *interp_name;
1282   CORE_ADDR sym_addr;
1283
1284   /* First, remove all the solib event breakpoints.  Their addresses
1285      may have changed since the last time we ran the program.  */
1286   remove_solib_event_breakpoints ();
1287
1288   info->interp_text_sect_low = info->interp_text_sect_high = 0;
1289   info->interp_plt_sect_low = info->interp_plt_sect_high = 0;
1290
1291   /* If we already have a shared library list in the target, and
1292      r_debug contains r_brk, set the breakpoint there - this should
1293      mean r_brk has already been relocated.  Assume the dynamic linker
1294      is the object containing r_brk.  */
1295
1296   solib_add (NULL, from_tty, &current_target, auto_solib_add);
1297   sym_addr = 0;
1298   if (info->debug_base && solib_svr4_r_map (info) != 0)
1299     sym_addr = solib_svr4_r_brk (info);
1300
1301   if (sym_addr != 0)
1302     {
1303       struct obj_section *os;
1304
1305       sym_addr = gdbarch_addr_bits_remove
1306         (target_gdbarch, gdbarch_convert_from_func_ptr_addr (target_gdbarch,
1307                                                               sym_addr,
1308                                                               &current_target));
1309
1310       os = find_pc_section (sym_addr);
1311       if (os != NULL)
1312         {
1313           /* Record the relocated start and end address of the dynamic linker
1314              text and plt section for svr4_in_dynsym_resolve_code.  */
1315           bfd *tmp_bfd;
1316           CORE_ADDR load_addr;
1317
1318           tmp_bfd = os->objfile->obfd;
1319           load_addr = ANOFFSET (os->objfile->section_offsets,
1320                                 os->objfile->sect_index_text);
1321
1322           interp_sect = bfd_get_section_by_name (tmp_bfd, ".text");
1323           if (interp_sect)
1324             {
1325               info->interp_text_sect_low =
1326                 bfd_section_vma (tmp_bfd, interp_sect) + load_addr;
1327               info->interp_text_sect_high =
1328                 info->interp_text_sect_low
1329                 + bfd_section_size (tmp_bfd, interp_sect);
1330             }
1331           interp_sect = bfd_get_section_by_name (tmp_bfd, ".plt");
1332           if (interp_sect)
1333             {
1334               info->interp_plt_sect_low =
1335                 bfd_section_vma (tmp_bfd, interp_sect) + load_addr;
1336               info->interp_plt_sect_high =
1337                 info->interp_plt_sect_low
1338                 + bfd_section_size (tmp_bfd, interp_sect);
1339             }
1340
1341           create_solib_event_breakpoint (target_gdbarch, sym_addr);
1342           return 1;
1343         }
1344     }
1345
1346   /* Find the program interpreter; if not found, warn the user and drop
1347      into the old breakpoint at symbol code.  */
1348   interp_name = find_program_interpreter ();
1349   if (interp_name)
1350     {
1351       CORE_ADDR load_addr = 0;
1352       int load_addr_found = 0;
1353       int loader_found_in_list = 0;
1354       struct so_list *so;
1355       bfd *tmp_bfd = NULL;
1356       struct target_ops *tmp_bfd_target;
1357       volatile struct gdb_exception ex;
1358
1359       sym_addr = 0;
1360
1361       /* Now we need to figure out where the dynamic linker was
1362          loaded so that we can load its symbols and place a breakpoint
1363          in the dynamic linker itself.
1364
1365          This address is stored on the stack.  However, I've been unable
1366          to find any magic formula to find it for Solaris (appears to
1367          be trivial on GNU/Linux).  Therefore, we have to try an alternate
1368          mechanism to find the dynamic linker's base address.  */
1369
1370       TRY_CATCH (ex, RETURN_MASK_ALL)
1371         {
1372           tmp_bfd = solib_bfd_open (interp_name);
1373         }
1374       if (tmp_bfd == NULL)
1375         goto bkpt_at_symbol;
1376
1377       /* Now convert the TMP_BFD into a target.  That way target, as
1378          well as BFD operations can be used.  Note that closing the
1379          target will also close the underlying bfd.  */
1380       tmp_bfd_target = target_bfd_reopen (tmp_bfd);
1381
1382       /* On a running target, we can get the dynamic linker's base
1383          address from the shared library table.  */
1384       so = master_so_list ();
1385       while (so)
1386         {
1387           if (svr4_same_1 (interp_name, so->so_original_name))
1388             {
1389               load_addr_found = 1;
1390               loader_found_in_list = 1;
1391               load_addr = LM_ADDR_CHECK (so, tmp_bfd);
1392               break;
1393             }
1394           so = so->next;
1395         }
1396
1397       /* If we were not able to find the base address of the loader
1398          from our so_list, then try using the AT_BASE auxilliary entry.  */
1399       if (!load_addr_found)
1400         if (target_auxv_search (&current_target, AT_BASE, &load_addr) > 0)
1401           load_addr_found = 1;
1402
1403       /* Otherwise we find the dynamic linker's base address by examining
1404          the current pc (which should point at the entry point for the
1405          dynamic linker) and subtracting the offset of the entry point.
1406
1407          This is more fragile than the previous approaches, but is a good
1408          fallback method because it has actually been working well in
1409          most cases.  */
1410       if (!load_addr_found)
1411         {
1412           struct regcache *regcache
1413             = get_thread_arch_regcache (inferior_ptid, target_gdbarch);
1414           load_addr = (regcache_read_pc (regcache)
1415                        - exec_entry_point (tmp_bfd, tmp_bfd_target));
1416         }
1417
1418       if (!loader_found_in_list)
1419         {
1420           info->debug_loader_name = xstrdup (interp_name);
1421           info->debug_loader_offset_p = 1;
1422           info->debug_loader_offset = load_addr;
1423           solib_add (NULL, from_tty, &current_target, auto_solib_add);
1424         }
1425
1426       /* Record the relocated start and end address of the dynamic linker
1427          text and plt section for svr4_in_dynsym_resolve_code.  */
1428       interp_sect = bfd_get_section_by_name (tmp_bfd, ".text");
1429       if (interp_sect)
1430         {
1431           info->interp_text_sect_low =
1432             bfd_section_vma (tmp_bfd, interp_sect) + load_addr;
1433           info->interp_text_sect_high =
1434             info->interp_text_sect_low
1435             + bfd_section_size (tmp_bfd, interp_sect);
1436         }
1437       interp_sect = bfd_get_section_by_name (tmp_bfd, ".plt");
1438       if (interp_sect)
1439         {
1440           info->interp_plt_sect_low =
1441             bfd_section_vma (tmp_bfd, interp_sect) + load_addr;
1442           info->interp_plt_sect_high =
1443             info->interp_plt_sect_low
1444             + bfd_section_size (tmp_bfd, interp_sect);
1445         }
1446
1447       /* Now try to set a breakpoint in the dynamic linker.  */
1448       for (bkpt_namep = solib_break_names; *bkpt_namep != NULL; bkpt_namep++)
1449         {
1450           sym_addr = bfd_lookup_symbol (tmp_bfd, *bkpt_namep);
1451           if (sym_addr != 0)
1452             break;
1453         }
1454
1455       if (sym_addr != 0)
1456         /* Convert 'sym_addr' from a function pointer to an address.
1457            Because we pass tmp_bfd_target instead of the current
1458            target, this will always produce an unrelocated value.  */
1459         sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
1460                                                        sym_addr,
1461                                                        tmp_bfd_target);
1462
1463       /* We're done with both the temporary bfd and target.  Remember,
1464          closing the target closes the underlying bfd.  */
1465       target_close (tmp_bfd_target, 0);
1466
1467       if (sym_addr != 0)
1468         {
1469           create_solib_event_breakpoint (target_gdbarch, load_addr + sym_addr);
1470           xfree (interp_name);
1471           return 1;
1472         }
1473
1474       /* For whatever reason we couldn't set a breakpoint in the dynamic
1475          linker.  Warn and drop into the old code.  */
1476     bkpt_at_symbol:
1477       xfree (interp_name);
1478       warning (_("Unable to find dynamic linker breakpoint function.\n"
1479                "GDB will be unable to debug shared library initializers\n"
1480                "and track explicitly loaded dynamic code."));
1481     }
1482
1483   /* Scan through the lists of symbols, trying to look up the symbol and
1484      set a breakpoint there.  Terminate loop when we/if we succeed.  */
1485
1486   for (bkpt_namep = solib_break_names; *bkpt_namep != NULL; bkpt_namep++)
1487     {
1488       msymbol = lookup_minimal_symbol (*bkpt_namep, NULL, symfile_objfile);
1489       if ((msymbol != NULL) && (SYMBOL_VALUE_ADDRESS (msymbol) != 0))
1490         {
1491           sym_addr = SYMBOL_VALUE_ADDRESS (msymbol);
1492           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
1493                                                          sym_addr,
1494                                                          &current_target);
1495           create_solib_event_breakpoint (target_gdbarch, sym_addr);
1496           return 1;
1497         }
1498     }
1499
1500   for (bkpt_namep = bkpt_names; *bkpt_namep != NULL; bkpt_namep++)
1501     {
1502       msymbol = lookup_minimal_symbol (*bkpt_namep, NULL, symfile_objfile);
1503       if ((msymbol != NULL) && (SYMBOL_VALUE_ADDRESS (msymbol) != 0))
1504         {
1505           sym_addr = SYMBOL_VALUE_ADDRESS (msymbol);
1506           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
1507                                                          sym_addr,
1508                                                          &current_target);
1509           create_solib_event_breakpoint (target_gdbarch, sym_addr);
1510           return 1;
1511         }
1512     }
1513   return 0;
1514 }
1515
1516 /*
1517
1518    LOCAL FUNCTION
1519
1520    special_symbol_handling -- additional shared library symbol handling
1521
1522    SYNOPSIS
1523
1524    void special_symbol_handling ()
1525
1526    DESCRIPTION
1527
1528    Once the symbols from a shared object have been loaded in the usual
1529    way, we are called to do any system specific symbol handling that 
1530    is needed.
1531
1532    For SunOS4, this consisted of grunging around in the dynamic
1533    linkers structures to find symbol definitions for "common" symbols
1534    and adding them to the minimal symbol table for the runtime common
1535    objfile.
1536
1537    However, for SVR4, there's nothing to do.
1538
1539  */
1540
1541 static void
1542 svr4_special_symbol_handling (void)
1543 {
1544   svr4_relocate_main_executable ();
1545 }
1546
1547 /* Decide if the objfile needs to be relocated.  As indicated above,
1548    we will only be here when execution is stopped at the beginning
1549    of the program.  Relocation is necessary if the address at which
1550    we are presently stopped differs from the start address stored in
1551    the executable AND there's no interpreter section.  The condition
1552    regarding the interpreter section is very important because if
1553    there *is* an interpreter section, execution will begin there
1554    instead.  When there is an interpreter section, the start address
1555    is (presumably) used by the interpreter at some point to start
1556    execution of the program.
1557
1558    If there is an interpreter, it is normal for it to be set to an
1559    arbitrary address at the outset.  The job of finding it is
1560    handled in enable_break().
1561
1562    So, to summarize, relocations are necessary when there is no
1563    interpreter section and the start address obtained from the
1564    executable is different from the address at which GDB is
1565    currently stopped.
1566    
1567    [ The astute reader will note that we also test to make sure that
1568      the executable in question has the DYNAMIC flag set.  It is my
1569      opinion that this test is unnecessary (undesirable even).  It
1570      was added to avoid inadvertent relocation of an executable
1571      whose e_type member in the ELF header is not ET_DYN.  There may
1572      be a time in the future when it is desirable to do relocations
1573      on other types of files as well in which case this condition
1574      should either be removed or modified to accomodate the new file
1575      type.  (E.g, an ET_EXEC executable which has been built to be
1576      position-independent could safely be relocated by the OS if
1577      desired.  It is true that this violates the ABI, but the ABI
1578      has been known to be bent from time to time.)  - Kevin, Nov 2000. ]
1579    */
1580
1581 static CORE_ADDR
1582 svr4_static_exec_displacement (void)
1583 {
1584   asection *interp_sect;
1585   struct regcache *regcache
1586     = get_thread_arch_regcache (inferior_ptid, target_gdbarch);
1587   CORE_ADDR pc = regcache_read_pc (regcache);
1588
1589   interp_sect = bfd_get_section_by_name (exec_bfd, ".interp");
1590   if (interp_sect == NULL 
1591       && (bfd_get_file_flags (exec_bfd) & DYNAMIC) != 0
1592       && (exec_entry_point (exec_bfd, &exec_ops) != pc))
1593     return pc - exec_entry_point (exec_bfd, &exec_ops);
1594
1595   return 0;
1596 }
1597
1598 /* We relocate all of the sections by the same amount.  This
1599    behavior is mandated by recent editions of the System V ABI. 
1600    According to the System V Application Binary Interface,
1601    Edition 4.1, page 5-5:
1602
1603      ...  Though the system chooses virtual addresses for
1604      individual processes, it maintains the segments' relative
1605      positions.  Because position-independent code uses relative
1606      addressesing between segments, the difference between
1607      virtual addresses in memory must match the difference
1608      between virtual addresses in the file.  The difference
1609      between the virtual address of any segment in memory and
1610      the corresponding virtual address in the file is thus a
1611      single constant value for any one executable or shared
1612      object in a given process.  This difference is the base
1613      address.  One use of the base address is to relocate the
1614      memory image of the program during dynamic linking.
1615
1616    The same language also appears in Edition 4.0 of the System V
1617    ABI and is left unspecified in some of the earlier editions.  */
1618
1619 static CORE_ADDR
1620 svr4_exec_displacement (void)
1621 {
1622   int found;
1623   /* ENTRY_POINT is a possible function descriptor - before
1624      a call to gdbarch_convert_from_func_ptr_addr.  */
1625   CORE_ADDR entry_point;
1626
1627   if (exec_bfd == NULL)
1628     return 0;
1629
1630   if (target_auxv_search (&current_target, AT_ENTRY, &entry_point) == 1)
1631     return entry_point - bfd_get_start_address (exec_bfd);
1632
1633   return svr4_static_exec_displacement ();
1634 }
1635
1636 /* Relocate the main executable.  This function should be called upon
1637    stopping the inferior process at the entry point to the program. 
1638    The entry point from BFD is compared to the AT_ENTRY of AUXV and if they are
1639    different, the main executable is relocated by the proper amount.  */
1640
1641 static void
1642 svr4_relocate_main_executable (void)
1643 {
1644   CORE_ADDR displacement = svr4_exec_displacement ();
1645
1646   /* Even if DISPLACEMENT is 0 still try to relocate it as this is a new
1647      difference of in-memory vs. in-file addresses and we could already
1648      relocate the executable at this function to improper address before.  */
1649
1650   if (symfile_objfile)
1651     {
1652       struct section_offsets *new_offsets;
1653       int i;
1654
1655       new_offsets = alloca (symfile_objfile->num_sections
1656                             * sizeof (*new_offsets));
1657
1658       for (i = 0; i < symfile_objfile->num_sections; i++)
1659         new_offsets->offsets[i] = displacement;
1660
1661       objfile_relocate (symfile_objfile, new_offsets);
1662     }
1663   else if (exec_bfd)
1664     {
1665       asection *asect;
1666
1667       for (asect = exec_bfd->sections; asect != NULL; asect = asect->next)
1668         exec_set_section_address (bfd_get_filename (exec_bfd), asect->index,
1669                                   (bfd_section_vma (exec_bfd, asect)
1670                                    + displacement));
1671     }
1672 }
1673
1674 /*
1675
1676    GLOBAL FUNCTION
1677
1678    svr4_solib_create_inferior_hook -- shared library startup support
1679
1680    SYNOPSIS
1681
1682    void svr4_solib_create_inferior_hook (int from_tty)
1683
1684    DESCRIPTION
1685
1686    When gdb starts up the inferior, it nurses it along (through the
1687    shell) until it is ready to execute it's first instruction.  At this
1688    point, this function gets called via expansion of the macro
1689    SOLIB_CREATE_INFERIOR_HOOK.
1690
1691    For SunOS executables, this first instruction is typically the
1692    one at "_start", or a similar text label, regardless of whether
1693    the executable is statically or dynamically linked.  The runtime
1694    startup code takes care of dynamically linking in any shared
1695    libraries, once gdb allows the inferior to continue.
1696
1697    For SVR4 executables, this first instruction is either the first
1698    instruction in the dynamic linker (for dynamically linked
1699    executables) or the instruction at "start" for statically linked
1700    executables.  For dynamically linked executables, the system
1701    first exec's /lib/libc.so.N, which contains the dynamic linker,
1702    and starts it running.  The dynamic linker maps in any needed
1703    shared libraries, maps in the actual user executable, and then
1704    jumps to "start" in the user executable.
1705
1706    For both SunOS shared libraries, and SVR4 shared libraries, we
1707    can arrange to cooperate with the dynamic linker to discover the
1708    names of shared libraries that are dynamically linked, and the
1709    base addresses to which they are linked.
1710
1711    This function is responsible for discovering those names and
1712    addresses, and saving sufficient information about them to allow
1713    their symbols to be read at a later time.
1714
1715    FIXME
1716
1717    Between enable_break() and disable_break(), this code does not
1718    properly handle hitting breakpoints which the user might have
1719    set in the startup code or in the dynamic linker itself.  Proper
1720    handling will probably have to wait until the implementation is
1721    changed to use the "breakpoint handler function" method.
1722
1723    Also, what if child has exit()ed?  Must exit loop somehow.
1724  */
1725
1726 static void
1727 svr4_solib_create_inferior_hook (int from_tty)
1728 {
1729   struct inferior *inf;
1730   struct thread_info *tp;
1731   struct svr4_info *info;
1732
1733   info = get_svr4_info ();
1734
1735   /* Relocate the main executable if necessary.  */
1736   if (current_inferior ()->attach_flag == 0)
1737     svr4_relocate_main_executable ();
1738
1739   if (!svr4_have_link_map_offsets ())
1740     return;
1741
1742   if (!enable_break (info, from_tty))
1743     return;
1744
1745 #if defined(_SCO_DS)
1746   /* SCO needs the loop below, other systems should be using the
1747      special shared library breakpoints and the shared library breakpoint
1748      service routine.
1749
1750      Now run the target.  It will eventually hit the breakpoint, at
1751      which point all of the libraries will have been mapped in and we
1752      can go groveling around in the dynamic linker structures to find
1753      out what we need to know about them. */
1754
1755   inf = current_inferior ();
1756   tp = inferior_thread ();
1757
1758   clear_proceed_status ();
1759   inf->stop_soon = STOP_QUIETLY;
1760   tp->stop_signal = TARGET_SIGNAL_0;
1761   do
1762     {
1763       target_resume (pid_to_ptid (-1), 0, tp->stop_signal);
1764       wait_for_inferior (0);
1765     }
1766   while (tp->stop_signal != TARGET_SIGNAL_TRAP);
1767   inf->stop_soon = NO_STOP_QUIETLY;
1768 #endif /* defined(_SCO_DS) */
1769 }
1770
1771 static void
1772 svr4_clear_solib (void)
1773 {
1774   struct svr4_info *info;
1775
1776   info = get_svr4_info ();
1777   info->debug_base = 0;
1778   info->debug_loader_offset_p = 0;
1779   info->debug_loader_offset = 0;
1780   xfree (info->debug_loader_name);
1781   info->debug_loader_name = NULL;
1782 }
1783
1784 static void
1785 svr4_free_so (struct so_list *so)
1786 {
1787   xfree (so->lm_info->lm);
1788   xfree (so->lm_info);
1789 }
1790
1791
1792 /* Clear any bits of ADDR that wouldn't fit in a target-format
1793    data pointer.  "Data pointer" here refers to whatever sort of
1794    address the dynamic linker uses to manage its sections.  At the
1795    moment, we don't support shared libraries on any processors where
1796    code and data pointers are different sizes.
1797
1798    This isn't really the right solution.  What we really need here is
1799    a way to do arithmetic on CORE_ADDR values that respects the
1800    natural pointer/address correspondence.  (For example, on the MIPS,
1801    converting a 32-bit pointer to a 64-bit CORE_ADDR requires you to
1802    sign-extend the value.  There, simply truncating the bits above
1803    gdbarch_ptr_bit, as we do below, is no good.)  This should probably
1804    be a new gdbarch method or something.  */
1805 static CORE_ADDR
1806 svr4_truncate_ptr (CORE_ADDR addr)
1807 {
1808   if (gdbarch_ptr_bit (target_gdbarch) == sizeof (CORE_ADDR) * 8)
1809     /* We don't need to truncate anything, and the bit twiddling below
1810        will fail due to overflow problems.  */
1811     return addr;
1812   else
1813     return addr & (((CORE_ADDR) 1 << gdbarch_ptr_bit (target_gdbarch)) - 1);
1814 }
1815
1816
1817 static void
1818 svr4_relocate_section_addresses (struct so_list *so,
1819                                  struct target_section *sec)
1820 {
1821   sec->addr    = svr4_truncate_ptr (sec->addr    + LM_ADDR_CHECK (so,
1822                                                                   sec->bfd));
1823   sec->endaddr = svr4_truncate_ptr (sec->endaddr + LM_ADDR_CHECK (so,
1824                                                                   sec->bfd));
1825 }
1826 \f
1827
1828 /* Architecture-specific operations.  */
1829
1830 /* Per-architecture data key.  */
1831 static struct gdbarch_data *solib_svr4_data;
1832
1833 struct solib_svr4_ops
1834 {
1835   /* Return a description of the layout of `struct link_map'.  */
1836   struct link_map_offsets *(*fetch_link_map_offsets)(void);
1837 };
1838
1839 /* Return a default for the architecture-specific operations.  */
1840
1841 static void *
1842 solib_svr4_init (struct obstack *obstack)
1843 {
1844   struct solib_svr4_ops *ops;
1845
1846   ops = OBSTACK_ZALLOC (obstack, struct solib_svr4_ops);
1847   ops->fetch_link_map_offsets = NULL;
1848   return ops;
1849 }
1850
1851 /* Set the architecture-specific `struct link_map_offsets' fetcher for
1852    GDBARCH to FLMO.  Also, install SVR4 solib_ops into GDBARCH.  */
1853
1854 void
1855 set_solib_svr4_fetch_link_map_offsets (struct gdbarch *gdbarch,
1856                                        struct link_map_offsets *(*flmo) (void))
1857 {
1858   struct solib_svr4_ops *ops = gdbarch_data (gdbarch, solib_svr4_data);
1859
1860   ops->fetch_link_map_offsets = flmo;
1861
1862   set_solib_ops (gdbarch, &svr4_so_ops);
1863 }
1864
1865 /* Fetch a link_map_offsets structure using the architecture-specific
1866    `struct link_map_offsets' fetcher.  */
1867
1868 static struct link_map_offsets *
1869 svr4_fetch_link_map_offsets (void)
1870 {
1871   struct solib_svr4_ops *ops = gdbarch_data (target_gdbarch, solib_svr4_data);
1872
1873   gdb_assert (ops->fetch_link_map_offsets);
1874   return ops->fetch_link_map_offsets ();
1875 }
1876
1877 /* Return 1 if a link map offset fetcher has been defined, 0 otherwise.  */
1878
1879 static int
1880 svr4_have_link_map_offsets (void)
1881 {
1882   struct solib_svr4_ops *ops = gdbarch_data (target_gdbarch, solib_svr4_data);
1883   return (ops->fetch_link_map_offsets != NULL);
1884 }
1885 \f
1886
1887 /* Most OS'es that have SVR4-style ELF dynamic libraries define a
1888    `struct r_debug' and a `struct link_map' that are binary compatible
1889    with the origional SVR4 implementation.  */
1890
1891 /* Fetch (and possibly build) an appropriate `struct link_map_offsets'
1892    for an ILP32 SVR4 system.  */
1893   
1894 struct link_map_offsets *
1895 svr4_ilp32_fetch_link_map_offsets (void)
1896 {
1897   static struct link_map_offsets lmo;
1898   static struct link_map_offsets *lmp = NULL;
1899
1900   if (lmp == NULL)
1901     {
1902       lmp = &lmo;
1903
1904       lmo.r_version_offset = 0;
1905       lmo.r_version_size = 4;
1906       lmo.r_map_offset = 4;
1907       lmo.r_brk_offset = 8;
1908       lmo.r_ldsomap_offset = 20;
1909
1910       /* Everything we need is in the first 20 bytes.  */
1911       lmo.link_map_size = 20;
1912       lmo.l_addr_offset = 0;
1913       lmo.l_name_offset = 4;
1914       lmo.l_ld_offset = 8;
1915       lmo.l_next_offset = 12;
1916       lmo.l_prev_offset = 16;
1917     }
1918
1919   return lmp;
1920 }
1921
1922 /* Fetch (and possibly build) an appropriate `struct link_map_offsets'
1923    for an LP64 SVR4 system.  */
1924   
1925 struct link_map_offsets *
1926 svr4_lp64_fetch_link_map_offsets (void)
1927 {
1928   static struct link_map_offsets lmo;
1929   static struct link_map_offsets *lmp = NULL;
1930
1931   if (lmp == NULL)
1932     {
1933       lmp = &lmo;
1934
1935       lmo.r_version_offset = 0;
1936       lmo.r_version_size = 4;
1937       lmo.r_map_offset = 8;
1938       lmo.r_brk_offset = 16;
1939       lmo.r_ldsomap_offset = 40;
1940
1941       /* Everything we need is in the first 40 bytes.  */
1942       lmo.link_map_size = 40;
1943       lmo.l_addr_offset = 0;
1944       lmo.l_name_offset = 8;
1945       lmo.l_ld_offset = 16;
1946       lmo.l_next_offset = 24;
1947       lmo.l_prev_offset = 32;
1948     }
1949
1950   return lmp;
1951 }
1952 \f
1953
1954 struct target_so_ops svr4_so_ops;
1955
1956 /* Lookup global symbol for ELF DSOs linked with -Bsymbolic. Those DSOs have a
1957    different rule for symbol lookup.  The lookup begins here in the DSO, not in
1958    the main executable.  */
1959
1960 static struct symbol *
1961 elf_lookup_lib_symbol (const struct objfile *objfile,
1962                        const char *name,
1963                        const char *linkage_name,
1964                        const domain_enum domain)
1965 {
1966   bfd *abfd;
1967
1968   if (objfile == symfile_objfile)
1969     abfd = exec_bfd;
1970   else
1971     {
1972       /* OBJFILE should have been passed as the non-debug one.  */
1973       gdb_assert (objfile->separate_debug_objfile_backlink == NULL);
1974
1975       abfd = objfile->obfd;
1976     }
1977
1978   if (abfd == NULL || scan_dyntag (DT_SYMBOLIC, abfd, NULL) != 1)
1979     return NULL;
1980
1981   return lookup_global_symbol_from_objfile
1982                 (objfile, name, linkage_name, domain);
1983 }
1984
1985 extern initialize_file_ftype _initialize_svr4_solib; /* -Wmissing-prototypes */
1986
1987 void
1988 _initialize_svr4_solib (void)
1989 {
1990   solib_svr4_data = gdbarch_data_register_pre_init (solib_svr4_init);
1991   solib_svr4_pspace_data
1992     = register_program_space_data_with_cleanup (svr4_pspace_data_cleanup);
1993
1994   svr4_so_ops.relocate_section_addresses = svr4_relocate_section_addresses;
1995   svr4_so_ops.free_so = svr4_free_so;
1996   svr4_so_ops.clear_solib = svr4_clear_solib;
1997   svr4_so_ops.solib_create_inferior_hook = svr4_solib_create_inferior_hook;
1998   svr4_so_ops.special_symbol_handling = svr4_special_symbol_handling;
1999   svr4_so_ops.current_sos = svr4_current_sos;
2000   svr4_so_ops.open_symbol_file_object = open_symbol_file_object;
2001   svr4_so_ops.in_dynsym_resolve_code = svr4_in_dynsym_resolve_code;
2002   svr4_so_ops.bfd_open = solib_bfd_open;
2003   svr4_so_ops.lookup_lib_global_symbol = elf_lookup_lib_symbol;
2004   svr4_so_ops.same = svr4_same;
2005   svr4_so_ops.keep_data_in_core = svr4_keep_data_in_core;
2006 }