OSDN Git Service

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