OSDN Git Service

Replace free() with xfree().
[pf3gnuchains/pf3gnuchains4x.git] / gdb / solib-svr4.c
1 /* Handle SunOS and SVR4 shared libraries for GDB, the GNU Debugger.
2    Copyright 1990, 91, 92, 93, 94, 95, 96, 98, 1999, 2000
3    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 2 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, write to the Free Software
19    Foundation, Inc., 59 Temple Place - Suite 330,
20    Boston, MA 02111-1307, USA.  */
21
22 #define _SYSCALL32      /* for Sparc64 cross Sparc32 */
23 #include "defs.h"
24
25
26 #include <sys/types.h>
27 #include <signal.h>
28 #include "gdb_string.h"
29 #include <sys/param.h>
30 #include <fcntl.h>
31
32 #ifndef SVR4_SHARED_LIBS
33  /* SunOS shared libs need the nlist structure.  */
34 #include <a.out.h>
35 #else
36 #include "elf/external.h"
37 #endif
38
39 #ifdef HAVE_LINK_H
40 #include <link.h>
41 #endif
42
43 #include "symtab.h"
44 #include "bfd.h"
45 #include "symfile.h"
46 #include "objfiles.h"
47 #include "gdbcore.h"
48 #include "command.h"
49 #include "target.h"
50 #include "frame.h"
51 #include "gdb_regex.h"
52 #include "inferior.h"
53 #include "environ.h"
54 #include "language.h"
55 #include "gdbcmd.h"
56
57 #include "solist.h"
58 #include "solib-svr4.h"
59
60 /* Link map info to include in an allocated so_list entry */
61
62 struct lm_info
63   {
64     /* Pointer to copy of link map from inferior.  The type is char *
65        rather than void *, so that we may use byte offsets to find the
66        various fields without the need for a cast.  */
67     char *lm;
68   };
69
70 /* On SVR4 systems, a list of symbols in the dynamic linker where
71    GDB can try to place a breakpoint to monitor shared library
72    events.
73
74    If none of these symbols are found, or other errors occur, then
75    SVR4 systems will fall back to using a symbol as the "startup
76    mapping complete" breakpoint address.  */
77
78 #ifdef SVR4_SHARED_LIBS
79 static char *solib_break_names[] =
80 {
81   "r_debug_state",
82   "_r_debug_state",
83   "_dl_debug_state",
84   "rtld_db_dlactivity",
85   NULL
86 };
87 #endif
88
89 #define BKPT_AT_SYMBOL 1
90
91 #if defined (BKPT_AT_SYMBOL) && defined (SVR4_SHARED_LIBS)
92 static char *bkpt_names[] =
93 {
94 #ifdef SOLIB_BKPT_NAME
95   SOLIB_BKPT_NAME,              /* Prefer configured name if it exists. */
96 #endif
97   "_start",
98   "main",
99   NULL
100 };
101 #endif
102
103 /* Symbols which are used to locate the base of the link map structures. */
104
105 #ifndef SVR4_SHARED_LIBS
106 static char *debug_base_symbols[] =
107 {
108   "_DYNAMIC",
109   "_DYNAMIC__MGC",
110   NULL
111 };
112 #endif
113
114 static char *main_name_list[] =
115 {
116   "main_$main",
117   NULL
118 };
119
120
121 /* Fetch (and possibly build) an appropriate link_map_offsets structure
122    for native targets using struct definitions from link.h.  */
123
124 struct link_map_offsets *
125 default_svr4_fetch_link_map_offsets (void)
126 {
127 #ifdef HAVE_LINK_H
128   static struct link_map_offsets lmo;
129   static struct link_map_offsets *lmp = 0;
130 #if defined (HAVE_STRUCT_LINK_MAP32)
131   static struct link_map_offsets lmo32;
132   static struct link_map_offsets *lmp32 = 0;
133 #endif
134
135 #ifndef offsetof
136 #define offsetof(TYPE, MEMBER) ((unsigned long) &((TYPE *)0)->MEMBER)
137 #endif
138 #define fieldsize(TYPE, MEMBER) (sizeof (((TYPE *)0)->MEMBER))
139
140   if (lmp == 0)
141     {
142       lmp = &lmo;
143
144 #ifdef SVR4_SHARED_LIBS
145       lmo.r_debug_size = sizeof (struct r_debug);
146
147       lmo.r_map_offset = offsetof (struct r_debug, r_map);
148       lmo.r_map_size = fieldsize (struct r_debug, r_map);
149
150       lmo.link_map_size = sizeof (struct link_map);
151
152       lmo.l_addr_offset = offsetof (struct link_map, l_addr);
153       lmo.l_addr_size = fieldsize (struct link_map, l_addr);
154
155       lmo.l_next_offset = offsetof (struct link_map, l_next);
156       lmo.l_next_size = fieldsize (struct link_map, l_next);
157
158       lmo.l_prev_offset = offsetof (struct link_map, l_prev);
159       lmo.l_prev_size = fieldsize (struct link_map, l_prev);
160
161       lmo.l_name_offset = offsetof (struct link_map, l_name);
162       lmo.l_name_size = fieldsize (struct link_map, l_name);
163 #else /* !SVR4_SHARED_LIBS */
164       lmo.link_map_size = sizeof (struct link_map);
165
166       lmo.l_addr_offset = offsetof (struct link_map, lm_addr);
167       lmo.l_addr_size = fieldsize (struct link_map, lm_addr);
168
169       lmo.l_next_offset = offsetof (struct link_map, lm_next);
170       lmo.l_next_size = fieldsize (struct link_map, lm_next);
171
172       lmo.l_name_offset = offsetof (struct link_map, lm_name);
173       lmo.l_name_size = fieldsize (struct link_map, lm_name);
174 #endif /* SVR4_SHARED_LIBS */
175     }
176
177 #if defined (HAVE_STRUCT_LINK_MAP32)
178   if (lmp32 == 0)
179     {
180       lmp32 = &lmo32;
181
182       lmo32.r_debug_size = sizeof (struct r_debug32);
183
184       lmo32.r_map_offset = offsetof (struct r_debug32, r_map);
185       lmo32.r_map_size = fieldsize (struct r_debug32, r_map);
186
187       lmo32.link_map_size = sizeof (struct link_map32);
188
189       lmo32.l_addr_offset = offsetof (struct link_map32, l_addr);
190       lmo32.l_addr_size = fieldsize (struct link_map32, l_addr);
191
192       lmo32.l_next_offset = offsetof (struct link_map32, l_next);
193       lmo32.l_next_size = fieldsize (struct link_map32, l_next);
194
195       lmo32.l_prev_offset = offsetof (struct link_map32, l_prev);
196       lmo32.l_prev_size = fieldsize (struct link_map32, l_prev);
197
198       lmo32.l_name_offset = offsetof (struct link_map32, l_name);
199       lmo32.l_name_size = fieldsize (struct link_map32, l_name);
200     }
201 #endif /* defined (HAVE_STRUCT_LINK_MAP32) */
202
203 #if defined (HAVE_STRUCT_LINK_MAP32)
204   if (bfd_get_arch_size (exec_bfd) == 32)
205     return lmp32;
206   else
207 #endif
208     return lmp;
209
210 #else
211
212   internal_error ("default_svr4_fetch_link_map_offsets called without HAVE_LINK_H defined.");
213   return 0;
214
215 #endif /* HAVE_LINK_H */
216 }
217
218 /* Macro to extract an address from a solib structure.
219    When GDB is configured for some 32-bit targets (e.g. Solaris 2.7
220    sparc), BFD is configured to handle 64-bit targets, so CORE_ADDR is
221    64 bits.  We have to extract only the significant bits of addresses
222    to get the right address when accessing the core file BFD.  */
223
224 #define SOLIB_EXTRACT_ADDRESS(MEMBER) \
225         extract_address (&(MEMBER), sizeof (MEMBER))
226
227 /* local data declarations */
228
229 #ifndef SVR4_SHARED_LIBS
230
231 /* NOTE: converted the macros LM_ADDR, LM_NEXT, LM_NAME and
232    IGNORE_FIRST_LINK_MAP_ENTRY into functions (see below).
233    MVS, June 2000  */
234
235 static struct link_dynamic dynamic_copy;
236 static struct link_dynamic_2 ld_2_copy;
237 static struct ld_debug debug_copy;
238 static CORE_ADDR debug_addr;
239 static CORE_ADDR flag_addr;
240
241 #endif /* !SVR4_SHARED_LIBS */
242
243 /* link map access functions */
244
245 static CORE_ADDR
246 LM_ADDR (struct so_list *so)
247 {
248   struct link_map_offsets *lmo = SVR4_FETCH_LINK_MAP_OFFSETS ();
249
250   return extract_address (so->lm_info->lm + lmo->l_addr_offset, lmo->l_addr_size);
251 }
252
253 static CORE_ADDR
254 LM_NEXT (struct so_list *so)
255 {
256   struct link_map_offsets *lmo = SVR4_FETCH_LINK_MAP_OFFSETS ();
257
258   return extract_address (so->lm_info->lm + lmo->l_next_offset, lmo->l_next_size);
259 }
260
261 static CORE_ADDR
262 LM_NAME (struct so_list *so)
263 {
264   struct link_map_offsets *lmo = SVR4_FETCH_LINK_MAP_OFFSETS ();
265
266   return extract_address (so->lm_info->lm + lmo->l_name_offset, lmo->l_name_size);
267 }
268
269 #ifndef SVR4_SHARED_LIBS
270
271 static int 
272 IGNORE_FIRST_LINK_MAP_ENTRY (struct so_list *so)
273 {
274   return 0;
275 }
276
277 #else /* SVR4_SHARED_LIBS */
278
279 static int
280 IGNORE_FIRST_LINK_MAP_ENTRY (struct so_list *so)
281 {
282   struct link_map_offsets *lmo = SVR4_FETCH_LINK_MAP_OFFSETS ();
283
284   return extract_address (so->lm_info->lm + lmo->l_prev_offset,
285                           lmo->l_prev_size) == 0;
286 }
287
288 #endif /* !SVR4_SHARED_LIBS */
289
290 static CORE_ADDR debug_base;    /* Base of dynamic linker structures */
291 static CORE_ADDR breakpoint_addr;       /* Address where end bkpt is set */
292
293 /* Local function prototypes */
294
295 static int match_main (char *);
296
297 #ifndef SVR4_SHARED_LIBS
298
299 /* Allocate the runtime common object file.  */
300
301 static void
302 allocate_rt_common_objfile (void)
303 {
304   struct objfile *objfile;
305   struct objfile *last_one;
306
307   objfile = (struct objfile *) xmalloc (sizeof (struct objfile));
308   memset (objfile, 0, sizeof (struct objfile));
309   objfile->md = NULL;
310   obstack_specify_allocation (&objfile->psymbol_cache.cache, 0, 0,
311                               xmalloc, xfree);
312   obstack_specify_allocation (&objfile->psymbol_obstack, 0, 0, xmalloc,
313                               xfree);
314   obstack_specify_allocation (&objfile->symbol_obstack, 0, 0, xmalloc,
315                               xfree);
316   obstack_specify_allocation (&objfile->type_obstack, 0, 0, xmalloc,
317                               xfree);
318   objfile->name = mstrsave (objfile->md, "rt_common");
319
320   /* Add this file onto the tail of the linked list of other such files. */
321
322   objfile->next = NULL;
323   if (object_files == NULL)
324     object_files = objfile;
325   else
326     {
327       for (last_one = object_files;
328            last_one->next;
329            last_one = last_one->next);
330       last_one->next = objfile;
331     }
332
333   rt_common_objfile = objfile;
334 }
335
336 /* Read all dynamically loaded common symbol definitions from the inferior
337    and put them into the minimal symbol table for the runtime common
338    objfile.  */
339
340 static void
341 solib_add_common_symbols (CORE_ADDR rtc_symp)
342 {
343   struct rtc_symb inferior_rtc_symb;
344   struct nlist inferior_rtc_nlist;
345   int len;
346   char *name;
347
348   /* Remove any runtime common symbols from previous runs.  */
349
350   if (rt_common_objfile != NULL && rt_common_objfile->minimal_symbol_count)
351     {
352       obstack_free (&rt_common_objfile->symbol_obstack, 0);
353       obstack_specify_allocation (&rt_common_objfile->symbol_obstack, 0, 0,
354                                   xmalloc, xfree);
355       rt_common_objfile->minimal_symbol_count = 0;
356       rt_common_objfile->msymbols = NULL;
357     }
358
359   init_minimal_symbol_collection ();
360   make_cleanup_discard_minimal_symbols ();
361
362   while (rtc_symp)
363     {
364       read_memory (rtc_symp,
365                    (char *) &inferior_rtc_symb,
366                    sizeof (inferior_rtc_symb));
367       read_memory (SOLIB_EXTRACT_ADDRESS (inferior_rtc_symb.rtc_sp),
368                    (char *) &inferior_rtc_nlist,
369                    sizeof (inferior_rtc_nlist));
370       if (inferior_rtc_nlist.n_type == N_COMM)
371         {
372           /* FIXME: The length of the symbol name is not available, but in the
373              current implementation the common symbol is allocated immediately
374              behind the name of the symbol. */
375           len = inferior_rtc_nlist.n_value - inferior_rtc_nlist.n_un.n_strx;
376
377           name = xmalloc (len);
378           read_memory (SOLIB_EXTRACT_ADDRESS (inferior_rtc_nlist.n_un.n_name),
379                        name, len);
380
381           /* Allocate the runtime common objfile if necessary. */
382           if (rt_common_objfile == NULL)
383             allocate_rt_common_objfile ();
384
385           prim_record_minimal_symbol (name, inferior_rtc_nlist.n_value,
386                                       mst_bss, rt_common_objfile);
387           xfree (name);
388         }
389       rtc_symp = SOLIB_EXTRACT_ADDRESS (inferior_rtc_symb.rtc_next);
390     }
391
392   /* Install any minimal symbols that have been collected as the current
393      minimal symbols for the runtime common objfile.  */
394
395   install_minimal_symbols (rt_common_objfile);
396 }
397
398 #endif /* SVR4_SHARED_LIBS */
399
400
401 #ifdef SVR4_SHARED_LIBS
402
403 static CORE_ADDR bfd_lookup_symbol (bfd *, char *);
404
405 /*
406
407    LOCAL FUNCTION
408
409    bfd_lookup_symbol -- lookup the value for a specific symbol
410
411    SYNOPSIS
412
413    CORE_ADDR bfd_lookup_symbol (bfd *abfd, char *symname)
414
415    DESCRIPTION
416
417    An expensive way to lookup the value of a single symbol for
418    bfd's that are only temporary anyway.  This is used by the
419    shared library support to find the address of the debugger
420    interface structures in the shared library.
421
422    Note that 0 is specifically allowed as an error return (no
423    such symbol).
424  */
425
426 static CORE_ADDR
427 bfd_lookup_symbol (bfd *abfd, char *symname)
428 {
429   unsigned int storage_needed;
430   asymbol *sym;
431   asymbol **symbol_table;
432   unsigned int number_of_symbols;
433   unsigned int i;
434   struct cleanup *back_to;
435   CORE_ADDR symaddr = 0;
436
437   storage_needed = bfd_get_symtab_upper_bound (abfd);
438
439   if (storage_needed > 0)
440     {
441       symbol_table = (asymbol **) xmalloc (storage_needed);
442       back_to = make_cleanup (xfree, (PTR) symbol_table);
443       number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table);
444
445       for (i = 0; i < number_of_symbols; i++)
446         {
447           sym = *symbol_table++;
448           if (STREQ (sym->name, symname))
449             {
450               /* Bfd symbols are section relative. */
451               symaddr = sym->value + sym->section->vma;
452               break;
453             }
454         }
455       do_cleanups (back_to);
456     }
457
458   if (symaddr)
459     return symaddr;
460
461   /* On FreeBSD, the dynamic linker is stripped by default.  So we'll
462      have to check the dynamic string table too.  */
463
464   storage_needed = bfd_get_dynamic_symtab_upper_bound (abfd);
465
466   if (storage_needed > 0)
467     {
468       symbol_table = (asymbol **) xmalloc (storage_needed);
469       back_to = make_cleanup (xfree, (PTR) symbol_table);
470       number_of_symbols = bfd_canonicalize_dynamic_symtab (abfd, symbol_table);
471
472       for (i = 0; i < number_of_symbols; i++)
473         {
474           sym = *symbol_table++;
475           if (STREQ (sym->name, symname))
476             {
477               /* Bfd symbols are section relative. */
478               symaddr = sym->value + sym->section->vma;
479               break;
480             }
481         }
482       do_cleanups (back_to);
483     }
484
485   return symaddr;
486 }
487
488 #ifdef HANDLE_SVR4_EXEC_EMULATORS
489
490 /*
491    Solaris BCP (the part of Solaris which allows it to run SunOS4
492    a.out files) throws in another wrinkle. Solaris does not fill
493    in the usual a.out link map structures when running BCP programs,
494    the only way to get at them is via groping around in the dynamic
495    linker.
496    The dynamic linker and it's structures are located in the shared
497    C library, which gets run as the executable's "interpreter" by
498    the kernel.
499
500    Note that we can assume nothing about the process state at the time
501    we need to find these structures.  We may be stopped on the first
502    instruction of the interpreter (C shared library), the first
503    instruction of the executable itself, or somewhere else entirely
504    (if we attached to the process for example).
505  */
506
507 static char *debug_base_symbols[] =
508 {
509   "r_debug",                    /* Solaris 2.3 */
510   "_r_debug",                   /* Solaris 2.1, 2.2 */
511   NULL
512 };
513
514 static int look_for_base (int, CORE_ADDR);
515
516 /*
517
518    LOCAL FUNCTION
519
520    look_for_base -- examine file for each mapped address segment
521
522    SYNOPSYS
523
524    static int look_for_base (int fd, CORE_ADDR baseaddr)
525
526    DESCRIPTION
527
528    This function is passed to proc_iterate_over_mappings, which
529    causes it to get called once for each mapped address space, with
530    an open file descriptor for the file mapped to that space, and the
531    base address of that mapped space.
532
533    Our job is to find the debug base symbol in the file that this
534    fd is open on, if it exists, and if so, initialize the dynamic
535    linker structure base address debug_base.
536
537    Note that this is a computationally expensive proposition, since
538    we basically have to open a bfd on every call, so we specifically
539    avoid opening the exec file.
540  */
541
542 static int
543 look_for_base (int fd, CORE_ADDR baseaddr)
544 {
545   bfd *interp_bfd;
546   CORE_ADDR address = 0;
547   char **symbolp;
548
549   /* If the fd is -1, then there is no file that corresponds to this
550      mapped memory segment, so skip it.  Also, if the fd corresponds
551      to the exec file, skip it as well. */
552
553   if (fd == -1
554       || (exec_bfd != NULL
555           && fdmatch (fileno ((FILE *) (exec_bfd->iostream)), fd)))
556     {
557       return (0);
558     }
559
560   /* Try to open whatever random file this fd corresponds to.  Note that
561      we have no way currently to find the filename.  Don't gripe about
562      any problems we might have, just fail. */
563
564   if ((interp_bfd = bfd_fdopenr ("unnamed", gnutarget, fd)) == NULL)
565     {
566       return (0);
567     }
568   if (!bfd_check_format (interp_bfd, bfd_object))
569     {
570       /* FIXME-leak: on failure, might not free all memory associated with
571          interp_bfd.  */
572       bfd_close (interp_bfd);
573       return (0);
574     }
575
576   /* Now try to find our debug base symbol in this file, which we at
577      least know to be a valid ELF executable or shared library. */
578
579   for (symbolp = debug_base_symbols; *symbolp != NULL; symbolp++)
580     {
581       address = bfd_lookup_symbol (interp_bfd, *symbolp);
582       if (address != 0)
583         {
584           break;
585         }
586     }
587   if (address == 0)
588     {
589       /* FIXME-leak: on failure, might not free all memory associated with
590          interp_bfd.  */
591       bfd_close (interp_bfd);
592       return (0);
593     }
594
595   /* Eureka!  We found the symbol.  But now we may need to relocate it
596      by the base address.  If the symbol's value is less than the base
597      address of the shared library, then it hasn't yet been relocated
598      by the dynamic linker, and we have to do it ourself.  FIXME: Note
599      that we make the assumption that the first segment that corresponds
600      to the shared library has the base address to which the library
601      was relocated. */
602
603   if (address < baseaddr)
604     {
605       address += baseaddr;
606     }
607   debug_base = address;
608   /* FIXME-leak: on failure, might not free all memory associated with
609      interp_bfd.  */
610   bfd_close (interp_bfd);
611   return (1);
612 }
613 #endif /* HANDLE_SVR4_EXEC_EMULATORS */
614
615 /*
616
617    LOCAL FUNCTION
618
619    elf_locate_base -- locate the base address of dynamic linker structs
620    for SVR4 elf targets.
621
622    SYNOPSIS
623
624    CORE_ADDR elf_locate_base (void)
625
626    DESCRIPTION
627
628    For SVR4 elf targets the address of the dynamic linker's runtime
629    structure is contained within the dynamic info section in the
630    executable file.  The dynamic section is also mapped into the
631    inferior address space.  Because the runtime loader fills in the
632    real address before starting the inferior, we have to read in the
633    dynamic info section from the inferior address space.
634    If there are any errors while trying to find the address, we
635    silently return 0, otherwise the found address is returned.
636
637  */
638
639 static CORE_ADDR
640 elf_locate_base (void)
641 {
642   sec_ptr dyninfo_sect;
643   int dyninfo_sect_size;
644   CORE_ADDR dyninfo_addr;
645   char *buf;
646   char *bufend;
647   int arch_size;
648
649   /* Find the start address of the .dynamic section.  */
650   dyninfo_sect = bfd_get_section_by_name (exec_bfd, ".dynamic");
651   if (dyninfo_sect == NULL)
652     return 0;
653   dyninfo_addr = bfd_section_vma (exec_bfd, dyninfo_sect);
654
655   /* Read in .dynamic section, silently ignore errors.  */
656   dyninfo_sect_size = bfd_section_size (exec_bfd, dyninfo_sect);
657   buf = alloca (dyninfo_sect_size);
658   if (target_read_memory (dyninfo_addr, buf, dyninfo_sect_size))
659     return 0;
660
661   /* Find the DT_DEBUG entry in the the .dynamic section.
662      For mips elf we look for DT_MIPS_RLD_MAP, mips elf apparently has
663      no DT_DEBUG entries.  */
664
665   arch_size = bfd_get_arch_size (exec_bfd);
666   if (arch_size == -1)  /* failure */
667     return 0;
668
669   if (arch_size == 32)
670     { /* 32-bit elf */
671       for (bufend = buf + dyninfo_sect_size;
672            buf < bufend;
673            buf += sizeof (Elf32_External_Dyn))
674         {
675           Elf32_External_Dyn *x_dynp = (Elf32_External_Dyn *) buf;
676           long dyn_tag;
677           CORE_ADDR dyn_ptr;
678
679           dyn_tag = bfd_h_get_32 (exec_bfd, (bfd_byte *) x_dynp->d_tag);
680           if (dyn_tag == DT_NULL)
681             break;
682           else if (dyn_tag == DT_DEBUG)
683             {
684               dyn_ptr = bfd_h_get_32 (exec_bfd, 
685                                       (bfd_byte *) x_dynp->d_un.d_ptr);
686               return dyn_ptr;
687             }
688 #ifdef DT_MIPS_RLD_MAP
689           else if (dyn_tag == DT_MIPS_RLD_MAP)
690             {
691               char *pbuf;
692
693               pbuf = alloca (TARGET_PTR_BIT / HOST_CHAR_BIT);
694               /* DT_MIPS_RLD_MAP contains a pointer to the address
695                  of the dynamic link structure.  */
696               dyn_ptr = bfd_h_get_32 (exec_bfd, 
697                                       (bfd_byte *) x_dynp->d_un.d_ptr);
698               if (target_read_memory (dyn_ptr, pbuf, sizeof (pbuf)))
699                 return 0;
700               return extract_unsigned_integer (pbuf, sizeof (pbuf));
701             }
702 #endif
703         }
704     }
705   else /* 64-bit elf */
706     {
707       for (bufend = buf + dyninfo_sect_size;
708            buf < bufend;
709            buf += sizeof (Elf64_External_Dyn))
710         {
711           Elf64_External_Dyn *x_dynp = (Elf64_External_Dyn *) buf;
712           long dyn_tag;
713           CORE_ADDR dyn_ptr;
714
715           dyn_tag = bfd_h_get_64 (exec_bfd, (bfd_byte *) x_dynp->d_tag);
716           if (dyn_tag == DT_NULL)
717             break;
718           else if (dyn_tag == DT_DEBUG)
719             {
720               dyn_ptr = bfd_h_get_64 (exec_bfd, 
721                                       (bfd_byte *) x_dynp->d_un.d_ptr);
722               return dyn_ptr;
723             }
724         }
725     }
726
727   /* DT_DEBUG entry not found.  */
728   return 0;
729 }
730
731 #endif /* SVR4_SHARED_LIBS */
732
733 /*
734
735    LOCAL FUNCTION
736
737    locate_base -- locate the base address of dynamic linker structs
738
739    SYNOPSIS
740
741    CORE_ADDR locate_base (void)
742
743    DESCRIPTION
744
745    For both the SunOS and SVR4 shared library implementations, if the
746    inferior executable has been linked dynamically, there is a single
747    address somewhere in the inferior's data space which is the key to
748    locating all of the dynamic linker's runtime structures.  This
749    address is the value of the debug base symbol.  The job of this
750    function is to find and return that address, or to return 0 if there
751    is no such address (the executable is statically linked for example).
752
753    For SunOS, the job is almost trivial, since the dynamic linker and
754    all of it's structures are statically linked to the executable at
755    link time.  Thus the symbol for the address we are looking for has
756    already been added to the minimal symbol table for the executable's
757    objfile at the time the symbol file's symbols were read, and all we
758    have to do is look it up there.  Note that we explicitly do NOT want
759    to find the copies in the shared library.
760
761    The SVR4 version is a bit more complicated because the address
762    is contained somewhere in the dynamic info section.  We have to go
763    to a lot more work to discover the address of the debug base symbol.
764    Because of this complexity, we cache the value we find and return that
765    value on subsequent invocations.  Note there is no copy in the
766    executable symbol tables.
767
768  */
769
770 static CORE_ADDR
771 locate_base (void)
772 {
773
774 #ifndef SVR4_SHARED_LIBS
775
776   struct minimal_symbol *msymbol;
777   CORE_ADDR address = 0;
778   char **symbolp;
779
780   /* For SunOS, we want to limit the search for the debug base symbol to the
781      executable being debugged, since there is a duplicate named symbol in the
782      shared library.  We don't want the shared library versions. */
783
784   for (symbolp = debug_base_symbols; *symbolp != NULL; symbolp++)
785     {
786       msymbol = lookup_minimal_symbol (*symbolp, NULL, symfile_objfile);
787       if ((msymbol != NULL) && (SYMBOL_VALUE_ADDRESS (msymbol) != 0))
788         {
789           address = SYMBOL_VALUE_ADDRESS (msymbol);
790           return (address);
791         }
792     }
793   return (0);
794
795 #else /* SVR4_SHARED_LIBS */
796
797   /* Check to see if we have a currently valid address, and if so, avoid
798      doing all this work again and just return the cached address.  If
799      we have no cached address, try to locate it in the dynamic info
800      section for ELF executables.  */
801
802   if (debug_base == 0)
803     {
804       if (exec_bfd != NULL
805           && bfd_get_flavour (exec_bfd) == bfd_target_elf_flavour)
806         debug_base = elf_locate_base ();
807 #ifdef HANDLE_SVR4_EXEC_EMULATORS
808       /* Try it the hard way for emulated executables.  */
809       else if (inferior_pid != 0 && target_has_execution)
810         proc_iterate_over_mappings (look_for_base);
811 #endif
812     }
813   return (debug_base);
814
815 #endif /* !SVR4_SHARED_LIBS */
816
817 }
818
819 /*
820
821    LOCAL FUNCTION
822
823    first_link_map_member -- locate first member in dynamic linker's map
824
825    SYNOPSIS
826
827    static CORE_ADDR first_link_map_member (void)
828
829    DESCRIPTION
830
831    Find the first element in the inferior's dynamic link map, and
832    return its address in the inferior.  This function doesn't copy the
833    link map entry itself into our address space; current_sos actually
834    does the reading.  */
835
836 static CORE_ADDR
837 first_link_map_member (void)
838 {
839   CORE_ADDR lm = 0;
840
841 #ifndef SVR4_SHARED_LIBS
842
843   read_memory (debug_base, (char *) &dynamic_copy, sizeof (dynamic_copy));
844   if (dynamic_copy.ld_version >= 2)
845     {
846       /* It is a version that we can deal with, so read in the secondary
847          structure and find the address of the link map list from it. */
848       read_memory (SOLIB_EXTRACT_ADDRESS (dynamic_copy.ld_un.ld_2),
849                    (char *) &ld_2_copy, sizeof (struct link_dynamic_2));
850       lm = SOLIB_EXTRACT_ADDRESS (ld_2_copy.ld_loaded);
851     }
852
853 #else /* SVR4_SHARED_LIBS */
854   struct link_map_offsets *lmo = SVR4_FETCH_LINK_MAP_OFFSETS ();
855   char *r_map_buf = xmalloc (lmo->r_map_size);
856   struct cleanup *cleanups = make_cleanup (xfree, r_map_buf);
857
858   read_memory (debug_base + lmo->r_map_offset, r_map_buf, lmo->r_map_size);
859
860   lm = extract_address (r_map_buf, lmo->r_map_size);
861
862   /* FIXME:  Perhaps we should validate the info somehow, perhaps by
863      checking r_version for a known version number, or r_state for
864      RT_CONSISTENT. */
865
866   do_cleanups (cleanups);
867
868 #endif /* !SVR4_SHARED_LIBS */
869
870   return (lm);
871 }
872
873 #ifdef SVR4_SHARED_LIBS
874 /*
875
876   LOCAL FUNCTION
877
878   open_symbol_file_object
879
880   SYNOPSIS
881
882   void open_symbol_file_object (void *from_tty)
883
884   DESCRIPTION
885
886   If no open symbol file, attempt to locate and open the main symbol
887   file.  On SVR4 systems, this is the first link map entry.  If its
888   name is here, we can open it.  Useful when attaching to a process
889   without first loading its symbol file.
890
891   If FROM_TTYP dereferences to a non-zero integer, allow messages to
892   be printed.  This parameter is a pointer rather than an int because
893   open_symbol_file_object() is called via catch_errors() and
894   catch_errors() requires a pointer argument. */
895
896 static int
897 open_symbol_file_object (void *from_ttyp)
898 {
899   CORE_ADDR lm, l_name;
900   char *filename;
901   int errcode;
902   int from_tty = *(int *)from_ttyp;
903   struct link_map_offsets *lmo = SVR4_FETCH_LINK_MAP_OFFSETS ();
904   char *l_name_buf = xmalloc (lmo->l_name_size);
905   struct cleanup *cleanups = make_cleanup (xfree, l_name_buf);
906
907   if (symfile_objfile)
908     if (!query ("Attempt to reload symbols from process? "))
909       return 0;
910
911   if ((debug_base = locate_base ()) == 0)
912     return 0;   /* failed somehow... */
913
914   /* First link map member should be the executable.  */
915   if ((lm = first_link_map_member ()) == 0)
916     return 0;   /* failed somehow... */
917
918   /* Read address of name from target memory to GDB.  */
919   read_memory (lm + lmo->l_name_offset, l_name_buf, lmo->l_name_size);
920
921   /* Convert the address to host format.  */
922   l_name = extract_address (l_name_buf, lmo->l_name_size);
923
924   /* Free l_name_buf.  */
925   do_cleanups (cleanups);
926
927   if (l_name == 0)
928     return 0;           /* No filename.  */
929
930   /* Now fetch the filename from target memory.  */
931   target_read_string (l_name, &filename, SO_NAME_MAX_PATH_SIZE - 1, &errcode);
932
933   if (errcode)
934     {
935       warning ("failed to read exec filename from attached file: %s",
936                safe_strerror (errcode));
937       return 0;
938     }
939
940   make_cleanup (xfree, filename);
941   /* Have a pathname: read the symbol file.  */
942   symbol_file_command (filename, from_tty);
943
944   return 1;
945 }
946 #else
947
948 static int
949 open_symbol_file_object (int *from_ttyp)
950 {
951   return 1;
952 }
953
954 #endif /* SVR4_SHARED_LIBS */
955
956
957 /* LOCAL FUNCTION
958
959    current_sos -- build a list of currently loaded shared objects
960
961    SYNOPSIS
962
963    struct so_list *current_sos ()
964
965    DESCRIPTION
966
967    Build a list of `struct so_list' objects describing the shared
968    objects currently loaded in the inferior.  This list does not
969    include an entry for the main executable file.
970
971    Note that we only gather information directly available from the
972    inferior --- we don't examine any of the shared library files
973    themselves.  The declaration of `struct so_list' says which fields
974    we provide values for.  */
975
976 static struct so_list *
977 svr4_current_sos (void)
978 {
979   CORE_ADDR lm;
980   struct so_list *head = 0;
981   struct so_list **link_ptr = &head;
982
983   /* Make sure we've looked up the inferior's dynamic linker's base
984      structure.  */
985   if (! debug_base)
986     {
987       debug_base = locate_base ();
988
989       /* If we can't find the dynamic linker's base structure, this
990          must not be a dynamically linked executable.  Hmm.  */
991       if (! debug_base)
992         return 0;
993     }
994
995   /* Walk the inferior's link map list, and build our list of
996      `struct so_list' nodes.  */
997   lm = first_link_map_member ();  
998   while (lm)
999     {
1000       struct link_map_offsets *lmo = SVR4_FETCH_LINK_MAP_OFFSETS ();
1001       struct so_list *new
1002         = (struct so_list *) xmalloc (sizeof (struct so_list));
1003       struct cleanup *old_chain = make_cleanup (xfree, new);
1004
1005       memset (new, 0, sizeof (*new));
1006
1007       new->lm_info = xmalloc (sizeof (struct lm_info));
1008       make_cleanup (xfree, new->lm_info);
1009
1010       new->lm_info->lm = xmalloc (lmo->link_map_size);
1011       make_cleanup (xfree, new->lm_info->lm);
1012       memset (new->lm_info->lm, 0, lmo->link_map_size);
1013
1014       read_memory (lm, new->lm_info->lm, lmo->link_map_size);
1015
1016       lm = LM_NEXT (new);
1017
1018       /* For SVR4 versions, the first entry in the link map is for the
1019          inferior executable, so we must ignore it.  For some versions of
1020          SVR4, it has no name.  For others (Solaris 2.3 for example), it
1021          does have a name, so we can no longer use a missing name to
1022          decide when to ignore it. */
1023       if (IGNORE_FIRST_LINK_MAP_ENTRY (new))
1024         free_so (new);
1025       else
1026         {
1027           int errcode;
1028           char *buffer;
1029
1030           /* Extract this shared object's name.  */
1031           target_read_string (LM_NAME (new), &buffer,
1032                               SO_NAME_MAX_PATH_SIZE - 1, &errcode);
1033           if (errcode != 0)
1034             {
1035               warning ("current_sos: Can't read pathname for load map: %s\n",
1036                        safe_strerror (errcode));
1037             }
1038           else
1039             {
1040               strncpy (new->so_name, buffer, SO_NAME_MAX_PATH_SIZE - 1);
1041               new->so_name[SO_NAME_MAX_PATH_SIZE - 1] = '\0';
1042               xfree (buffer);
1043               strcpy (new->so_original_name, new->so_name);
1044             }
1045
1046           /* If this entry has no name, or its name matches the name
1047              for the main executable, don't include it in the list.  */
1048           if (! new->so_name[0]
1049               || match_main (new->so_name))
1050             free_so (new);
1051           else
1052             {
1053               new->next = 0;
1054               *link_ptr = new;
1055               link_ptr = &new->next;
1056             }
1057         }
1058
1059       discard_cleanups (old_chain);
1060     }
1061
1062   return head;
1063 }
1064
1065
1066 /* On some systems, the only way to recognize the link map entry for
1067    the main executable file is by looking at its name.  Return
1068    non-zero iff SONAME matches one of the known main executable names.  */
1069
1070 static int
1071 match_main (char *soname)
1072 {
1073   char **mainp;
1074
1075   for (mainp = main_name_list; *mainp != NULL; mainp++)
1076     {
1077       if (strcmp (soname, *mainp) == 0)
1078         return (1);
1079     }
1080
1081   return (0);
1082 }
1083
1084
1085 #ifdef SVR4_SHARED_LIBS
1086
1087 /* Return 1 if PC lies in the dynamic symbol resolution code of the
1088    SVR4 run time loader.  */
1089
1090 static CORE_ADDR interp_text_sect_low;
1091 static CORE_ADDR interp_text_sect_high;
1092 static CORE_ADDR interp_plt_sect_low;
1093 static CORE_ADDR interp_plt_sect_high;
1094
1095 int
1096 in_svr4_dynsym_resolve_code (CORE_ADDR pc)
1097 {
1098   return ((pc >= interp_text_sect_low && pc < interp_text_sect_high)
1099           || (pc >= interp_plt_sect_low && pc < interp_plt_sect_high)
1100           || in_plt_section (pc, NULL));
1101 }
1102 #endif
1103
1104 /*
1105
1106    LOCAL FUNCTION
1107
1108    disable_break -- remove the "mapping changed" breakpoint
1109
1110    SYNOPSIS
1111
1112    static int disable_break ()
1113
1114    DESCRIPTION
1115
1116    Removes the breakpoint that gets hit when the dynamic linker
1117    completes a mapping change.
1118
1119  */
1120
1121 #ifndef SVR4_SHARED_LIBS
1122
1123 static int
1124 disable_break (void)
1125 {
1126   int status = 1;
1127
1128   int in_debugger = 0;
1129
1130   /* Read the debugger structure from the inferior to retrieve the
1131      address of the breakpoint and the original contents of the
1132      breakpoint address.  Remove the breakpoint by writing the original
1133      contents back. */
1134
1135   read_memory (debug_addr, (char *) &debug_copy, sizeof (debug_copy));
1136
1137   /* Set `in_debugger' to zero now. */
1138
1139   write_memory (flag_addr, (char *) &in_debugger, sizeof (in_debugger));
1140
1141   breakpoint_addr = SOLIB_EXTRACT_ADDRESS (debug_copy.ldd_bp_addr);
1142   write_memory (breakpoint_addr, (char *) &debug_copy.ldd_bp_inst,
1143                 sizeof (debug_copy.ldd_bp_inst));
1144
1145   /* For the SVR4 version, we always know the breakpoint address.  For the
1146      SunOS version we don't know it until the above code is executed.
1147      Grumble if we are stopped anywhere besides the breakpoint address. */
1148
1149   if (stop_pc != breakpoint_addr)
1150     {
1151       warning ("stopped at unknown breakpoint while handling shared libraries");
1152     }
1153
1154   return (status);
1155 }
1156
1157 #endif /* #ifdef SVR4_SHARED_LIBS */
1158
1159 /*
1160
1161    LOCAL FUNCTION
1162
1163    enable_break -- arrange for dynamic linker to hit breakpoint
1164
1165    SYNOPSIS
1166
1167    int enable_break (void)
1168
1169    DESCRIPTION
1170
1171    Both the SunOS and the SVR4 dynamic linkers have, as part of their
1172    debugger interface, support for arranging for the inferior to hit
1173    a breakpoint after mapping in the shared libraries.  This function
1174    enables that breakpoint.
1175
1176    For SunOS, there is a special flag location (in_debugger) which we
1177    set to 1.  When the dynamic linker sees this flag set, it will set
1178    a breakpoint at a location known only to itself, after saving the
1179    original contents of that place and the breakpoint address itself,
1180    in it's own internal structures.  When we resume the inferior, it
1181    will eventually take a SIGTRAP when it runs into the breakpoint.
1182    We handle this (in a different place) by restoring the contents of
1183    the breakpointed location (which is only known after it stops),
1184    chasing around to locate the shared libraries that have been
1185    loaded, then resuming.
1186
1187    For SVR4, the debugger interface structure contains a member (r_brk)
1188    which is statically initialized at the time the shared library is
1189    built, to the offset of a function (_r_debug_state) which is guaran-
1190    teed to be called once before mapping in a library, and again when
1191    the mapping is complete.  At the time we are examining this member,
1192    it contains only the unrelocated offset of the function, so we have
1193    to do our own relocation.  Later, when the dynamic linker actually
1194    runs, it relocates r_brk to be the actual address of _r_debug_state().
1195
1196    The debugger interface structure also contains an enumeration which
1197    is set to either RT_ADD or RT_DELETE prior to changing the mapping,
1198    depending upon whether or not the library is being mapped or unmapped,
1199    and then set to RT_CONSISTENT after the library is mapped/unmapped.
1200  */
1201
1202 static int
1203 enable_break (void)
1204 {
1205   int success = 0;
1206
1207 #ifndef SVR4_SHARED_LIBS
1208
1209   int j;
1210   int in_debugger;
1211
1212   /* Get link_dynamic structure */
1213
1214   j = target_read_memory (debug_base, (char *) &dynamic_copy,
1215                           sizeof (dynamic_copy));
1216   if (j)
1217     {
1218       /* unreadable */
1219       return (0);
1220     }
1221
1222   /* Calc address of debugger interface structure */
1223
1224   debug_addr = SOLIB_EXTRACT_ADDRESS (dynamic_copy.ldd);
1225
1226   /* Calc address of `in_debugger' member of debugger interface structure */
1227
1228   flag_addr = debug_addr + (CORE_ADDR) ((char *) &debug_copy.ldd_in_debugger -
1229                                         (char *) &debug_copy);
1230
1231   /* Write a value of 1 to this member.  */
1232
1233   in_debugger = 1;
1234   write_memory (flag_addr, (char *) &in_debugger, sizeof (in_debugger));
1235   success = 1;
1236
1237 #else /* SVR4_SHARED_LIBS */
1238
1239 #ifdef BKPT_AT_SYMBOL
1240
1241   struct minimal_symbol *msymbol;
1242   char **bkpt_namep;
1243   asection *interp_sect;
1244
1245   /* First, remove all the solib event breakpoints.  Their addresses
1246      may have changed since the last time we ran the program.  */
1247   remove_solib_event_breakpoints ();
1248
1249 #ifdef SVR4_SHARED_LIBS
1250   interp_text_sect_low = interp_text_sect_high = 0;
1251   interp_plt_sect_low = interp_plt_sect_high = 0;
1252
1253   /* Find the .interp section; if not found, warn the user and drop
1254      into the old breakpoint at symbol code.  */
1255   interp_sect = bfd_get_section_by_name (exec_bfd, ".interp");
1256   if (interp_sect)
1257     {
1258       unsigned int interp_sect_size;
1259       char *buf;
1260       CORE_ADDR load_addr;
1261       bfd *tmp_bfd = NULL;
1262       int tmp_fd = -1;
1263       char *tmp_pathname = NULL;
1264       CORE_ADDR sym_addr = 0;
1265
1266       /* Read the contents of the .interp section into a local buffer;
1267          the contents specify the dynamic linker this program uses.  */
1268       interp_sect_size = bfd_section_size (exec_bfd, interp_sect);
1269       buf = alloca (interp_sect_size);
1270       bfd_get_section_contents (exec_bfd, interp_sect,
1271                                 buf, 0, interp_sect_size);
1272
1273       /* Now we need to figure out where the dynamic linker was
1274          loaded so that we can load its symbols and place a breakpoint
1275          in the dynamic linker itself.
1276
1277          This address is stored on the stack.  However, I've been unable
1278          to find any magic formula to find it for Solaris (appears to
1279          be trivial on GNU/Linux).  Therefore, we have to try an alternate
1280          mechanism to find the dynamic linker's base address.  */
1281
1282       tmp_fd  = solib_open (buf, &tmp_pathname);
1283       if (tmp_fd >= 0)
1284         tmp_bfd = bfd_fdopenr (tmp_pathname, gnutarget, tmp_fd);
1285
1286       if (tmp_bfd == NULL)
1287         goto bkpt_at_symbol;
1288
1289       /* Make sure the dynamic linker's really a useful object.  */
1290       if (!bfd_check_format (tmp_bfd, bfd_object))
1291         {
1292           warning ("Unable to grok dynamic linker %s as an object file", buf);
1293           bfd_close (tmp_bfd);
1294           goto bkpt_at_symbol;
1295         }
1296
1297       /* We find the dynamic linker's base address by examining the
1298          current pc (which point at the entry point for the dynamic
1299          linker) and subtracting the offset of the entry point.  */
1300       load_addr = read_pc () - tmp_bfd->start_address;
1301
1302       /* Record the relocated start and end address of the dynamic linker
1303          text and plt section for in_svr4_dynsym_resolve_code.  */
1304       interp_sect = bfd_get_section_by_name (tmp_bfd, ".text");
1305       if (interp_sect)
1306         {
1307           interp_text_sect_low =
1308             bfd_section_vma (tmp_bfd, interp_sect) + load_addr;
1309           interp_text_sect_high =
1310             interp_text_sect_low + bfd_section_size (tmp_bfd, interp_sect);
1311         }
1312       interp_sect = bfd_get_section_by_name (tmp_bfd, ".plt");
1313       if (interp_sect)
1314         {
1315           interp_plt_sect_low =
1316             bfd_section_vma (tmp_bfd, interp_sect) + load_addr;
1317           interp_plt_sect_high =
1318             interp_plt_sect_low + bfd_section_size (tmp_bfd, interp_sect);
1319         }
1320
1321       /* Now try to set a breakpoint in the dynamic linker.  */
1322       for (bkpt_namep = solib_break_names; *bkpt_namep != NULL; bkpt_namep++)
1323         {
1324           sym_addr = bfd_lookup_symbol (tmp_bfd, *bkpt_namep);
1325           if (sym_addr != 0)
1326             break;
1327         }
1328
1329       /* We're done with the temporary bfd.  */
1330       bfd_close (tmp_bfd);
1331
1332       if (sym_addr != 0)
1333         {
1334           create_solib_event_breakpoint (load_addr + sym_addr);
1335           return 1;
1336         }
1337
1338       /* For whatever reason we couldn't set a breakpoint in the dynamic
1339          linker.  Warn and drop into the old code.  */
1340     bkpt_at_symbol:
1341       warning ("Unable to find dynamic linker breakpoint function.\nGDB will be unable to debug shared library initializers\nand track explicitly loaded dynamic code.");
1342     }
1343 #endif
1344
1345   /* Scan through the list of symbols, trying to look up the symbol and
1346      set a breakpoint there.  Terminate loop when we/if we succeed. */
1347
1348   breakpoint_addr = 0;
1349   for (bkpt_namep = bkpt_names; *bkpt_namep != NULL; bkpt_namep++)
1350     {
1351       msymbol = lookup_minimal_symbol (*bkpt_namep, NULL, symfile_objfile);
1352       if ((msymbol != NULL) && (SYMBOL_VALUE_ADDRESS (msymbol) != 0))
1353         {
1354           create_solib_event_breakpoint (SYMBOL_VALUE_ADDRESS (msymbol));
1355           return 1;
1356         }
1357     }
1358
1359   /* Nothing good happened.  */
1360   success = 0;
1361
1362 #endif /* BKPT_AT_SYMBOL */
1363
1364 #endif /* !SVR4_SHARED_LIBS */
1365
1366   return (success);
1367 }
1368
1369 /*
1370
1371    LOCAL FUNCTION
1372
1373    special_symbol_handling -- additional shared library symbol handling
1374
1375    SYNOPSIS
1376
1377    void special_symbol_handling ()
1378
1379    DESCRIPTION
1380
1381    Once the symbols from a shared object have been loaded in the usual
1382    way, we are called to do any system specific symbol handling that 
1383    is needed.
1384
1385    For SunOS4, this consists of grunging around in the dynamic
1386    linkers structures to find symbol definitions for "common" symbols
1387    and adding them to the minimal symbol table for the runtime common
1388    objfile.
1389
1390  */
1391
1392 static void
1393 svr4_special_symbol_handling (void)
1394 {
1395 #ifndef SVR4_SHARED_LIBS
1396   int j;
1397
1398   if (debug_addr == 0)
1399     {
1400       /* Get link_dynamic structure */
1401
1402       j = target_read_memory (debug_base, (char *) &dynamic_copy,
1403                               sizeof (dynamic_copy));
1404       if (j)
1405         {
1406           /* unreadable */
1407           return;
1408         }
1409
1410       /* Calc address of debugger interface structure */
1411       /* FIXME, this needs work for cross-debugging of core files
1412          (byteorder, size, alignment, etc).  */
1413
1414       debug_addr = SOLIB_EXTRACT_ADDRESS (dynamic_copy.ldd);
1415     }
1416
1417   /* Read the debugger structure from the inferior, just to make sure
1418      we have a current copy. */
1419
1420   j = target_read_memory (debug_addr, (char *) &debug_copy,
1421                           sizeof (debug_copy));
1422   if (j)
1423     return;                     /* unreadable */
1424
1425   /* Get common symbol definitions for the loaded object. */
1426
1427   if (debug_copy.ldd_cp)
1428     {
1429       solib_add_common_symbols (SOLIB_EXTRACT_ADDRESS (debug_copy.ldd_cp));
1430     }
1431
1432 #endif /* !SVR4_SHARED_LIBS */
1433 }
1434
1435 /* Relocate the main executable.  This function should be called upon
1436    stopping the inferior process at the entry point to the program. 
1437    The entry point from BFD is compared to the PC and if they are
1438    different, the main executable is relocated by the proper amount. 
1439    
1440    As written it will only attempt to relocate executables which
1441    lack interpreter sections.  It seems likely that only dynamic
1442    linker executables will get relocated, though it should work
1443    properly for a position-independent static executable as well.  */
1444
1445 static void
1446 svr4_relocate_main_executable (void)
1447 {
1448   asection *interp_sect;
1449   CORE_ADDR pc = read_pc ();
1450
1451   /* Decide if the objfile needs to be relocated.  As indicated above,
1452      we will only be here when execution is stopped at the beginning
1453      of the program.  Relocation is necessary if the address at which
1454      we are presently stopped differs from the start address stored in
1455      the executable AND there's no interpreter section.  The condition
1456      regarding the interpreter section is very important because if
1457      there *is* an interpreter section, execution will begin there
1458      instead.  When there is an interpreter section, the start address
1459      is (presumably) used by the interpreter at some point to start
1460      execution of the program.
1461
1462      If there is an interpreter, it is normal for it to be set to an
1463      arbitrary address at the outset.  The job of finding it is
1464      handled in enable_break().
1465
1466      So, to summarize, relocations are necessary when there is no
1467      interpreter section and the start address obtained from the
1468      executable is different from the address at which GDB is
1469      currently stopped.
1470      
1471      [ The astute reader will note that we also test to make sure that
1472        the executable in question has the DYNAMIC flag set.  It is my
1473        opinion that this test is unnecessary (undesirable even).  It
1474        was added to avoid inadvertent relocation of an executable
1475        whose e_type member in the ELF header is not ET_DYN.  There may
1476        be a time in the future when it is desirable to do relocations
1477        on other types of files as well in which case this condition
1478        should either be removed or modified to accomodate the new file
1479        type.  (E.g, an ET_EXEC executable which has been built to be
1480        position-independent could safely be relocated by the OS if
1481        desired.  It is true that this violates the ABI, but the ABI
1482        has been known to be bent from time to time.)  - Kevin, Nov 2000. ]
1483      */
1484
1485   interp_sect = bfd_get_section_by_name (exec_bfd, ".interp");
1486   if (interp_sect == NULL 
1487       && (bfd_get_file_flags (exec_bfd) & DYNAMIC) != 0
1488       && bfd_get_start_address (exec_bfd) != pc)
1489     {
1490       struct cleanup *old_chain;
1491       struct section_offsets *new_offsets;
1492       int i, changed;
1493       CORE_ADDR displacement;
1494       
1495       /* It is necessary to relocate the objfile.  The amount to
1496          relocate by is simply the address at which we are stopped
1497          minus the starting address from the executable.
1498
1499          We relocate all of the sections by the same amount.  This
1500          behavior is mandated by recent editions of the System V ABI. 
1501          According to the System V Application Binary Interface,
1502          Edition 4.1, page 5-5:
1503
1504            ...  Though the system chooses virtual addresses for
1505            individual processes, it maintains the segments' relative
1506            positions.  Because position-independent code uses relative
1507            addressesing between segments, the difference between
1508            virtual addresses in memory must match the difference
1509            between virtual addresses in the file.  The difference
1510            between the virtual address of any segment in memory and
1511            the corresponding virtual address in the file is thus a
1512            single constant value for any one executable or shared
1513            object in a given process.  This difference is the base
1514            address.  One use of the base address is to relocate the
1515            memory image of the program during dynamic linking.
1516
1517          The same language also appears in Edition 4.0 of the System V
1518          ABI and is left unspecified in some of the earlier editions.  */
1519
1520       displacement = pc - bfd_get_start_address (exec_bfd);
1521       changed = 0;
1522
1523       new_offsets = xcalloc (sizeof (struct section_offsets),
1524                              symfile_objfile->num_sections);
1525       old_chain = make_cleanup (xfree, new_offsets);
1526
1527       for (i = 0; i < symfile_objfile->num_sections; i++)
1528         {
1529           if (displacement != ANOFFSET (symfile_objfile->section_offsets, i))
1530             changed = 1;
1531           new_offsets->offsets[i] = displacement;
1532         }
1533
1534       if (changed)
1535         objfile_relocate (symfile_objfile, new_offsets);
1536
1537       do_cleanups (old_chain);
1538     }
1539 }
1540
1541 /*
1542
1543    GLOBAL FUNCTION
1544
1545    svr4_solib_create_inferior_hook -- shared library startup support
1546
1547    SYNOPSIS
1548
1549    void svr4_solib_create_inferior_hook()
1550
1551    DESCRIPTION
1552
1553    When gdb starts up the inferior, it nurses it along (through the
1554    shell) until it is ready to execute it's first instruction.  At this
1555    point, this function gets called via expansion of the macro
1556    SOLIB_CREATE_INFERIOR_HOOK.
1557
1558    For SunOS executables, this first instruction is typically the
1559    one at "_start", or a similar text label, regardless of whether
1560    the executable is statically or dynamically linked.  The runtime
1561    startup code takes care of dynamically linking in any shared
1562    libraries, once gdb allows the inferior to continue.
1563
1564    For SVR4 executables, this first instruction is either the first
1565    instruction in the dynamic linker (for dynamically linked
1566    executables) or the instruction at "start" for statically linked
1567    executables.  For dynamically linked executables, the system
1568    first exec's /lib/libc.so.N, which contains the dynamic linker,
1569    and starts it running.  The dynamic linker maps in any needed
1570    shared libraries, maps in the actual user executable, and then
1571    jumps to "start" in the user executable.
1572
1573    For both SunOS shared libraries, and SVR4 shared libraries, we
1574    can arrange to cooperate with the dynamic linker to discover the
1575    names of shared libraries that are dynamically linked, and the
1576    base addresses to which they are linked.
1577
1578    This function is responsible for discovering those names and
1579    addresses, and saving sufficient information about them to allow
1580    their symbols to be read at a later time.
1581
1582    FIXME
1583
1584    Between enable_break() and disable_break(), this code does not
1585    properly handle hitting breakpoints which the user might have
1586    set in the startup code or in the dynamic linker itself.  Proper
1587    handling will probably have to wait until the implementation is
1588    changed to use the "breakpoint handler function" method.
1589
1590    Also, what if child has exit()ed?  Must exit loop somehow.
1591  */
1592
1593 static void
1594 svr4_solib_create_inferior_hook (void)
1595 {
1596   /* Relocate the main executable if necessary.  */
1597   svr4_relocate_main_executable ();
1598
1599   /* If we are using the BKPT_AT_SYMBOL code, then we don't need the base
1600      yet.  In fact, in the case of a SunOS4 executable being run on
1601      Solaris, we can't get it yet.  current_sos will get it when it needs
1602      it.  */
1603 #if !(defined (SVR4_SHARED_LIBS) && defined (BKPT_AT_SYMBOL))
1604   if ((debug_base = locate_base ()) == 0)
1605     {
1606       /* Can't find the symbol or the executable is statically linked. */
1607       return;
1608     }
1609 #endif
1610
1611   if (!enable_break ())
1612     {
1613       warning ("shared library handler failed to enable breakpoint");
1614       return;
1615     }
1616
1617 #if !defined(SVR4_SHARED_LIBS) || defined(_SCO_DS)
1618   /* SCO and SunOS need the loop below, other systems should be using the
1619      special shared library breakpoints and the shared library breakpoint
1620      service routine.
1621
1622      Now run the target.  It will eventually hit the breakpoint, at
1623      which point all of the libraries will have been mapped in and we
1624      can go groveling around in the dynamic linker structures to find
1625      out what we need to know about them. */
1626
1627   clear_proceed_status ();
1628   stop_soon_quietly = 1;
1629   stop_signal = TARGET_SIGNAL_0;
1630   do
1631     {
1632       target_resume (-1, 0, stop_signal);
1633       wait_for_inferior ();
1634     }
1635   while (stop_signal != TARGET_SIGNAL_TRAP);
1636   stop_soon_quietly = 0;
1637
1638 #if !defined(_SCO_DS)
1639   /* We are now either at the "mapping complete" breakpoint (or somewhere
1640      else, a condition we aren't prepared to deal with anyway), so adjust
1641      the PC as necessary after a breakpoint, disable the breakpoint, and
1642      add any shared libraries that were mapped in. */
1643
1644   if (DECR_PC_AFTER_BREAK)
1645     {
1646       stop_pc -= DECR_PC_AFTER_BREAK;
1647       write_register (PC_REGNUM, stop_pc);
1648     }
1649
1650   if (!disable_break ())
1651     {
1652       warning ("shared library handler failed to disable breakpoint");
1653     }
1654
1655   if (auto_solib_add)
1656     solib_add ((char *) 0, 0, (struct target_ops *) 0);
1657 #endif /* ! _SCO_DS */
1658 #endif
1659 }
1660
1661 static void
1662 svr4_clear_solib (void)
1663 {
1664   debug_base = 0;
1665 }
1666
1667 static void
1668 svr4_free_so (struct so_list *so)
1669 {
1670   xfree (so->lm_info->lm);
1671   xfree (so->lm_info);
1672 }
1673
1674 static void
1675 svr4_relocate_section_addresses (struct so_list *so,
1676                                  struct section_table *sec)
1677 {
1678   sec->addr += LM_ADDR (so);
1679   sec->endaddr += LM_ADDR (so);
1680 }
1681
1682 static struct target_so_ops svr4_so_ops;
1683
1684 void
1685 _initialize_svr4_solib (void)
1686 {
1687   svr4_so_ops.relocate_section_addresses = svr4_relocate_section_addresses;
1688   svr4_so_ops.free_so = svr4_free_so;
1689   svr4_so_ops.clear_solib = svr4_clear_solib;
1690   svr4_so_ops.solib_create_inferior_hook = svr4_solib_create_inferior_hook;
1691   svr4_so_ops.special_symbol_handling = svr4_special_symbol_handling;
1692   svr4_so_ops.current_sos = svr4_current_sos;
1693   svr4_so_ops.open_symbol_file_object = open_symbol_file_object;
1694
1695   /* FIXME: Don't do this here.  *_gdbarch_init() should set so_ops. */
1696   current_target_so_ops = &svr4_so_ops;
1697 }
1698