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