2000-03-21 J.T. Conklin <jtc@redback.com>
[platform/upstream/binutils.git] / gdb / solib.c
1 /* Handle SunOS and SVR4 shared libraries for GDB, the GNU Debugger.
2    Copyright 1990, 91, 92, 93, 94, 95, 96, 98, 1999
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
23 #include "defs.h"
24
25 /* This file is only compilable if link.h is available. */
26
27 #ifdef HAVE_LINK_H
28
29 #include <sys/types.h>
30 #include <signal.h>
31 #include "gdb_string.h"
32 #include <sys/param.h>
33 #include <fcntl.h>
34
35 #ifndef SVR4_SHARED_LIBS
36  /* SunOS shared libs need the nlist structure.  */
37 #include <a.out.h>
38 #else
39 #include "elf/external.h"
40 #endif
41
42 #include <link.h>
43
44 #include "symtab.h"
45 #include "bfd.h"
46 #include "symfile.h"
47 #include "objfiles.h"
48 #include "gdbcore.h"
49 #include "command.h"
50 #include "target.h"
51 #include "frame.h"
52 #include "gnu-regex.h"
53 #include "inferior.h"
54 #include "environ.h"
55 #include "language.h"
56 #include "gdbcmd.h"
57
58 #define MAX_PATH_SIZE 512       /* FIXME: Should be dynamic */
59
60 /* On SVR4 systems, a list of symbols in the dynamic linker where
61    GDB can try to place a breakpoint to monitor shared library
62    events.
63
64    If none of these symbols are found, or other errors occur, then
65    SVR4 systems will fall back to using a symbol as the "startup
66    mapping complete" breakpoint address.  */
67
68 #ifdef SVR4_SHARED_LIBS
69 static char *solib_break_names[] =
70 {
71   "r_debug_state",
72   "_r_debug_state",
73   "_dl_debug_state",
74   "rtld_db_dlactivity",
75   NULL
76 };
77 #endif
78
79 #define BKPT_AT_SYMBOL 1
80
81 #if defined (BKPT_AT_SYMBOL) && defined (SVR4_SHARED_LIBS)
82 static char *bkpt_names[] =
83 {
84 #ifdef SOLIB_BKPT_NAME
85   SOLIB_BKPT_NAME,              /* Prefer configured name if it exists. */
86 #endif
87   "_start",
88   "main",
89   NULL
90 };
91 #endif
92
93 /* Symbols which are used to locate the base of the link map structures. */
94
95 #ifndef SVR4_SHARED_LIBS
96 static char *debug_base_symbols[] =
97 {
98   "_DYNAMIC",
99   "_DYNAMIC__MGC",
100   NULL
101 };
102 #endif
103
104 static char *main_name_list[] =
105 {
106   "main_$main",
107   NULL
108 };
109
110 /* local data declarations */
111
112 /* Macro to extract an address from a solib structure.
113    When GDB is configured for some 32-bit targets (e.g. Solaris 2.7
114    sparc), BFD is configured to handle 64-bit targets, so CORE_ADDR is
115    64 bits.  We have to extract only the significant bits of addresses
116    to get the right address when accessing the core file BFD.  */
117
118 #define SOLIB_EXTRACT_ADDRESS(member) \
119   extract_address (&member, sizeof (member))
120
121 #ifndef SVR4_SHARED_LIBS
122
123 #define LM_ADDR(so) (SOLIB_EXTRACT_ADDRESS ((so) -> lm.lm_addr))
124 #define LM_NEXT(so) (SOLIB_EXTRACT_ADDRESS ((so) -> lm.lm_next))
125 #define LM_NAME(so) (SOLIB_EXTRACT_ADDRESS ((so) -> lm.lm_name))
126 /* Test for first link map entry; first entry is a shared library. */
127 #define IGNORE_FIRST_LINK_MAP_ENTRY(so) (0)
128 static struct link_dynamic dynamic_copy;
129 static struct link_dynamic_2 ld_2_copy;
130 static struct ld_debug debug_copy;
131 static CORE_ADDR debug_addr;
132 static CORE_ADDR flag_addr;
133
134 #else /* SVR4_SHARED_LIBS */
135
136 #define LM_ADDR(so) (SOLIB_EXTRACT_ADDRESS ((so) -> lm.l_addr))
137 #define LM_NEXT(so) (SOLIB_EXTRACT_ADDRESS ((so) -> lm.l_next))
138 #define LM_NAME(so) (SOLIB_EXTRACT_ADDRESS ((so) -> lm.l_name))
139 /* Test for first link map entry; first entry is the exec-file. */
140 #define IGNORE_FIRST_LINK_MAP_ENTRY(so) \
141   (SOLIB_EXTRACT_ADDRESS ((so) -> lm.l_prev) == 0)
142 static struct r_debug debug_copy;
143 char shadow_contents[BREAKPOINT_MAX];   /* Stash old bkpt addr contents */
144
145 #endif /* !SVR4_SHARED_LIBS */
146
147 struct so_list
148   {
149     /* The following fields of the structure come directly from the
150        dynamic linker's tables in the inferior, and are initialized by
151        current_sos.  */
152
153     struct so_list *next;       /* next structure in linked list */
154     struct link_map lm;         /* copy of link map from inferior */
155     CORE_ADDR lmaddr;           /* addr in inferior lm was read from */
156
157     /* Shared object file name, exactly as it appears in the
158        inferior's link map.  This may be a relative path, or something
159        which needs to be looked up in LD_LIBRARY_PATH, etc.  We use it
160        to tell which entries in the inferior's dynamic linker's link
161        map we've already loaded.  */
162     char so_original_name[MAX_PATH_SIZE];
163
164     /* shared object file name, expanded to something GDB can open */
165     char so_name[MAX_PATH_SIZE];
166
167     /* The following fields of the structure are built from
168        information gathered from the shared object file itself, and
169        are initialized when we actually add it to our symbol tables.  */
170
171     bfd *abfd;
172     CORE_ADDR lmend;            /* upper addr bound of mapped object */
173     char symbols_loaded;        /* flag: symbols read in yet? */
174     char from_tty;              /* flag: print msgs? */
175     struct objfile *objfile;    /* objfile for loaded lib */
176     struct section_table *sections;
177     struct section_table *sections_end;
178     struct section_table *textsection;
179   };
180
181 static struct so_list *so_list_head;    /* List of known shared objects */
182 static CORE_ADDR debug_base;    /* Base of dynamic linker structures */
183 static CORE_ADDR breakpoint_addr;       /* Address where end bkpt is set */
184
185 static int solib_cleanup_queued = 0;    /* make_run_cleanup called */
186
187 extern int
188 fdmatch PARAMS ((int, int));    /* In libiberty */
189
190 /* Local function prototypes */
191
192 static void
193 do_clear_solib PARAMS ((PTR));
194
195 static int
196 match_main PARAMS ((char *));
197
198 static void
199 special_symbol_handling PARAMS ((void));
200
201 static void
202 sharedlibrary_command PARAMS ((char *, int));
203
204 static int
205 enable_break PARAMS ((void));
206
207 static void
208 info_sharedlibrary_command PARAMS ((char *, int));
209
210 static int symbol_add_stub PARAMS ((PTR));
211
212 static CORE_ADDR
213   first_link_map_member PARAMS ((void));
214
215 static CORE_ADDR
216   locate_base PARAMS ((void));
217
218 static int solib_map_sections PARAMS ((PTR));
219
220 #ifdef SVR4_SHARED_LIBS
221
222 static CORE_ADDR
223   elf_locate_base PARAMS ((void));
224
225 #else
226
227 static struct so_list *current_sos (void);
228 static void free_so (struct so_list *node);
229
230 static int
231 disable_break PARAMS ((void));
232
233 static void
234 allocate_rt_common_objfile PARAMS ((void));
235
236 static void
237 solib_add_common_symbols (CORE_ADDR);
238
239 #endif
240
241 void _initialize_solib PARAMS ((void));
242
243 /* If non-zero, this is a prefix that will be added to the front of the name
244    shared libraries with an absolute filename for loading.  */
245 static char *solib_absolute_prefix = NULL;
246
247 /* If non-empty, this is a search path for loading non-absolute shared library
248    symbol files.  This takes precedence over the environment variables PATH
249    and LD_LIBRARY_PATH.  */
250 static char *solib_search_path = NULL;
251
252 /*
253
254    LOCAL FUNCTION
255
256    solib_map_sections -- open bfd and build sections for shared lib
257
258    SYNOPSIS
259
260    static int solib_map_sections (struct so_list *so)
261
262    DESCRIPTION
263
264    Given a pointer to one of the shared objects in our list
265    of mapped objects, use the recorded name to open a bfd
266    descriptor for the object, build a section table, and then
267    relocate all the section addresses by the base address at
268    which the shared object was mapped.
269
270    FIXMES
271
272    In most (all?) cases the shared object file name recorded in the
273    dynamic linkage tables will be a fully qualified pathname.  For
274    cases where it isn't, do we really mimic the systems search
275    mechanism correctly in the below code (particularly the tilde
276    expansion stuff?).
277  */
278
279 static int
280 solib_map_sections (arg)
281      PTR arg;
282 {
283   struct so_list *so = (struct so_list *) arg;  /* catch_errors bogon */
284   char *filename;
285   char *scratch_pathname;
286   int scratch_chan;
287   struct section_table *p;
288   struct cleanup *old_chain;
289   bfd *abfd;
290
291   filename = tilde_expand (so->so_name);
292
293   if (solib_absolute_prefix && ROOTED_P (filename))
294     /* Prefix shared libraries with absolute filenames with
295        SOLIB_ABSOLUTE_PREFIX.  */
296     {
297       char *pfxed_fn;
298       int pfx_len;
299
300       pfx_len = strlen (solib_absolute_prefix);
301
302       /* Remove trailing slashes.  */
303       while (pfx_len > 0 && SLASH_P (solib_absolute_prefix[pfx_len - 1]))
304         pfx_len--;
305
306       pfxed_fn = xmalloc (pfx_len + strlen (filename) + 1);
307       strcpy (pfxed_fn, solib_absolute_prefix);
308       strcat (pfxed_fn, filename);
309       free (filename);
310
311       filename = pfxed_fn;
312     }
313
314   old_chain = make_cleanup (free, filename);
315
316   scratch_chan = -1;
317
318   if (solib_search_path)
319     scratch_chan = openp (solib_search_path,
320                           1, filename, O_RDONLY, 0, &scratch_pathname);
321   if (scratch_chan < 0)
322     scratch_chan = openp (get_in_environ (inferior_environ, "PATH"),
323                           1, filename, O_RDONLY, 0, &scratch_pathname);
324   if (scratch_chan < 0)
325     {
326       scratch_chan = openp (get_in_environ
327                             (inferior_environ, "LD_LIBRARY_PATH"),
328                             1, filename, O_RDONLY, 0, &scratch_pathname);
329     }
330   if (scratch_chan < 0)
331     {
332       perror_with_name (filename);
333     }
334   /* Leave scratch_pathname allocated.  abfd->name will point to it.  */
335
336   abfd = bfd_fdopenr (scratch_pathname, gnutarget, scratch_chan);
337   if (!abfd)
338     {
339       close (scratch_chan);
340       error ("Could not open `%s' as an executable file: %s",
341              scratch_pathname, bfd_errmsg (bfd_get_error ()));
342     }
343   /* Leave bfd open, core_xfer_memory and "info files" need it.  */
344   so->abfd = abfd;
345   abfd->cacheable = true;
346
347   /* copy full path name into so_name, so that later symbol_file_add can find
348      it */
349   if (strlen (scratch_pathname) >= MAX_PATH_SIZE)
350     error ("Full path name length of shared library exceeds MAX_PATH_SIZE in so_list structure.");
351   strcpy (so->so_name, scratch_pathname);
352
353   if (!bfd_check_format (abfd, bfd_object))
354     {
355       error ("\"%s\": not in executable format: %s.",
356              scratch_pathname, bfd_errmsg (bfd_get_error ()));
357     }
358   if (build_section_table (abfd, &so->sections, &so->sections_end))
359     {
360       error ("Can't find the file sections in `%s': %s",
361              bfd_get_filename (abfd), bfd_errmsg (bfd_get_error ()));
362     }
363
364   for (p = so->sections; p < so->sections_end; p++)
365     {
366       /* Relocate the section binding addresses as recorded in the shared
367          object's file by the base address to which the object was actually
368          mapped. */
369       p->addr += LM_ADDR (so);
370       p->endaddr += LM_ADDR (so);
371       so->lmend = max (p->endaddr, so->lmend);
372       if (STREQ (p->the_bfd_section->name, ".text"))
373         {
374           so->textsection = p;
375         }
376     }
377
378   /* Free the file names, close the file now.  */
379   do_cleanups (old_chain);
380
381   return (1);
382 }
383
384 #ifndef SVR4_SHARED_LIBS
385
386 /* Allocate the runtime common object file.  */
387
388 static void
389 allocate_rt_common_objfile ()
390 {
391   struct objfile *objfile;
392   struct objfile *last_one;
393
394   objfile = (struct objfile *) xmalloc (sizeof (struct objfile));
395   memset (objfile, 0, sizeof (struct objfile));
396   objfile->md = NULL;
397   obstack_specify_allocation (&objfile->psymbol_cache.cache, 0, 0,
398                               xmalloc, free);
399   obstack_specify_allocation (&objfile->psymbol_obstack, 0, 0, xmalloc,
400                               free);
401   obstack_specify_allocation (&objfile->symbol_obstack, 0, 0, xmalloc,
402                               free);
403   obstack_specify_allocation (&objfile->type_obstack, 0, 0, xmalloc,
404                               free);
405   objfile->name = mstrsave (objfile->md, "rt_common");
406
407   /* Add this file onto the tail of the linked list of other such files. */
408
409   objfile->next = NULL;
410   if (object_files == NULL)
411     object_files = objfile;
412   else
413     {
414       for (last_one = object_files;
415            last_one->next;
416            last_one = last_one->next);
417       last_one->next = objfile;
418     }
419
420   rt_common_objfile = objfile;
421 }
422
423 /* Read all dynamically loaded common symbol definitions from the inferior
424    and put them into the minimal symbol table for the runtime common
425    objfile.  */
426
427 static void
428 solib_add_common_symbols (rtc_symp)
429      CORE_ADDR rtc_symp;
430 {
431   struct rtc_symb inferior_rtc_symb;
432   struct nlist inferior_rtc_nlist;
433   int len;
434   char *name;
435
436   /* Remove any runtime common symbols from previous runs.  */
437
438   if (rt_common_objfile != NULL && rt_common_objfile->minimal_symbol_count)
439     {
440       obstack_free (&rt_common_objfile->symbol_obstack, 0);
441       obstack_specify_allocation (&rt_common_objfile->symbol_obstack, 0, 0,
442                                   xmalloc, free);
443       rt_common_objfile->minimal_symbol_count = 0;
444       rt_common_objfile->msymbols = NULL;
445     }
446
447   init_minimal_symbol_collection ();
448   make_cleanup ((make_cleanup_func) discard_minimal_symbols, 0);
449
450   while (rtc_symp)
451     {
452       read_memory (rtc_symp,
453                    (char *) &inferior_rtc_symb,
454                    sizeof (inferior_rtc_symb));
455       read_memory (SOLIB_EXTRACT_ADDRESS (inferior_rtc_symb.rtc_sp),
456                    (char *) &inferior_rtc_nlist,
457                    sizeof (inferior_rtc_nlist));
458       if (inferior_rtc_nlist.n_type == N_COMM)
459         {
460           /* FIXME: The length of the symbol name is not available, but in the
461              current implementation the common symbol is allocated immediately
462              behind the name of the symbol. */
463           len = inferior_rtc_nlist.n_value - inferior_rtc_nlist.n_un.n_strx;
464
465           name = xmalloc (len);
466           read_memory (SOLIB_EXTRACT_ADDRESS (inferior_rtc_nlist.n_un.n_name),
467                        name, len);
468
469           /* Allocate the runtime common objfile if necessary. */
470           if (rt_common_objfile == NULL)
471             allocate_rt_common_objfile ();
472
473           prim_record_minimal_symbol (name, inferior_rtc_nlist.n_value,
474                                       mst_bss, rt_common_objfile);
475           free (name);
476         }
477       rtc_symp = SOLIB_EXTRACT_ADDRESS (inferior_rtc_symb.rtc_next);
478     }
479
480   /* Install any minimal symbols that have been collected as the current
481      minimal symbols for the runtime common objfile.  */
482
483   install_minimal_symbols (rt_common_objfile);
484 }
485
486 #endif /* SVR4_SHARED_LIBS */
487
488
489 #ifdef SVR4_SHARED_LIBS
490
491 static CORE_ADDR
492   bfd_lookup_symbol PARAMS ((bfd *, char *));
493
494 /*
495
496    LOCAL FUNCTION
497
498    bfd_lookup_symbol -- lookup the value for a specific symbol
499
500    SYNOPSIS
501
502    CORE_ADDR bfd_lookup_symbol (bfd *abfd, char *symname)
503
504    DESCRIPTION
505
506    An expensive way to lookup the value of a single symbol for
507    bfd's that are only temporary anyway.  This is used by the
508    shared library support to find the address of the debugger
509    interface structures in the shared library.
510
511    Note that 0 is specifically allowed as an error return (no
512    such symbol).
513  */
514
515 static CORE_ADDR
516 bfd_lookup_symbol (abfd, symname)
517      bfd *abfd;
518      char *symname;
519 {
520   unsigned int storage_needed;
521   asymbol *sym;
522   asymbol **symbol_table;
523   unsigned int number_of_symbols;
524   unsigned int i;
525   struct cleanup *back_to;
526   CORE_ADDR symaddr = 0;
527
528   storage_needed = bfd_get_symtab_upper_bound (abfd);
529
530   if (storage_needed > 0)
531     {
532       symbol_table = (asymbol **) xmalloc (storage_needed);
533       back_to = make_cleanup (free, (PTR) symbol_table);
534       number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table);
535
536       for (i = 0; i < number_of_symbols; i++)
537         {
538           sym = *symbol_table++;
539           if (STREQ (sym->name, symname))
540             {
541               /* Bfd symbols are section relative. */
542               symaddr = sym->value + sym->section->vma;
543               break;
544             }
545         }
546       do_cleanups (back_to);
547     }
548   return (symaddr);
549 }
550
551 #ifdef HANDLE_SVR4_EXEC_EMULATORS
552
553 /*
554    Solaris BCP (the part of Solaris which allows it to run SunOS4
555    a.out files) throws in another wrinkle. Solaris does not fill
556    in the usual a.out link map structures when running BCP programs,
557    the only way to get at them is via groping around in the dynamic
558    linker.
559    The dynamic linker and it's structures are located in the shared
560    C library, which gets run as the executable's "interpreter" by
561    the kernel.
562
563    Note that we can assume nothing about the process state at the time
564    we need to find these structures.  We may be stopped on the first
565    instruction of the interpreter (C shared library), the first
566    instruction of the executable itself, or somewhere else entirely
567    (if we attached to the process for example).
568  */
569
570 static char *debug_base_symbols[] =
571 {
572   "r_debug",                    /* Solaris 2.3 */
573   "_r_debug",                   /* Solaris 2.1, 2.2 */
574   NULL
575 };
576
577 static int
578 look_for_base PARAMS ((int, CORE_ADDR));
579
580 /*
581
582    LOCAL FUNCTION
583
584    look_for_base -- examine file for each mapped address segment
585
586    SYNOPSYS
587
588    static int look_for_base (int fd, CORE_ADDR baseaddr)
589
590    DESCRIPTION
591
592    This function is passed to proc_iterate_over_mappings, which
593    causes it to get called once for each mapped address space, with
594    an open file descriptor for the file mapped to that space, and the
595    base address of that mapped space.
596
597    Our job is to find the debug base symbol in the file that this
598    fd is open on, if it exists, and if so, initialize the dynamic
599    linker structure base address debug_base.
600
601    Note that this is a computationally expensive proposition, since
602    we basically have to open a bfd on every call, so we specifically
603    avoid opening the exec file.
604  */
605
606 static int
607 look_for_base (fd, baseaddr)
608      int fd;
609      CORE_ADDR baseaddr;
610 {
611   bfd *interp_bfd;
612   CORE_ADDR address = 0;
613   char **symbolp;
614
615   /* If the fd is -1, then there is no file that corresponds to this
616      mapped memory segment, so skip it.  Also, if the fd corresponds
617      to the exec file, skip it as well. */
618
619   if (fd == -1
620       || (exec_bfd != NULL
621           && fdmatch (fileno ((FILE *) (exec_bfd->iostream)), fd)))
622     {
623       return (0);
624     }
625
626   /* Try to open whatever random file this fd corresponds to.  Note that
627      we have no way currently to find the filename.  Don't gripe about
628      any problems we might have, just fail. */
629
630   if ((interp_bfd = bfd_fdopenr ("unnamed", gnutarget, fd)) == NULL)
631     {
632       return (0);
633     }
634   if (!bfd_check_format (interp_bfd, bfd_object))
635     {
636       /* FIXME-leak: on failure, might not free all memory associated with
637          interp_bfd.  */
638       bfd_close (interp_bfd);
639       return (0);
640     }
641
642   /* Now try to find our debug base symbol in this file, which we at
643      least know to be a valid ELF executable or shared library. */
644
645   for (symbolp = debug_base_symbols; *symbolp != NULL; symbolp++)
646     {
647       address = bfd_lookup_symbol (interp_bfd, *symbolp);
648       if (address != 0)
649         {
650           break;
651         }
652     }
653   if (address == 0)
654     {
655       /* FIXME-leak: on failure, might not free all memory associated with
656          interp_bfd.  */
657       bfd_close (interp_bfd);
658       return (0);
659     }
660
661   /* Eureka!  We found the symbol.  But now we may need to relocate it
662      by the base address.  If the symbol's value is less than the base
663      address of the shared library, then it hasn't yet been relocated
664      by the dynamic linker, and we have to do it ourself.  FIXME: Note
665      that we make the assumption that the first segment that corresponds
666      to the shared library has the base address to which the library
667      was relocated. */
668
669   if (address < baseaddr)
670     {
671       address += baseaddr;
672     }
673   debug_base = address;
674   /* FIXME-leak: on failure, might not free all memory associated with
675      interp_bfd.  */
676   bfd_close (interp_bfd);
677   return (1);
678 }
679 #endif /* HANDLE_SVR4_EXEC_EMULATORS */
680
681 /*
682
683    LOCAL FUNCTION
684
685    elf_locate_base -- locate the base address of dynamic linker structs
686    for SVR4 elf targets.
687
688    SYNOPSIS
689
690    CORE_ADDR elf_locate_base (void)
691
692    DESCRIPTION
693
694    For SVR4 elf targets the address of the dynamic linker's runtime
695    structure is contained within the dynamic info section in the
696    executable file.  The dynamic section is also mapped into the
697    inferior address space.  Because the runtime loader fills in the
698    real address before starting the inferior, we have to read in the
699    dynamic info section from the inferior address space.
700    If there are any errors while trying to find the address, we
701    silently return 0, otherwise the found address is returned.
702
703  */
704
705 static CORE_ADDR
706 elf_locate_base ()
707 {
708   sec_ptr dyninfo_sect;
709   int dyninfo_sect_size;
710   CORE_ADDR dyninfo_addr;
711   char *buf;
712   char *bufend;
713
714   /* Find the start address of the .dynamic section.  */
715   dyninfo_sect = bfd_get_section_by_name (exec_bfd, ".dynamic");
716   if (dyninfo_sect == NULL)
717     return 0;
718   dyninfo_addr = bfd_section_vma (exec_bfd, dyninfo_sect);
719
720   /* Read in .dynamic section, silently ignore errors.  */
721   dyninfo_sect_size = bfd_section_size (exec_bfd, dyninfo_sect);
722   buf = alloca (dyninfo_sect_size);
723   if (target_read_memory (dyninfo_addr, buf, dyninfo_sect_size))
724     return 0;
725
726   /* Find the DT_DEBUG entry in the the .dynamic section.
727      For mips elf we look for DT_MIPS_RLD_MAP, mips elf apparently has
728      no DT_DEBUG entries.  */
729 #ifndef TARGET_ELF64
730   for (bufend = buf + dyninfo_sect_size;
731        buf < bufend;
732        buf += sizeof (Elf32_External_Dyn))
733     {
734       Elf32_External_Dyn *x_dynp = (Elf32_External_Dyn *) buf;
735       long dyn_tag;
736       CORE_ADDR dyn_ptr;
737
738       dyn_tag = bfd_h_get_32 (exec_bfd, (bfd_byte *) x_dynp->d_tag);
739       if (dyn_tag == DT_NULL)
740         break;
741       else if (dyn_tag == DT_DEBUG)
742         {
743           dyn_ptr = bfd_h_get_32 (exec_bfd, (bfd_byte *) x_dynp->d_un.d_ptr);
744           return dyn_ptr;
745         }
746 #ifdef DT_MIPS_RLD_MAP
747       else if (dyn_tag == DT_MIPS_RLD_MAP)
748         {
749           char pbuf[TARGET_PTR_BIT / HOST_CHAR_BIT];
750
751           /* DT_MIPS_RLD_MAP contains a pointer to the address
752              of the dynamic link structure.  */
753           dyn_ptr = bfd_h_get_32 (exec_bfd, (bfd_byte *) x_dynp->d_un.d_ptr);
754           if (target_read_memory (dyn_ptr, pbuf, sizeof (pbuf)))
755             return 0;
756           return extract_unsigned_integer (pbuf, sizeof (pbuf));
757         }
758 #endif
759     }
760 #else /* ELF64 */
761   for (bufend = buf + dyninfo_sect_size;
762        buf < bufend;
763        buf += sizeof (Elf64_External_Dyn))
764     {
765       Elf64_External_Dyn *x_dynp = (Elf64_External_Dyn *) buf;
766       long dyn_tag;
767       CORE_ADDR dyn_ptr;
768
769       dyn_tag = bfd_h_get_64 (exec_bfd, (bfd_byte *) x_dynp->d_tag);
770       if (dyn_tag == DT_NULL)
771         break;
772       else if (dyn_tag == DT_DEBUG)
773         {
774           dyn_ptr = bfd_h_get_64 (exec_bfd, (bfd_byte *) x_dynp->d_un.d_ptr);
775           return dyn_ptr;
776         }
777     }
778 #endif
779
780   /* DT_DEBUG entry not found.  */
781   return 0;
782 }
783
784 #endif /* SVR4_SHARED_LIBS */
785
786 /*
787
788    LOCAL FUNCTION
789
790    locate_base -- locate the base address of dynamic linker structs
791
792    SYNOPSIS
793
794    CORE_ADDR locate_base (void)
795
796    DESCRIPTION
797
798    For both the SunOS and SVR4 shared library implementations, if the
799    inferior executable has been linked dynamically, there is a single
800    address somewhere in the inferior's data space which is the key to
801    locating all of the dynamic linker's runtime structures.  This
802    address is the value of the debug base symbol.  The job of this
803    function is to find and return that address, or to return 0 if there
804    is no such address (the executable is statically linked for example).
805
806    For SunOS, the job is almost trivial, since the dynamic linker and
807    all of it's structures are statically linked to the executable at
808    link time.  Thus the symbol for the address we are looking for has
809    already been added to the minimal symbol table for the executable's
810    objfile at the time the symbol file's symbols were read, and all we
811    have to do is look it up there.  Note that we explicitly do NOT want
812    to find the copies in the shared library.
813
814    The SVR4 version is a bit more complicated because the address
815    is contained somewhere in the dynamic info section.  We have to go
816    to a lot more work to discover the address of the debug base symbol.
817    Because of this complexity, we cache the value we find and return that
818    value on subsequent invocations.  Note there is no copy in the
819    executable symbol tables.
820
821  */
822
823 static CORE_ADDR
824 locate_base ()
825 {
826
827 #ifndef SVR4_SHARED_LIBS
828
829   struct minimal_symbol *msymbol;
830   CORE_ADDR address = 0;
831   char **symbolp;
832
833   /* For SunOS, we want to limit the search for the debug base symbol to the
834      executable being debugged, since there is a duplicate named symbol in the
835      shared library.  We don't want the shared library versions. */
836
837   for (symbolp = debug_base_symbols; *symbolp != NULL; symbolp++)
838     {
839       msymbol = lookup_minimal_symbol (*symbolp, NULL, symfile_objfile);
840       if ((msymbol != NULL) && (SYMBOL_VALUE_ADDRESS (msymbol) != 0))
841         {
842           address = SYMBOL_VALUE_ADDRESS (msymbol);
843           return (address);
844         }
845     }
846   return (0);
847
848 #else /* SVR4_SHARED_LIBS */
849
850   /* Check to see if we have a currently valid address, and if so, avoid
851      doing all this work again and just return the cached address.  If
852      we have no cached address, try to locate it in the dynamic info
853      section for ELF executables.  */
854
855   if (debug_base == 0)
856     {
857       if (exec_bfd != NULL
858           && bfd_get_flavour (exec_bfd) == bfd_target_elf_flavour)
859         debug_base = elf_locate_base ();
860 #ifdef HANDLE_SVR4_EXEC_EMULATORS
861       /* Try it the hard way for emulated executables.  */
862       else if (inferior_pid != 0 && target_has_execution)
863         proc_iterate_over_mappings (look_for_base);
864 #endif
865     }
866   return (debug_base);
867
868 #endif /* !SVR4_SHARED_LIBS */
869
870 }
871
872 /*
873
874    LOCAL FUNCTION
875
876    first_link_map_member -- locate first member in dynamic linker's map
877
878    SYNOPSIS
879
880    static CORE_ADDR first_link_map_member (void)
881
882    DESCRIPTION
883
884    Find the first element in the inferior's dynamic link map, and
885    return its address in the inferior.  This function doesn't copy the
886    link map entry itself into our address space; current_sos actually
887    does the reading.  */
888
889 static CORE_ADDR
890 first_link_map_member ()
891 {
892   CORE_ADDR lm = 0;
893
894 #ifndef SVR4_SHARED_LIBS
895
896   read_memory (debug_base, (char *) &dynamic_copy, sizeof (dynamic_copy));
897   if (dynamic_copy.ld_version >= 2)
898     {
899       /* It is a version that we can deal with, so read in the secondary
900          structure and find the address of the link map list from it. */
901       read_memory (SOLIB_EXTRACT_ADDRESS (dynamic_copy.ld_un.ld_2),
902                    (char *) &ld_2_copy, sizeof (struct link_dynamic_2));
903       lm = SOLIB_EXTRACT_ADDRESS (ld_2_copy.ld_loaded);
904     }
905
906 #else /* SVR4_SHARED_LIBS */
907
908   read_memory (debug_base, (char *) &debug_copy, sizeof (struct r_debug));
909   /* FIXME:  Perhaps we should validate the info somehow, perhaps by
910      checking r_version for a known version number, or r_state for
911      RT_CONSISTENT. */
912   lm = SOLIB_EXTRACT_ADDRESS (debug_copy.r_map);
913
914 #endif /* !SVR4_SHARED_LIBS */
915
916   return (lm);
917 }
918
919 #ifdef SVR4_SHARED_LIBS
920 /*
921
922   LOCAL FUNCTION
923
924   open_exec_file_object
925
926   SYNOPSIS
927
928   void open_symbol_file_object (int from_tty)
929
930   DESCRIPTION
931
932   If no open symbol file, attempt to locate and open the main symbol
933   file.  On SVR4 systems, this is the first link map entry.  If its
934   name is here, we can open it.  Useful when attaching to a process
935   without first loading its symbol file.
936
937  */
938
939 int
940 open_symbol_file_object (arg)
941      PTR arg;
942 {
943   int from_tty = (int) arg;     /* sneak past catch_errors */
944   CORE_ADDR lm;
945   struct link_map lmcopy;
946   char *filename;
947   int errcode;
948
949   if (symfile_objfile)
950     if (!query ("Attempt to reload symbols from process? "))
951       return 0;
952
953   if ((debug_base = locate_base ()) == 0)
954     return 0;   /* failed somehow... */
955
956   /* First link map member should be the executable.  */
957   if ((lm = first_link_map_member ()) == 0)
958     return 0;   /* failed somehow... */
959
960   /* Read from target memory to GDB.  */
961   read_memory (lm, (void *) &lmcopy, sizeof (lmcopy));
962
963   if (lmcopy.l_name == 0)
964     return 0;   /* no filename.  */
965
966   /* Now fetch the filename from target memory.  */
967   target_read_string (SOLIB_EXTRACT_ADDRESS (lmcopy.l_name), &filename, 
968                       MAX_PATH_SIZE - 1, &errcode);
969   if (errcode)
970     {
971       warning ("failed to read exec filename from attached file: %s",
972                safe_strerror (errcode));
973       return 0;
974     }
975
976   make_cleanup ((make_cleanup_func) free, (void *) filename);
977   /* Have a pathname: read the symbol file.  */
978   symbol_file_command (filename, from_tty);
979
980   return 1;
981 }
982 #endif /* SVR4_SHARED_LIBS */
983
984
985 /* LOCAL FUNCTION
986
987    free_so --- free a `struct so_list' object
988
989    SYNOPSIS
990
991    void free_so (struct so_list *so)
992
993    DESCRIPTION
994
995    Free the storage associated with the `struct so_list' object SO.
996    If we have opened a BFD for SO, close it.  
997
998    The caller is responsible for removing SO from whatever list it is
999    a member of.  If we have placed SO's sections in some target's
1000    section table, the caller is responsible for removing them.
1001
1002    This function doesn't mess with objfiles at all.  If there is an
1003    objfile associated with SO that needs to be removed, the caller is
1004    responsible for taking care of that.  */
1005
1006 static void
1007 free_so (struct so_list *so)
1008 {
1009   char *bfd_filename = 0;
1010
1011   if (so->sections)
1012     free (so->sections);
1013       
1014   if (so->abfd)
1015     {
1016       bfd_filename = bfd_get_filename (so->abfd);
1017       if (! bfd_close (so->abfd))
1018         warning ("cannot close \"%s\": %s",
1019                  bfd_filename, bfd_errmsg (bfd_get_error ()));
1020     }
1021
1022   if (bfd_filename)
1023     free (bfd_filename);
1024
1025   free (so);
1026 }
1027
1028
1029 /* On some systems, the only way to recognize the link map entry for
1030    the main executable file is by looking at its name.  Return
1031    non-zero iff SONAME matches one of the known main executable names.  */
1032
1033 static int
1034 match_main (soname)
1035      char *soname;
1036 {
1037   char **mainp;
1038
1039   for (mainp = main_name_list; *mainp != NULL; mainp++)
1040     {
1041       if (strcmp (soname, *mainp) == 0)
1042         return (1);
1043     }
1044
1045   return (0);
1046 }
1047
1048
1049 /* LOCAL FUNCTION
1050
1051    current_sos -- build a list of currently loaded shared objects
1052
1053    SYNOPSIS
1054
1055    struct so_list *current_sos ()
1056
1057    DESCRIPTION
1058
1059    Build a list of `struct so_list' objects describing the shared
1060    objects currently loaded in the inferior.  This list does not
1061    include an entry for the main executable file.
1062
1063    Note that we only gather information directly available from the
1064    inferior --- we don't examine any of the shared library files
1065    themselves.  The declaration of `struct so_list' says which fields
1066    we provide values for.  */
1067
1068 static struct so_list *
1069 current_sos ()
1070 {
1071   CORE_ADDR lm;
1072   struct so_list *head = 0;
1073   struct so_list **link_ptr = &head;
1074
1075   /* Make sure we've looked up the inferior's dynamic linker's base
1076      structure.  */
1077   if (! debug_base)
1078     {
1079       debug_base = locate_base ();
1080
1081       /* If we can't find the dynamic linker's base structure, this
1082          must not be a dynamically linked executable.  Hmm.  */
1083       if (! debug_base)
1084         return 0;
1085     }
1086
1087   /* Walk the inferior's link map list, and build our list of
1088      `struct so_list' nodes.  */
1089   lm = first_link_map_member ();  
1090   while (lm)
1091     {
1092       struct so_list *new
1093         = (struct so_list *) xmalloc (sizeof (struct so_list));
1094       struct cleanup *old_chain = make_cleanup (free, new);
1095       memset (new, 0, sizeof (*new));
1096
1097       new->lmaddr = lm;
1098       read_memory (lm, (char *) &(new->lm), sizeof (struct link_map));
1099
1100       lm = LM_NEXT (new);
1101
1102       /* For SVR4 versions, the first entry in the link map is for the
1103          inferior executable, so we must ignore it.  For some versions of
1104          SVR4, it has no name.  For others (Solaris 2.3 for example), it
1105          does have a name, so we can no longer use a missing name to
1106          decide when to ignore it. */
1107       if (IGNORE_FIRST_LINK_MAP_ENTRY (new))
1108         free_so (new);
1109       else
1110         {
1111           int errcode;
1112           char *buffer;
1113
1114           /* Extract this shared object's name.  */
1115           target_read_string (LM_NAME (new), &buffer,
1116                               MAX_PATH_SIZE - 1, &errcode);
1117           if (errcode != 0)
1118             {
1119               warning ("current_sos: Can't read pathname for load map: %s\n",
1120                        safe_strerror (errcode));
1121             }
1122           else
1123             {
1124               strncpy (new->so_name, buffer, MAX_PATH_SIZE - 1);
1125               new->so_name[MAX_PATH_SIZE - 1] = '\0';
1126               free (buffer);
1127               strcpy (new->so_original_name, new->so_name);
1128             }
1129
1130           /* If this entry has no name, or its name matches the name
1131              for the main executable, don't include it in the list.  */
1132           if (! new->so_name[0]
1133               || match_main (new->so_name))
1134             free_so (new);
1135           else
1136             {
1137               new->next = 0;
1138               *link_ptr = new;
1139               link_ptr = &new->next;
1140             }
1141         }
1142
1143       discard_cleanups (old_chain);
1144     }
1145
1146   return head;
1147 }
1148
1149
1150 /* A small stub to get us past the arg-passing pinhole of catch_errors.  */
1151
1152 static int
1153 symbol_add_stub (arg)
1154      PTR arg;
1155 {
1156   register struct so_list *so = (struct so_list *) arg;  /* catch_errs bogon */
1157   CORE_ADDR text_addr = 0;
1158   struct section_addr_info *sap;
1159
1160   /* Have we already loaded this shared object?  */
1161   ALL_OBJFILES (so->objfile)
1162     {
1163       if (strcmp (so->objfile->name, so->so_name) == 0)
1164         return 1;
1165     }
1166
1167   /* Find the shared object's text segment.  */
1168   if (so->textsection)
1169     text_addr = so->textsection->addr;
1170   else if (so->abfd != NULL)
1171     {
1172       asection *lowest_sect;
1173
1174       /* If we didn't find a mapped non zero sized .text section, set up
1175          text_addr so that the relocation in symbol_file_add does no harm.  */
1176       lowest_sect = bfd_get_section_by_name (so->abfd, ".text");
1177       if (lowest_sect == NULL)
1178         bfd_map_over_sections (so->abfd, find_lowest_section,
1179                                (PTR) &lowest_sect);
1180       if (lowest_sect)
1181         text_addr = bfd_section_vma (so->abfd, lowest_sect)
1182           + LM_ADDR (so);
1183     }
1184
1185   sap = build_section_addr_info_from_section_table (so->sections,
1186                                                     so->sections_end);
1187   sap->text_addr = text_addr;
1188   so->objfile = symbol_file_add (so->so_name, so->from_tty,
1189                                  sap, 0, OBJF_SHARED);
1190   free_section_addr_info (sap);
1191
1192   return (1);
1193 }
1194
1195
1196 /* LOCAL FUNCTION
1197
1198    solib_add -- synchronize GDB's shared object list with the inferior's
1199
1200    SYNOPSIS
1201
1202    void solib_add (char *pattern, int from_tty, struct target_ops *TARGET)
1203
1204    DESCRIPTION
1205
1206    Extract the list of currently loaded shared objects from the
1207    inferior, and compare it with the list of shared objects for which
1208    GDB has currently loaded symbolic information.  If new shared
1209    objects have been loaded, or old shared objects have disappeared,
1210    make the appropriate changes to GDB's tables.
1211
1212    If PATTERN is non-null, read symbols only for shared objects
1213    whose names match PATTERN.
1214
1215    If FROM_TTY is non-null, feel free to print messages about what
1216    we're doing.
1217
1218    If TARGET is non-null, add the sections of all new shared objects
1219    to TARGET's section table.  Note that this doesn't remove any
1220    sections for shared objects that have been unloaded, and it
1221    doesn't check to see if the new shared objects are already present in
1222    the section table.  But we only use this for core files and
1223    processes we've just attached to, so that's okay.  */
1224
1225 void
1226 solib_add (char *pattern, int from_tty, struct target_ops *target)
1227 {
1228   struct so_list *inferior = current_sos ();
1229   struct so_list *gdb, **gdb_link;
1230
1231 #ifdef SVR4_SHARED_LIBS
1232   /* If we are attaching to a running process for which we 
1233      have not opened a symbol file, we may be able to get its 
1234      symbols now!  */
1235   if (attach_flag &&
1236       symfile_objfile == NULL)
1237     catch_errors (open_symbol_file_object, (PTR) from_tty, 
1238                   "Error reading attached process's symbol file.\n",
1239                   RETURN_MASK_ALL);
1240
1241 #endif SVR4_SHARED_LIBS
1242
1243   if (pattern)
1244     {
1245       char *re_err = re_comp (pattern);
1246
1247       if (re_err)
1248         error ("Invalid regexp: %s", re_err);
1249     }
1250
1251   /* Since this function might actually add some elements to the
1252      so_list_head list, arrange for it to be cleaned up when
1253      appropriate.  */
1254   if (!solib_cleanup_queued)
1255     {
1256       make_run_cleanup (do_clear_solib, NULL);
1257       solib_cleanup_queued = 1;
1258     }
1259
1260   /* GDB and the inferior's dynamic linker each maintain their own
1261      list of currently loaded shared objects; we want to bring the
1262      former in sync with the latter.  Scan both lists, seeing which
1263      shared objects appear where.  There are three cases:
1264
1265      - A shared object appears on both lists.  This means that GDB
1266        knows about it already, and it's still loaded in the inferior.
1267        Nothing needs to happen.
1268
1269      - A shared object appears only on GDB's list.  This means that
1270        the inferior has unloaded it.  We should remove the shared
1271        object from GDB's tables.
1272
1273      - A shared object appears only on the inferior's list.  This
1274        means that it's just been loaded.  We should add it to GDB's
1275        tables.
1276
1277      So we walk GDB's list, checking each entry to see if it appears
1278      in the inferior's list too.  If it does, no action is needed, and
1279      we remove it from the inferior's list.  If it doesn't, the
1280      inferior has unloaded it, and we remove it from GDB's list.  By
1281      the time we're done walking GDB's list, the inferior's list
1282      contains only the new shared objects, which we then add.  */
1283
1284   gdb = so_list_head;
1285   gdb_link = &so_list_head;
1286   while (gdb)
1287     {
1288       struct so_list *i = inferior;
1289       struct so_list **i_link = &inferior;
1290
1291       /* Check to see whether the shared object *gdb also appears in
1292          the inferior's current list.  */
1293       while (i)
1294         {
1295           if (! strcmp (gdb->so_original_name, i->so_original_name))
1296             break;
1297
1298           i_link = &i->next;
1299           i = *i_link;
1300         }
1301
1302       /* If the shared object appears on the inferior's list too, then
1303          it's still loaded, so we don't need to do anything.  Delete
1304          it from the inferior's list, and leave it on GDB's list.  */
1305       if (i)
1306         {
1307           *i_link = i->next;
1308           free_so (i);
1309           gdb_link = &gdb->next;
1310           gdb = *gdb_link;
1311         }
1312
1313       /* If it's not on the inferior's list, remove it from GDB's tables.  */
1314       else
1315         {
1316           *gdb_link = gdb->next;
1317
1318           /* Unless the user loaded it explicitly, free SO's objfile.  */
1319           if (! (gdb->objfile->flags & OBJF_USERLOADED))
1320             free_objfile (gdb->objfile);
1321
1322           /* Some targets' section tables might be referring to
1323              sections from so->abfd; remove them.  */
1324           remove_target_sections (gdb->abfd);
1325
1326           free_so (gdb);
1327           gdb = *gdb_link;
1328         }
1329     }
1330
1331   /* Now the inferior's list contains only shared objects that don't
1332      appear in GDB's list --- those that are newly loaded.  Add them
1333      to GDB's shared object list, and read in their symbols, if
1334      appropriate.  */
1335   if (inferior)
1336     {
1337       struct so_list *i;
1338
1339       /* Add the new shared objects to GDB's list.  */
1340       *gdb_link = inferior;
1341
1342       /* Fill in the rest of each of the `struct so_list' nodes, and
1343          read symbols for those files whose names match PATTERN.  */
1344       for (i = inferior; i; i = i->next)
1345         {
1346           i->from_tty = from_tty;
1347
1348           /* Fill in the rest of the `struct so_list' node.  */
1349           catch_errors (solib_map_sections, i,
1350                         "Error while mapping shared library sections:\n",
1351                         RETURN_MASK_ALL);
1352
1353           if (! pattern || re_exec (i->so_name))
1354             {
1355               if (i->symbols_loaded)
1356                 {
1357                   if (from_tty)
1358                     printf_unfiltered ("Symbols already loaded for %s\n",
1359                                        i->so_name);
1360                 }
1361               else
1362                 {
1363                   if (catch_errors
1364                       (symbol_add_stub, i,
1365                        "Error while reading shared library symbols:\n",
1366                        RETURN_MASK_ALL))
1367                     {
1368                       if (from_tty)
1369                         printf_unfiltered ("Loaded symbols for %s\n",
1370                                            i->so_name);
1371                       i->symbols_loaded = 1;
1372                     }
1373                 }
1374             }
1375         }
1376
1377       /* If requested, add the shared objects' sections to the the
1378          TARGET's section table.  */
1379       if (target)
1380         {
1381           int new_sections;
1382
1383           /* Figure out how many sections we'll need to add in total.  */
1384           new_sections = 0;
1385           for (i = inferior; i; i = i->next)
1386             new_sections += (i->sections_end - i->sections);
1387
1388           if (new_sections > 0)
1389             {
1390               int space = target_resize_to_sections (target, new_sections);
1391
1392               for (i = inferior; i; i = i->next)
1393                 {
1394                   int count = (i->sections_end - i->sections);
1395                   memcpy (target->to_sections + space,
1396                           i->sections,
1397                           count * sizeof (i->sections[0]));
1398                   space += count;
1399                 }
1400             }
1401         }
1402
1403       /* Getting new symbols may change our opinion about what is
1404          frameless.  */
1405       reinit_frame_cache ();
1406
1407       special_symbol_handling ();
1408     }
1409 }
1410
1411
1412 /*
1413
1414    LOCAL FUNCTION
1415
1416    info_sharedlibrary_command -- code for "info sharedlibrary"
1417
1418    SYNOPSIS
1419
1420    static void info_sharedlibrary_command ()
1421
1422    DESCRIPTION
1423
1424    Walk through the shared library list and print information
1425    about each attached library.
1426  */
1427
1428 static void
1429 info_sharedlibrary_command (ignore, from_tty)
1430      char *ignore;
1431      int from_tty;
1432 {
1433   register struct so_list *so = NULL;   /* link map state variable */
1434   int header_done = 0;
1435   int addr_width;
1436   char *addr_fmt;
1437
1438   if (exec_bfd == NULL)
1439     {
1440       printf_unfiltered ("No executable file.\n");
1441       return;
1442     }
1443
1444 #ifndef TARGET_ELF64
1445   addr_width = 8 + 4;
1446   addr_fmt = "08l";
1447 #else
1448   addr_width = 16 + 4;
1449   addr_fmt = "016l";
1450 #endif
1451
1452   solib_add (0, 0, 0);
1453
1454   for (so = so_list_head; so; so = so->next)
1455     {
1456       if (so->so_name[0])
1457         {
1458           if (!header_done)
1459             {
1460               printf_unfiltered ("%-*s%-*s%-12s%s\n", addr_width, "From",
1461                                  addr_width, "To", "Syms Read",
1462                                  "Shared Object Library");
1463               header_done++;
1464             }
1465
1466           printf_unfiltered ("%-*s", addr_width,
1467                       local_hex_string_custom ((unsigned long) LM_ADDR (so),
1468                                                addr_fmt));
1469           printf_unfiltered ("%-*s", addr_width,
1470                          local_hex_string_custom ((unsigned long) so->lmend,
1471                                                   addr_fmt));
1472           printf_unfiltered ("%-12s", so->symbols_loaded ? "Yes" : "No");
1473           printf_unfiltered ("%s\n", so->so_name);
1474         }
1475     }
1476   if (so_list_head == NULL)
1477     {
1478       printf_unfiltered ("No shared libraries loaded at this time.\n");
1479     }
1480 }
1481
1482 /*
1483
1484    GLOBAL FUNCTION
1485
1486    solib_address -- check to see if an address is in a shared lib
1487
1488    SYNOPSIS
1489
1490    char * solib_address (CORE_ADDR address)
1491
1492    DESCRIPTION
1493
1494    Provides a hook for other gdb routines to discover whether or
1495    not a particular address is within the mapped address space of
1496    a shared library.  Any address between the base mapping address
1497    and the first address beyond the end of the last mapping, is
1498    considered to be within the shared library address space, for
1499    our purposes.
1500
1501    For example, this routine is called at one point to disable
1502    breakpoints which are in shared libraries that are not currently
1503    mapped in.
1504  */
1505
1506 char *
1507 solib_address (address)
1508      CORE_ADDR address;
1509 {
1510   register struct so_list *so = 0;      /* link map state variable */
1511
1512   for (so = so_list_head; so; so = so->next)
1513     {
1514       if (LM_ADDR (so) <= address && address < so->lmend)
1515         return (so->so_name);
1516     }
1517
1518   return (0);
1519 }
1520
1521 /* Called by free_all_symtabs */
1522
1523 void
1524 clear_solib ()
1525 {
1526   /* This function is expected to handle ELF shared libraries.  It is
1527      also used on Solaris, which can run either ELF or a.out binaries
1528      (for compatibility with SunOS 4), both of which can use shared
1529      libraries.  So we don't know whether we have an ELF executable or
1530      an a.out executable until the user chooses an executable file.
1531
1532      ELF shared libraries don't get mapped into the address space
1533      until after the program starts, so we'd better not try to insert
1534      breakpoints in them immediately.  We have to wait until the
1535      dynamic linker has loaded them; we'll hit a bp_shlib_event
1536      breakpoint (look for calls to create_solib_event_breakpoint) when
1537      it's ready.
1538
1539      SunOS shared libraries seem to be different --- they're present
1540      as soon as the process begins execution, so there's no need to
1541      put off inserting breakpoints.  There's also nowhere to put a
1542      bp_shlib_event breakpoint, so if we put it off, we'll never get
1543      around to it.
1544
1545      So: disable breakpoints only if we're using ELF shared libs.  */
1546   if (exec_bfd != NULL
1547       && bfd_get_flavour (exec_bfd) != bfd_target_aout_flavour)
1548     disable_breakpoints_in_shlibs (1);
1549
1550   while (so_list_head)
1551     {
1552       struct so_list *so = so_list_head;
1553       so_list_head = so->next;
1554       free_so (so);
1555     }
1556
1557   debug_base = 0;
1558 }
1559
1560 static void
1561 do_clear_solib (dummy)
1562      PTR dummy;
1563 {
1564   solib_cleanup_queued = 0;
1565   clear_solib ();
1566 }
1567
1568 #ifdef SVR4_SHARED_LIBS
1569
1570 /* Return 1 if PC lies in the dynamic symbol resolution code of the
1571    SVR4 run time loader.  */
1572
1573 static CORE_ADDR interp_text_sect_low;
1574 static CORE_ADDR interp_text_sect_high;
1575 static CORE_ADDR interp_plt_sect_low;
1576 static CORE_ADDR interp_plt_sect_high;
1577
1578 int
1579 in_svr4_dynsym_resolve_code (pc)
1580      CORE_ADDR pc;
1581 {
1582   return ((pc >= interp_text_sect_low && pc < interp_text_sect_high)
1583           || (pc >= interp_plt_sect_low && pc < interp_plt_sect_high)
1584           || in_plt_section (pc, NULL));
1585 }
1586 #endif
1587
1588 /*
1589
1590    LOCAL FUNCTION
1591
1592    disable_break -- remove the "mapping changed" breakpoint
1593
1594    SYNOPSIS
1595
1596    static int disable_break ()
1597
1598    DESCRIPTION
1599
1600    Removes the breakpoint that gets hit when the dynamic linker
1601    completes a mapping change.
1602
1603  */
1604
1605 #ifndef SVR4_SHARED_LIBS
1606
1607 static int
1608 disable_break ()
1609 {
1610   int status = 1;
1611
1612 #ifndef SVR4_SHARED_LIBS
1613
1614   int in_debugger = 0;
1615
1616   /* Read the debugger structure from the inferior to retrieve the
1617      address of the breakpoint and the original contents of the
1618      breakpoint address.  Remove the breakpoint by writing the original
1619      contents back. */
1620
1621   read_memory (debug_addr, (char *) &debug_copy, sizeof (debug_copy));
1622
1623   /* Set `in_debugger' to zero now. */
1624
1625   write_memory (flag_addr, (char *) &in_debugger, sizeof (in_debugger));
1626
1627   breakpoint_addr = SOLIB_EXTRACT_ADDRESS (debug_copy.ldd_bp_addr);
1628   write_memory (breakpoint_addr, (char *) &debug_copy.ldd_bp_inst,
1629                 sizeof (debug_copy.ldd_bp_inst));
1630
1631 #else /* SVR4_SHARED_LIBS */
1632
1633   /* Note that breakpoint address and original contents are in our address
1634      space, so we just need to write the original contents back. */
1635
1636   if (memory_remove_breakpoint (breakpoint_addr, shadow_contents) != 0)
1637     {
1638       status = 0;
1639     }
1640
1641 #endif /* !SVR4_SHARED_LIBS */
1642
1643   /* For the SVR4 version, we always know the breakpoint address.  For the
1644      SunOS version we don't know it until the above code is executed.
1645      Grumble if we are stopped anywhere besides the breakpoint address. */
1646
1647   if (stop_pc != breakpoint_addr)
1648     {
1649       warning ("stopped at unknown breakpoint while handling shared libraries");
1650     }
1651
1652   return (status);
1653 }
1654
1655 #endif /* #ifdef SVR4_SHARED_LIBS */
1656
1657 /*
1658
1659    LOCAL FUNCTION
1660
1661    enable_break -- arrange for dynamic linker to hit breakpoint
1662
1663    SYNOPSIS
1664
1665    int enable_break (void)
1666
1667    DESCRIPTION
1668
1669    Both the SunOS and the SVR4 dynamic linkers have, as part of their
1670    debugger interface, support for arranging for the inferior to hit
1671    a breakpoint after mapping in the shared libraries.  This function
1672    enables that breakpoint.
1673
1674    For SunOS, there is a special flag location (in_debugger) which we
1675    set to 1.  When the dynamic linker sees this flag set, it will set
1676    a breakpoint at a location known only to itself, after saving the
1677    original contents of that place and the breakpoint address itself,
1678    in it's own internal structures.  When we resume the inferior, it
1679    will eventually take a SIGTRAP when it runs into the breakpoint.
1680    We handle this (in a different place) by restoring the contents of
1681    the breakpointed location (which is only known after it stops),
1682    chasing around to locate the shared libraries that have been
1683    loaded, then resuming.
1684
1685    For SVR4, the debugger interface structure contains a member (r_brk)
1686    which is statically initialized at the time the shared library is
1687    built, to the offset of a function (_r_debug_state) which is guaran-
1688    teed to be called once before mapping in a library, and again when
1689    the mapping is complete.  At the time we are examining this member,
1690    it contains only the unrelocated offset of the function, so we have
1691    to do our own relocation.  Later, when the dynamic linker actually
1692    runs, it relocates r_brk to be the actual address of _r_debug_state().
1693
1694    The debugger interface structure also contains an enumeration which
1695    is set to either RT_ADD or RT_DELETE prior to changing the mapping,
1696    depending upon whether or not the library is being mapped or unmapped,
1697    and then set to RT_CONSISTENT after the library is mapped/unmapped.
1698  */
1699
1700 static int
1701 enable_break ()
1702 {
1703   int success = 0;
1704
1705 #ifndef SVR4_SHARED_LIBS
1706
1707   int j;
1708   int in_debugger;
1709
1710   /* Get link_dynamic structure */
1711
1712   j = target_read_memory (debug_base, (char *) &dynamic_copy,
1713                           sizeof (dynamic_copy));
1714   if (j)
1715     {
1716       /* unreadable */
1717       return (0);
1718     }
1719
1720   /* Calc address of debugger interface structure */
1721
1722   debug_addr = SOLIB_EXTRACT_ADDRESS (dynamic_copy.ldd);
1723
1724   /* Calc address of `in_debugger' member of debugger interface structure */
1725
1726   flag_addr = debug_addr + (CORE_ADDR) ((char *) &debug_copy.ldd_in_debugger -
1727                                         (char *) &debug_copy);
1728
1729   /* Write a value of 1 to this member.  */
1730
1731   in_debugger = 1;
1732   write_memory (flag_addr, (char *) &in_debugger, sizeof (in_debugger));
1733   success = 1;
1734
1735 #else /* SVR4_SHARED_LIBS */
1736
1737 #ifdef BKPT_AT_SYMBOL
1738
1739   struct minimal_symbol *msymbol;
1740   char **bkpt_namep;
1741   asection *interp_sect;
1742
1743   /* First, remove all the solib event breakpoints.  Their addresses
1744      may have changed since the last time we ran the program.  */
1745   remove_solib_event_breakpoints ();
1746
1747 #ifdef SVR4_SHARED_LIBS
1748   interp_text_sect_low = interp_text_sect_high = 0;
1749   interp_plt_sect_low = interp_plt_sect_high = 0;
1750
1751   /* Find the .interp section; if not found, warn the user and drop
1752      into the old breakpoint at symbol code.  */
1753   interp_sect = bfd_get_section_by_name (exec_bfd, ".interp");
1754   if (interp_sect)
1755     {
1756       unsigned int interp_sect_size;
1757       char *buf;
1758       CORE_ADDR load_addr;
1759       bfd *tmp_bfd;
1760       CORE_ADDR sym_addr = 0;
1761
1762       /* Read the contents of the .interp section into a local buffer;
1763          the contents specify the dynamic linker this program uses.  */
1764       interp_sect_size = bfd_section_size (exec_bfd, interp_sect);
1765       buf = alloca (interp_sect_size);
1766       bfd_get_section_contents (exec_bfd, interp_sect,
1767                                 buf, 0, interp_sect_size);
1768
1769       /* Now we need to figure out where the dynamic linker was
1770          loaded so that we can load its symbols and place a breakpoint
1771          in the dynamic linker itself.
1772
1773          This address is stored on the stack.  However, I've been unable
1774          to find any magic formula to find it for Solaris (appears to
1775          be trivial on GNU/Linux).  Therefore, we have to try an alternate
1776          mechanism to find the dynamic linker's base address.  */
1777       tmp_bfd = bfd_openr (buf, gnutarget);
1778       if (tmp_bfd == NULL)
1779         goto bkpt_at_symbol;
1780
1781       /* Make sure the dynamic linker's really a useful object.  */
1782       if (!bfd_check_format (tmp_bfd, bfd_object))
1783         {
1784           warning ("Unable to grok dynamic linker %s as an object file", buf);
1785           bfd_close (tmp_bfd);
1786           goto bkpt_at_symbol;
1787         }
1788
1789       /* We find the dynamic linker's base address by examining the
1790          current pc (which point at the entry point for the dynamic
1791          linker) and subtracting the offset of the entry point.  */
1792       load_addr = read_pc () - tmp_bfd->start_address;
1793
1794       /* Record the relocated start and end address of the dynamic linker
1795          text and plt section for in_svr4_dynsym_resolve_code.  */
1796       interp_sect = bfd_get_section_by_name (tmp_bfd, ".text");
1797       if (interp_sect)
1798         {
1799           interp_text_sect_low =
1800             bfd_section_vma (tmp_bfd, interp_sect) + load_addr;
1801           interp_text_sect_high =
1802             interp_text_sect_low + bfd_section_size (tmp_bfd, interp_sect);
1803         }
1804       interp_sect = bfd_get_section_by_name (tmp_bfd, ".plt");
1805       if (interp_sect)
1806         {
1807           interp_plt_sect_low =
1808             bfd_section_vma (tmp_bfd, interp_sect) + load_addr;
1809           interp_plt_sect_high =
1810             interp_plt_sect_low + bfd_section_size (tmp_bfd, interp_sect);
1811         }
1812
1813       /* Now try to set a breakpoint in the dynamic linker.  */
1814       for (bkpt_namep = solib_break_names; *bkpt_namep != NULL; bkpt_namep++)
1815         {
1816           sym_addr = bfd_lookup_symbol (tmp_bfd, *bkpt_namep);
1817           if (sym_addr != 0)
1818             break;
1819         }
1820
1821       /* We're done with the temporary bfd.  */
1822       bfd_close (tmp_bfd);
1823
1824       if (sym_addr != 0)
1825         {
1826           create_solib_event_breakpoint (load_addr + sym_addr);
1827           return 1;
1828         }
1829
1830       /* For whatever reason we couldn't set a breakpoint in the dynamic
1831          linker.  Warn and drop into the old code.  */
1832     bkpt_at_symbol:
1833       warning ("Unable to find dynamic linker breakpoint function.\nGDB will be unable to debug shared library initializers\nand track explicitly loaded dynamic code.");
1834     }
1835 #endif
1836
1837   /* Scan through the list of symbols, trying to look up the symbol and
1838      set a breakpoint there.  Terminate loop when we/if we succeed. */
1839
1840   breakpoint_addr = 0;
1841   for (bkpt_namep = bkpt_names; *bkpt_namep != NULL; bkpt_namep++)
1842     {
1843       msymbol = lookup_minimal_symbol (*bkpt_namep, NULL, symfile_objfile);
1844       if ((msymbol != NULL) && (SYMBOL_VALUE_ADDRESS (msymbol) != 0))
1845         {
1846           create_solib_event_breakpoint (SYMBOL_VALUE_ADDRESS (msymbol));
1847           return 1;
1848         }
1849     }
1850
1851   /* Nothing good happened.  */
1852   success = 0;
1853
1854 #endif /* BKPT_AT_SYMBOL */
1855
1856 #endif /* !SVR4_SHARED_LIBS */
1857
1858   return (success);
1859 }
1860
1861 /*
1862
1863    GLOBAL FUNCTION
1864
1865    solib_create_inferior_hook -- shared library startup support
1866
1867    SYNOPSIS
1868
1869    void solib_create_inferior_hook()
1870
1871    DESCRIPTION
1872
1873    When gdb starts up the inferior, it nurses it along (through the
1874    shell) until it is ready to execute it's first instruction.  At this
1875    point, this function gets called via expansion of the macro
1876    SOLIB_CREATE_INFERIOR_HOOK.
1877
1878    For SunOS executables, this first instruction is typically the
1879    one at "_start", or a similar text label, regardless of whether
1880    the executable is statically or dynamically linked.  The runtime
1881    startup code takes care of dynamically linking in any shared
1882    libraries, once gdb allows the inferior to continue.
1883
1884    For SVR4 executables, this first instruction is either the first
1885    instruction in the dynamic linker (for dynamically linked
1886    executables) or the instruction at "start" for statically linked
1887    executables.  For dynamically linked executables, the system
1888    first exec's /lib/libc.so.N, which contains the dynamic linker,
1889    and starts it running.  The dynamic linker maps in any needed
1890    shared libraries, maps in the actual user executable, and then
1891    jumps to "start" in the user executable.
1892
1893    For both SunOS shared libraries, and SVR4 shared libraries, we
1894    can arrange to cooperate with the dynamic linker to discover the
1895    names of shared libraries that are dynamically linked, and the
1896    base addresses to which they are linked.
1897
1898    This function is responsible for discovering those names and
1899    addresses, and saving sufficient information about them to allow
1900    their symbols to be read at a later time.
1901
1902    FIXME
1903
1904    Between enable_break() and disable_break(), this code does not
1905    properly handle hitting breakpoints which the user might have
1906    set in the startup code or in the dynamic linker itself.  Proper
1907    handling will probably have to wait until the implementation is
1908    changed to use the "breakpoint handler function" method.
1909
1910    Also, what if child has exit()ed?  Must exit loop somehow.
1911  */
1912
1913 void
1914 solib_create_inferior_hook ()
1915 {
1916   /* If we are using the BKPT_AT_SYMBOL code, then we don't need the base
1917      yet.  In fact, in the case of a SunOS4 executable being run on
1918      Solaris, we can't get it yet.  current_sos will get it when it needs
1919      it.  */
1920 #if !(defined (SVR4_SHARED_LIBS) && defined (BKPT_AT_SYMBOL))
1921   if ((debug_base = locate_base ()) == 0)
1922     {
1923       /* Can't find the symbol or the executable is statically linked. */
1924       return;
1925     }
1926 #endif
1927
1928   if (!enable_break ())
1929     {
1930       warning ("shared library handler failed to enable breakpoint");
1931       return;
1932     }
1933
1934 #if !defined(SVR4_SHARED_LIBS) || defined(_SCO_DS)
1935   /* SCO and SunOS need the loop below, other systems should be using the
1936      special shared library breakpoints and the shared library breakpoint
1937      service routine.
1938
1939      Now run the target.  It will eventually hit the breakpoint, at
1940      which point all of the libraries will have been mapped in and we
1941      can go groveling around in the dynamic linker structures to find
1942      out what we need to know about them. */
1943
1944   clear_proceed_status ();
1945   stop_soon_quietly = 1;
1946   stop_signal = TARGET_SIGNAL_0;
1947   do
1948     {
1949       target_resume (-1, 0, stop_signal);
1950       wait_for_inferior ();
1951     }
1952   while (stop_signal != TARGET_SIGNAL_TRAP);
1953   stop_soon_quietly = 0;
1954
1955 #if !defined(_SCO_DS)
1956   /* We are now either at the "mapping complete" breakpoint (or somewhere
1957      else, a condition we aren't prepared to deal with anyway), so adjust
1958      the PC as necessary after a breakpoint, disable the breakpoint, and
1959      add any shared libraries that were mapped in. */
1960
1961   if (DECR_PC_AFTER_BREAK)
1962     {
1963       stop_pc -= DECR_PC_AFTER_BREAK;
1964       write_register (PC_REGNUM, stop_pc);
1965     }
1966
1967   if (!disable_break ())
1968     {
1969       warning ("shared library handler failed to disable breakpoint");
1970     }
1971
1972   if (auto_solib_add)
1973     solib_add ((char *) 0, 0, (struct target_ops *) 0);
1974 #endif /* ! _SCO_DS */
1975 #endif
1976 }
1977
1978 /*
1979
1980    LOCAL FUNCTION
1981
1982    special_symbol_handling -- additional shared library symbol handling
1983
1984    SYNOPSIS
1985
1986    void special_symbol_handling ()
1987
1988    DESCRIPTION
1989
1990    Once the symbols from a shared object have been loaded in the usual
1991    way, we are called to do any system specific symbol handling that 
1992    is needed.
1993
1994    For SunOS4, this consists of grunging around in the dynamic
1995    linkers structures to find symbol definitions for "common" symbols
1996    and adding them to the minimal symbol table for the runtime common
1997    objfile.
1998
1999  */
2000
2001 static void
2002 special_symbol_handling ()
2003 {
2004 #ifndef SVR4_SHARED_LIBS
2005   int j;
2006
2007   if (debug_addr == 0)
2008     {
2009       /* Get link_dynamic structure */
2010
2011       j = target_read_memory (debug_base, (char *) &dynamic_copy,
2012                               sizeof (dynamic_copy));
2013       if (j)
2014         {
2015           /* unreadable */
2016           return;
2017         }
2018
2019       /* Calc address of debugger interface structure */
2020       /* FIXME, this needs work for cross-debugging of core files
2021          (byteorder, size, alignment, etc).  */
2022
2023       debug_addr = SOLIB_EXTRACT_ADDRESS (dynamic_copy.ldd);
2024     }
2025
2026   /* Read the debugger structure from the inferior, just to make sure
2027      we have a current copy. */
2028
2029   j = target_read_memory (debug_addr, (char *) &debug_copy,
2030                           sizeof (debug_copy));
2031   if (j)
2032     return;                     /* unreadable */
2033
2034   /* Get common symbol definitions for the loaded object. */
2035
2036   if (debug_copy.ldd_cp)
2037     {
2038       solib_add_common_symbols (SOLIB_EXTRACT_ADDRESS (debug_copy.ldd_cp));
2039     }
2040
2041 #endif /* !SVR4_SHARED_LIBS */
2042 }
2043
2044
2045 /*
2046
2047    LOCAL FUNCTION
2048
2049    sharedlibrary_command -- handle command to explicitly add library
2050
2051    SYNOPSIS
2052
2053    static void sharedlibrary_command (char *args, int from_tty)
2054
2055    DESCRIPTION
2056
2057  */
2058
2059 static void
2060 sharedlibrary_command (args, from_tty)
2061      char *args;
2062      int from_tty;
2063 {
2064   dont_repeat ();
2065   solib_add (args, from_tty, (struct target_ops *) 0);
2066 }
2067
2068 #endif /* HAVE_LINK_H */
2069
2070 void
2071 _initialize_solib ()
2072 {
2073 #ifdef HAVE_LINK_H
2074
2075   add_com ("sharedlibrary", class_files, sharedlibrary_command,
2076            "Load shared object library symbols for files matching REGEXP.");
2077   add_info ("sharedlibrary", info_sharedlibrary_command,
2078             "Status of loaded shared object libraries.");
2079
2080   add_show_from_set
2081     (add_set_cmd ("auto-solib-add", class_support, var_zinteger,
2082                   (char *) &auto_solib_add,
2083                   "Set autoloading of shared library symbols.\n\
2084 If nonzero, symbols from all shared object libraries will be loaded\n\
2085 automatically when the inferior begins execution or when the dynamic linker\n\
2086 informs gdb that a new library has been loaded.  Otherwise, symbols\n\
2087 must be loaded manually, using `sharedlibrary'.",
2088                   &setlist),
2089      &showlist);
2090
2091   add_show_from_set
2092     (add_set_cmd ("solib-absolute-prefix", class_support, var_filename,
2093                   (char *) &solib_absolute_prefix,
2094                   "Set prefix for loading absolute shared library symbol files.\n\
2095 For other (relative) files, you can add values using `set solib-search-path'.",
2096                   &setlist),
2097      &showlist);
2098   add_show_from_set
2099     (add_set_cmd ("solib-search-path", class_support, var_string,
2100                   (char *) &solib_search_path,
2101                   "Set the search path for loading non-absolute shared library symbol files.\n\
2102 This takes precedence over the environment variables PATH and LD_LIBRARY_PATH.",
2103                   &setlist),
2104      &showlist);
2105
2106 #endif /* HAVE_LINK_H */
2107 }